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 |
|---|---|---|---|---|---|
Developing ASP.NET pages for mobile device browsers does not differ substantially from developing pages for desktop browsers. To help you create applications for mobile devices, ASP.NET provides a namespace devoted specifically to mobile Web development.
You can create a Web page from the create custom rendering for a control based on the requesting browser. With the adaptive architecture, you can use ASP.NET pages that inherit from the base class (rather than pages written specifically for mobile devices) and create custom adapters for ASP.NET Web server controls to render output specific to the devices that access your application.
In both cases, development follows the standard .NET event-driven model in which your application responds to user requests, button clicks, and so on.
Mobile Application Architecture
Although ASP.NET integrates technology to make ASP.NET mobile Web application development follow the same paradigm as traditional Web application development, the architecture's primary intent is not to allow you to create single pages that can target browsers in both desktop and mobile devices. You can create adapters for individual ASP.NET or for mobile Web server controls that allow these controls to render for both desktop and mobile device browsers, but the limitations of browsers on mobile devices often mean that pages designed for desktop browsers do not translate very well is usable. Additionally, for mobile devices you might choose to provide shortcuts that allow the user to fill in information with less typing because the device might be difficult to type on.
For these reasons, it is recommended that you create separate pages in your ASP.NET Web application for use in desktop and mobile device browsers. A page developed specifically for mobile device browsers allows you to break down presentation logic into smaller pieces that work better for the device's display area and input hardware. When considering building such pages, therefore, you should use mobile Web server controls if your application must support a wide range of mobile devices, support browsers that do not use HTML, or support devices with limited display and input capabilities.
Mobile Web Server Controls
The ASP.NET 2.0 System.Web.Mobile namespace is devoted specifically to mobile Web development. You can create a mobile Web page from the MobilePage base class and add mobile Web server controls from the System.Web.Mobile namespace. Mobile Web server controls have a number of specialized adapters in the framework and are therefore especially geared to developing mobile Web applications that target a wide range of mobile devices.
ASP.NET Web Server Controls and the Unified Adapter Architecture
All ASP.NET 2.0 Web server controls adhere to the unified adapter architecture. This means that all controls can render and handle any device-specific view state logic or device idiosyncrasies. Browser definition files can be found in the Browsers folder of the .NET Framework Config directory or in the App_Browsers folder of a Web application.
You can create custom adapters for each device and have the ASP.NET page framework use those adapters when a specific device accesses your page.
Choosing Custom Adapters or Mobile Controls
For most page developers, using the mobile Web server controls and creating pages that inherit from MobilePage is the recommended approach to mobile development. allows you to support new markup languages with the same controls that you are already using. For example, if you are creating an e-commerce site that supports desktop browsers as well as a large array of mobile devices, the recommended approach is to create a set of ASP.NET pages that inherit from the Page class and a separate set of pages that inherit from the MobilePage base class and use mobile controls. This provides you with mobile support without having to create custom adapters.
The mobile Web server controls also follow the unified adapter architecture, so.
A benefit of creating custom adapters for the ASP.NET Web server controls is therefore that you can use the Page base class for your Web pages and be able to take full advantage of the ASP.NET 2.0 feature set. | http://www.yaldex.com/asp_net_tutorial/html/f2bf0e0f-955c-4a75-a48f-97a01e3f4e2c.htm | CC-MAIN-2017-30 | refinedweb | 686 | 54.32 |
In route to their final storage destination on the World Wide Web, characters move through various layers of programming interfaces and can cross software and hardware boundaries. This article provides helpful hints and best practices for accurately transporting character data from browser to database
and back again.
Most operating systems, application development languages, and platforms have come a very long way in internationalization. Some things are easy, like entering your name into a Swing text field. Keyboards, input methods, and host software collaborate to create the correct characters whether your name is John, José, or (Tanaka). Unfortunately, although entering non-ASCII text in a browser can be as easy as entering it into a Swing component, accurately transmitting it over the web can be complicated. As no industry standard governs how application data should be encoded in either GET or POST commands, the trip through various layers of programming interfaces can transform character data into meaningless gibberish. Furthermore, web server and database administrators often know very little about character-encoding transformations that affect data fidelity as text moves from browser to database.
GET
Modern browsers can display most text correctly as long as the HTML page provides sufficient hints for the browser to select and use appropriate fonts and encodings to interpret the characters. The following image shows a possible display when you do not provide any character encoding information to the browser. In this case, characters are received via the HTML page without data loss but are subsequently interpreted incorrectly.
In the next image, the browser (Firefox 1.07) mistakenly interprets the file content as ISO 8859-1 encoded text, which is incorrect. Although most browsers allow a user to change or override these settings for any particular document, this expectation is unreasonable for typical users.
The text is actually UTF-8 (a Unicode encoding) text. After placing this information in the HTML code as a <meta> tag, the browser correctly displays the Japanese greeting for "Hello, World!"
<meta>
The correctly described HTML file is shown below. Notice that the <meta> tag contains a content attribute that tells the browser that the file has type text/html with charset=UTF-8. The keyword charset is used within the content attribute to communicate the HTML file's character encoding. Use language tags wherever possible so that browsers can find and utilize language-specific glyphs when appropriate. For example, both Chinese and Japanese use many of the same characters. Because glyphs differ significantly for some characters in these and other languages, language tags help browsers find the most appropriate fonts for presentation.
text/html
charset=UTF-8
charset
If you generate pages with JavaServer Pages (JSP) technology, you still must indicate the character encoding of the generated HTML page. You can do this with either the JSP page directive or with the HTML <meta> tag. The JSP page tag should be the first element of your JSP file and should contain a contentType attribute with the charset setting. The pageEncoding attribute is used by the JSP compiler to help it know the encoding of the JSP page itself.
page
contentType
pageEncoding
<%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
...
Now your pages are correctly encoded, and they communicate that information to the browser. Great, but nothing has been transmitted from the browser yet. As already shown, browsers learn a page's encoding information from charset information stored in the HTTP header or in the HTML <meta> tag. They use this same information when encoding form data for GET or POST commands they send back to a server. If an accept-charset attribute exists in the HTML form tag, browsers will use that setting instead. Again, browsers encode form data in the same encoding as the page or the form itself.
accept-charset
The following JSP shows a page that indicates that its contents are encoded as ISO-8859-1, a commonly used character encoding that handles languages and scripts used in many countries of Western Europe and the Americas. The page generates an HTML form that asks for a user's name. On submission, the same page processes the incoming GET command and prints a greeting to the user indicated in the NAME parameter.
NAME
<% @page pageEncoding="ISO-8859-1" contentType="text/html; charset=ISO-8859-1" %>
<html lang="en">
click the Submit button. The browser creates and uses the following URL to send information to the server:
John
Fine so far. Now, type in José and click the Submit button. The resulting URL is shown again below:
José
Although the resulting NAME parameter looks a little different, it is correct. The %E9 string is a URL-encoded character: the hexadecimal integer value of the character's codepoint in the ISO 8859-1 charset. Servers that expect GET and POST data in the 8859-1 charset have no problem decoding this URL-encoded entity.
%E9
In brief, URL-encoding is a web standard for URLs that requires all non-ASCII characters and specific ASCII characters to be encoded as hexadecimal strings in the form %HH. Unfortunately, that same standard does not prescribe which charset to use when encoding the data.
%HH
What happens when the page's charset does not contain a character entered into the form? Imagine that a user in Japan, Korea, or China enters their name into the same JSP page shown above. The characters most likely do not appear in the ISO 8859-1 encoding. Encoding them to ISO 8859-1 will present a significant problem to the browser, and each browser handles this problem differently.
Given the Japanese name (Tanaka), the Firefox version 1.07 browser produces the following GET URL:
This URL is odd at first glance, but you can decipher its meaning quickly. First, the Firefox browser knows that it can't represent in the 8859-1 charset
it doesn't even try. Instead, it encodes the characters as numeric character references. Other browsers may behave differently, opting to generate question marks or even to prevent their input entirely. In this case, however, each character is encoded into &#D; form, where D represents the character's decimal codepoint value in the Unicode character set. The character has value 30000. has value 20013. Creating numeric character references, we produce the following parameter string:
&#D;
D
NAME=田中
Now the URL-encoding takes place, to convert the special characters
&, #, and ; characters into their %HH equivalents.
NAME=%26%2330000%3B%26%2320013%3B
If your JSP page retrieves this parameter and simply returns it to the browser, there is no apparent data loss. Although the page's character encoding is still 8859-1, the browser understands numeric character references too, and it will do its best to display the Japanese appropriately. However, there is still a problem lurking here. Although server-side code that processes GET and POST commands typically understand URL-encoded strings, they rarely understand numeric character references. Most servlet code that reads the previous NAME parameter will decode the string to find 田中 and will not know that this represents anything other than the literal characters. In other words, the real characters for won't be discovered unless you've intentionally planned for this situation. Don't send numeric character references instead of actual codepoint or encoding values. Doing so would allow potential data loss as the character continues through the application.
田中
To remedy this problem, always select an HTML page encoding that can handle all characters that you intend to process. If you expect to have multilingual users and hope to process multiple scripts, use a character encoding that represents those scripts. UTF-8 is a Unicode character encoding, and it can correctly represent all characters in active use throughout the world. Using UTF-8 in the page instead of 8859-1, the browser produces a different URL.
This is a correctly encoded NAME parameter that uses the UTF-8 charset. UTF-8 encodes with 3 bytes per character. Since each byte has a value outside the ASCII range, the browser URL-encodes the values, producing the %HH form for each byte as shown above. A server that expects UTF-8 form data will be able to handle the parameter correctly.
Although current browsers take hints from the page or form encoding and send form data back to the server in the same encoding, most web servers remain blissfully unaware of the character-encoding choice. They typically assume that the encoding is ISO-8859-1. Even if an application goes through the trouble to URL-encode a GET parameter in UTF-8 , the server (let's say Tomcat 5.5.9 or Sun Java System Application Server 8.1) will assume encoding 8859-1. The result is that text data becomes mangled almost immediately as it travels through the various tiers of even a simple web-based application.
When you change the previous JSP technology code to use the UTF-8 charset, the new code appears as follows.
<%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>
<html>
>
Now type in "José" and submit. The GET URL will look like this.
The %C3%A9 is the URL-encoded UTF-8 representation of José. No problem. The browser takes its hint from the contentType setting where UTF-8 is specified as the character encoding. The browser displays the following text.
%C3%A9
Notice the response text: Hello, José! That's not right. What happened? Although the browser is correctly sending the GET data, the web server incorrectly assumed character-encoding 8859-1 as it read the NAME parameter Jos%C3%A9 from the URL. From its perspective, the %C3 entity represents the encoded value 0xC3 (Ã) in ISO-8859-1. %A9 is 0xA9 (©) in ISO-8859-1. Hmmph
but the content type was explicitly set in the JSP tag!
Hello, José!
Jos%C3%A9
%C3
0xC3
%A9
0xA9
There is no published standard that prescribes how to communicate charset choice for GET and POST data. How should it be resolved? Some servers do try to address this. Setting in the sun-web.xml file. The correct interpretation of the URL is shown in the following image.
URIEncoding="UTF-8"
<parameter-encoding
What if you want to POST non-ASCII data? All is well since you set that URIEncoding flag, right? Wrong. Tomcat doesn't use the URIEncoding flag for POSTed form data. So, what does it use? ISO-8859-1.
URIEncoding
So now, you're back to where you started, and the simple application still greets Mr. ç°ä, instead of Mr. . Not good. Sun's application server, however, does correctly interpret both GET and POST data after setting the parameter-encoding tag as shown earlier, so this coding works well for users on that system.
parameter-encoding.
<context-param>
<param-name>PARAMETER_ENCODING</param-name>
<param-value>UTF-8</param-value>
</context-param>
Add the following code just before reading any parameters in the previous
JSP file.
String paramEncoding = application.getInitParameter("PARAMETER_ENCODING");
request.setCharacterEncoding(paramEncoding);
From a control servlet, you can read the parameter during servlet initiation and set the encoding before processing the parameters:
public class MsgHandler extends HttpServlet {.
Assuming your data has survived so far through the data-mangling gauntlet of browser encoding and web server processing, the database represents the last transformation hurdle for character data. To safely place data into the database and retrieve it unscathed, you must configure the database system to store data in a character encoding that can represent all the characters supported by the browser and your middle-tier business logic. Since UTF-8 has been used so far, it makes sense to continue that choice in the database. Otherwise, data will be irreversibly lost when you try to store text that contains characters that don't exist in the database's character encoding choice.
The following image shows such data loss (when the database character encoding is not a superset of the browser and middle-tier charset). In this situation, the browser and middle tier use UTF-8, but the database is configured for ASCII.
Once you update your database character set to UTF-8, however, data migrates from the browser to the database and back again with complete fidelity.
Most modern database systems support Unicode. Two popular relational database products, Oracle and MySQL, both provide full UTF-8 and UTF-16 encoding support in their most recent versions. If you have the opportunity to set up your application's database schema, seriously consider UTF-8 as your database character encoding. If you're in the situation that your database uses a different, more limited character encoding, and you experience data loss as described, you should consider migrating the encoding to UTF-8. Consult your database vendor for detailed instructions about performing the migration.
The trip from browser to database has several points of potential data loss. Text data often transforms through three or more charset encodings, and each transformation can cause irreversible data loss. To avoid this problem, follow these rules:
For more information, please see the following materials: | http://java.sun.com/developer/technicalArticles/Intl/HTTPCharset/ | crawl-002 | refinedweb | 2,179 | 54.42 |
In this user guide, you will learn how to use the AWS IoT core MQTT using an ESP32 to publish sensor readings to AWS MQTT. Through AWS IoT core, we’ll show you how to publish sensor readings to Amazon web services using Arduino IDE over MQTT protocol. The sensor readings will be displayed in a dashboard. Most importantly, you can access this sensor data from anywhere in the world.
.
Previously, we controlled the ESP module’s outputs through applications such as Telegram, Google Firebase, Blynk App, and Arduino IoT Cloud.
- Getting Started with Arduino IoT Cloud with ESP32: Send Sensor Readings and Control Outputs
This time we will look into another great application Amazon Web Services through which we will publish sensor readings obtained from the DHT22 sensor connected with the ESP32 development board.
We will require the following for our project:
Hardware Required:
- ESP32
- DHT22 Sensor
- Connecting Wires
- Breadboard
Software Required:
- Amazon Web Services
- Arduino IDE
AWS IoT Core
With Amazon Web Services, the user is granted inexpensive cloud computing services which are reliable and interactive. Although this web service is free to join, you will have to pay for any services which you use. For the user, it becomes extremely fun and easy to use this application to build IoT projects from anywhere over the internet. Only the Amazon web service account and a steady internet connection in your device (smartphone, laptop, tablet, etc.) are a requirement.
Getting Started with AWS IoT
Working in the Amazon Web Services is very simple and easy. Thus, follow the steps given below to successfully set up the ESP32 board and start with your very first project.
Firstly, type in your browser search tab and press enter. This will open the following homepage of AWS. if you do not have an account click ‘Create an AWS Account’ otherwise click ‘My Account.’
The following page opens up. Proceed with your account details or click ‘Sign in to an existing AWS account.’
AWS IoT Core
After you have successfully signed in, the AWS Management Console window will open. In the services search tab at the top write ‘IoT core’ and press enter. Choose IoT core as shown in the picture below.
Opening up the IoT core, the following window appears. This is the IoT core homepage. Go to ‘Monitor’ to open the dashboard.
Creating a Thing
To successfully create a thing associated with our project we will have to follow three main steps in order. These are:
- Specifying thing properties
- Configuring device certificate
- Attaching policies to certificate
First, to create a Thing go to Manage > Things. This opens the Things interface. Click ‘Create things’ to proceed further.
The following window will open. Select ‘create a single thing.’ Then click ‘Next.’
Specify Thing Properties
Now, give a name to your thing. You can use any name according to your preference. In our case, we have specified it as ‘DHT22_Sensor_Data.’ Leave the other properties as default. Scroll down and click ‘Next’ to move to the next step.
Configure Device Certificate
Next, select the options as shown below to generate the certificate associated with the thing.
Attach Policy
To attach a policy with our certificate click ‘Create policy.’
A new tab will open to create the policy. Give a name to your policy and add statements. In our case we have named the policy as ‘DHT22_Policy’ and set * signs in both Action and Resource ARN to allow ALL. Click ‘Create’ to finish creating the policy.
You will get the notification of successfully creating the policy.
Close this tab and go back to Create single thing tab. You will notice that the DHT22_Policy has already been attached with our thing. Click ‘Create thing’ to finish the process of creating the thing.
Downloading Certificates and Keys
Now we will have to download the key files for our certificate. These certificates will be used to communicate with the AWS server for authentication. Download the device certificate and the private key. Keep these safe with you and do not share with anyone otherwise the security of your project might get compromised.
Scroll down and you will be able to find the Root CA certificates. Download and save Amazon Root CA 1. We will use it in a later step. After the downloading is complete click ‘Done.’
Now, we will get the notification of successfully creating the thing and creating its certificate. You will notice that ‘DHT22_Sensor_Data’ thing has been created.
Installing Required Libraries
Now, let’s move to the next step. We will be required to download two libraries for this project. These include:
- Hornbill Examples
- DHT sensor library
- We will use GitHub to download the libraries. To download Hornbill examples, click here. Download the zip file as shown below.
Click the Code button and go to the Download Zip option as highlighted in the figure. Your zip file will get downloaded to your computer right away.
Click the Code button and go to the Download Zip option as highlighted in the figure. Your zip file will get downloaded to your computer right away.
After both libraries are downloaded, place them in a folder ‘AWS ESP32 project.’ Then extract both of them. Rename the DHT-sensor-library-master as ‘DHT-sensor-library.’ Open this folder. Inside it you will find the following files.
Delete the following files: DHT_U.cpp and DHT_U.h
These are also highlighted in the picture. For our project, we do not require these files. Copy this folder and go to Documents > Arduino > libraries and paste it inside the Arduino libraries folder.
Now go to Hornbill-Examples-master > arduino-esp32 > AWS_IOT.
Copy this AWS_IOT file and place it in the Arduino libraries folder.
Modifying the aws_iot_certificates.c according to the Thing
Now, we will modify the AWS_IOT file which we placed in the Arduino library according to certificates and keys associated with our Thing. First go to AWS_IOT > src > aws_iot_certificates.c and open it in MS Word. It will look something like this:
We will add the Amazon root CA1, the device certificate and the private key which we previously saved, inside this file. Open the Amazon root CA1 which we saved. As it is a .pem file so we will use a file converter to open the document. We are using the following website:. This will open the .pem file and you will be able to access the data inside it. Copy the Amazon root CA1 data which you obtain and head over to the aws_iot_certificates.c file which we opened in MS Word. Locate const char aws_root_ca_pem[] inside the file.
In the const char aws_root_ca_pem[], remove all the ‘XXXX’ and paste the root CA1 data inside it. Make sure the ‘\n\’remains after every line.
Likewise, we will add the private key and the device certificate in the aws_iot_certificates.c file as well.
First, to add the private key open the private key .test file which you saved. Copy and paste the contents of that file in the const char private_pem_key[]. Make sure to add ‘\n\’ after every line.
Similarly, to add the device certificate, copy the contents from the device certificate file which we saved and paste it in the const char certificate_pem_crt[]. Make sure to add ‘\n\’ after every line.
AWS IoT ESP32 Arduino Sketch
Open your Arduino IDE and create a new file. Copy the code given below in that file. You need to enter your network credentials. Additionally, you also have to provide your Client ID, MQTT topic, and AWS host.
#include <WiFi.h> #include "DHT.h" #include <AWS_IOT.h> #define DHT_PIN 27 #define DHT_TYPE 22 const char* ssid = "*********"; //Write your SSID const char* password = "**********"; //Write your password #define CLIENT_ID "Temp_Humidity" #define MQTT_TOPIC "$aws/things/DHT22_Sensor_Data/shadow/update" #define AWS_HOST "a1722qfsc********-ats.iot.ap-south-1.amazonaws.com" DHT dht(DHT_PIN,DHT_TYPE); AWS_IOT aws; void setup(){ Serial.begin(115200); Serial.print("Initializing...."); WiFi.begin(ssid,password); Serial.print("Connecting to WiFi..."); while(WiFi.status()!= WL_CONNECTED){ Serial.print("."); delay(300); } dht.begin(); Serial.print("Starting connection with AWS"); if(aws.connect(AWS_HOST,CLIENT_ID)==0){ Serial.print("Connected to AWS!"); } else{ Serial.print("Connection Failed! Check AWS HOST and Client ID"); } } void loop(){ float hum = dht.readHumidity(); float temp = dht.readTemperature(); if (isnan(hum) || isnan(temp) ){ Serial.println(F("Failed to read from DHT sensor!")); return;} else{"); } } delay(1000); }
How does the Code Work?
Now, let us understand how each part of the code works.
Including Libraries
Firstly, we will include the relevant libraries which are necessary for this project. We are using three libraries: WiFi.h, AWS_IOT.h and DHT.h
WiFi.h library is used to connect our ESP32 module with the local WIFI network. The other libraries are the ones that we previously installed and will be required for the AWS and sensor functionality.
#include <WiFi.h> #include "DHT.h" #include <AWS_IOT.h>
Defining DHT Sensor
The following lines of code will specify the type of DHT sensor and the GPIO pin of the ESP32 board which we will connect with the data pin of the sensor.
#define DHT_PIN 27 #define DHT_TYPE 22 DHT dht(DHT_PIN,DHT_TYPE);
Defining Network Credentials
Next, we will create two global parameters of type char which will hold the SSID and password. Replace the ‘*’ with your network credentials.
const char* ssid = "********"; //Write your SSID const char* password = "***********"; //Write your password
Defining AWS Parameters
Now, we will specify the client ID which we will call ‘Temp_Humidity.’ We are using MQTT protocol to transfer data from our ESP32 board to the Amazon web services. For MQTT topic and AWS host we will use the values which will be accessed from the AWS web site.
Go to AWS IoT > Manage > Things > DHT22_Sensor_Data > Classis Shadow. Scroll down and click MQTT topic. Copy the ‘update’ MQTT topic associated with the ‘Publish’ action and define it in the Arduino sketch as ‘MQTT_TOPIC.’
Likewise, the AWS host can be found if you go to AWS IoT > Settings. Copy the device data endpoint and define it as AWS_HOST in the Arduino sketch.
#define CLIENT_ID "Temp_Humidity" #define MQTT_TOPIC "$aws/things/DHT22_Sensor_Data/shadow/update" #define AWS_HOST "a1722qfsc******-ats.iot.ap-south-1.amazonaws.com"
Creating AWS_IOT object
We will also create an AWS_IOT object called ‘aws’ which we will use later on in the program code.
AWS_IOT aws;
setup()
Inside the setup() function, we will start the serial communication.
WiFi.begin(ssid,password); Serial.print("Connecting to WiFi..."); while(WiFi.status()!= WL_CONNECTED){ Serial.print("."); delay(300); }
After the connection will be established, we will initiate the connection with the DHT sensor using dht.begin()
dht.begin();
The following section of code will check for a successful connection with AWS by using aws.connect() and the AWS host and client ID parameters. When the ESP32 board makes a succesful connection with AWS the serial monitor will display “Connected to AWS.” Otherwise, it will display a failed connection message.
Serial.print("Starting connection with AWS"); if(aws.connect(AWS_HOST,CLIENT_ID)==0){ Serial.print("Connected to AWS!"); } else{ Serial.print("Connection Failed! Check AWS HOST and Client ID"); }; }
Else, we will create a string variable ‘temp_humidity’ that will publish the temperature and humidity sensor readings to AWS via MQTT protocol."); }
Subscribing Thing on AWS MQTT
To subscribe the DHT22_Sensor_Data Thing on AWS go to AWS IoT > Test. In the Topic filter search bar, copy and paste the MQTT topic for publishing. Then click Additional configuration.
Now change the MQTT payload display to ‘Display payloads as strings’ and hit Subscribe to finish the procedure.
We have successfully subscribed our Thing with Amazon Web Services for publishing data..
In your Arduino IDE, open up the serial monitor and you will be able to see the status of your WIFI and the AWS connection.
Shortly afterward, you will be able to view the temperature and humidity readings which will simultaneously get published in the AWS via MQTT protocol.
Open the AWS publish page to view the sensor data being published.
We will shortly update the article with a demo video.
Conclusion
In conclusion, we were able to learn about Amazon Web Services (AWS) and how to use AWS IoT core to get sensor readings. This was accomplished via MQTT protocol. Using AWS MQTT, we can subscribe to sensor readings topics published by various IoT nodes. Similarly, we can also publish on specific topics from the AWS IoT core portal. | https://microcontrollerslab.com/aws-iot-mqtt-esp32-publish-sensor-readings/ | CC-MAIN-2021-39 | refinedweb | 2,058 | 67.65 |
This plugin provides MJPEG video streaming for Flutter. It uses ipcam-view library for Android part, and a custom implementation for iOS part.
This is just a proof-of-concept, rather than a full-fledged plugin. Pull requests are welcome.
See the
example for details.
When you try this plugin in your own app, the compiler will complain about duplicate value in
AndroidManifest.xml. Add the following to
<application> tag of your
AndroidManifest.xml:
tools:replace="android:label"
and also this to the top-most
<manifest> tag:
xmlns:tools=""
example/lib/main.dart
import 'package:flutter/material.dart'; import 'package:mjpeg/mjpeg: const Text('MJPEG live view'), ), body: Center( child: RaisedButton( onPressed: () { Mjpeg.startLiveView(url: ""); }, child: const Text('Live view'), ), ), )); } }
Add this to your package's pubspec.yaml file:
dependencies: mjpeg: ^0.0.3
You can install packages from the command line:
with Flutter:
$ flutter packages get
Alternatively, your editor might support
flutter packages get.
Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:mjpeg/mjpeg/mjpeg.dart.
Run
flutter format to format
lib/mjpeg. | https://pub.dartlang.org/packages/mjpeg | CC-MAIN-2019-18 | refinedweb | 185 | 53.27 |
NAME
strsep - extract token from string
SYNOPSIS
#include <string.h> char *strsep(char **stringp, const char *delim);
DESCRIPTION
The strsep() function returns the next token from the string stringp which is delimited by delim. The token is terminated with a ‘\0’ char‐ acter and stringp is updated to point past the token. The strsep() function returns a pointer to the token, or NULL if delim is not found in stringp.
NOTES
The strsep() function was introduced as a replacement for strtok(), since the latter cannot handle empty fields. (However, strtok() con‐ forms to ANSI-C and hence is more portable.) BSD 4.4 index(3), memchr(3), rindex(3), strchr(3), strpbrk(3), strspn(3), strstr(3), strtok(3) | http://manpages.ubuntu.com/manpages/gutsy/pt/man3/strsep.3.html | CC-MAIN-2015-18 | refinedweb | 119 | 64.41 |
02 December 2011 09:47 [Source: ICIS news]
SINGAPORE (ICIS)--Shanghai Petrochemical Company (SPC), a subsidiary of Sinopec, is planning to process 12m tonnes of crude in 2012 at its 14m tonne/year refinery in ?xml:namespace>
SPC, which mainly processes crude from the Middle East and
The company is expected to finish building a 3.9m tonne/year residual hydrogenation unit and a 3.5m tonne/year residual fluid catalytic cracker at the same site in 2012, the source said.
At the same time, SPC will complete the construction of a few secondary units, such as a 1.5m tonne/year
The financial details of the new plants are unknown.
In addition, the company will restart its 2.5m tonne/year crude distillate unit (CDU) in late 2012 after debottlenecking, according to the source.
For more on naphtha, | http://www.icis.com/Articles/2011/12/02/9513370/chinas-shanghai-petrochemical-to-raise-crude-output-by-10-in.html | CC-MAIN-2014-49 | refinedweb | 139 | 65.62 |
Str
Calling Action on form load - Struts
. Even if you want to use the tag with a simple Action that does not require input... not want an action to trigger form validation, you need to remember to add...Calling Action on form load Hi all, is it possible to call
Struts 2 Redirect Action
Struts 2 Redirect Action
In this section, you will get familiar with struts 2 Redirect
action and learn to use it in the struts 2 application.
Redirect After Post:
This post Class and forward a
jsp file through it.
What is Action Class?
An Action
Struts Forward Action Example
Struts Forward Action Example
.....
Here in this example
you will learn more about Struts Forward Action... an Action Class
Developing the Action Mapping in the struts-config.xml-Configuration file).
Here the Dispatch_Action... Struts Dispatch Action Example
Struts Dispatch Action <p>hi here is my code in struts i want to validate my...;!--
This file contains the default Struts Validator pluggable validator... in this file.
# Struts Validator Error Messages
errors.required={0
Take input in batch file
Take input in batch file How to take input in batch file?
Thanks
Hi,
You can use the following line of code in your batch file:
set /p myfile=Enter file name:
In the above code myfile variable will hold the data
Implementing Actions in Struts 2
Implementing Actions in Struts 2
Package com.opensymphony.xwork2 contains the many Action classes and
interface, if you want to make an action class for you...;roseindia" extends="struts-default">
<action name="
Introduction to Action interface
Introduction To Struts Action Interface
The Action interface contains the a single method execute(). The business
logic of the action is executed within... from user.
NONE- If the execution of action is successful but you do
not want
No action instance for path
struts@roseindia.net
*/
/**
* Struts File Upload Action Form...;
<head>
<title>Struts File Upload and Save...;
<body>
<a href ="FileUploadAndSave.jsp">Struts File Upload<
multiple configurstion file in struts - Struts
multiple configurstion file in struts Hi,
Please tell me the solution.
I have three configuration file as 'struts-config.xml','struts...',
'index3.jsp' .I want to know that when any action occurs in these jsp pages
Struts File Upload and Save
Action Class
In our previous article entitled "Struts File
Upload... in the struts-config.xml
file:
<action
path... Struts File Upload and Save
Input and Output package
created two new objects directly to use this statements.
/* input and output... am using this, it is showing an error."cannot find symbol..input"
So,i want...Input and Output package Hi guys,
My professor used input and output
Struts 2 action-validation.xml not loading
Struts 2 action-validation.xml not loading Hi All,
I am getting... error
SERVER : Caught exception while loading file package/action-validation.xml
Connection refused: Connect - (unknown location)
The path of my action
Struts File Upload Example
entry in the struts-config.xml
file:
<action...
Struts File Upload Example
In this tutorial you will learn how to use Struts to
write
How to take input by user using jDialogue and use that input
has primary key emp_id ).
How can i do this ?
I just want to use the Input...How to take input by user using jDialogue and use that input I am using NetBeans
i have a 'Search by employee id' button .
I want when user click
input output
.
FileInputStream
It contains the input byte from a file.../O is
used to input any thing by the keyboard or a file. This is done using... you will learn how to write java program to
read file line by line. We will use
struts
struts <p>hi here is my code can you please help me to solve...;
<p><html>
<body></p>
<form action="login.do">
<pre>
user name:<input type="text" name="uname"/> 2 File Upload
Struts 2 File Upload
In this section you will learn how to write program in
Struts 2 to upload the file... be used to upload
the multipart file in your Struts 2 application. In this section you
how to pass input from radio button to jsp page
are matched from database. I want to pass the selected value in
Struts Action FormBean
and then retrive data to perform operation in execute() method in
Struts Action...how to pass input from radio button to jsp page hi..
the code below2.2.1 tabular Input example
like cart.
The Interceptor and action mapping is in the struts.xml file.
...struts2.2.1 tabular Input example
In this example, We will discuss about the Tabular Input validation using
struts2.2.1.
In this example,We validate
Struts Action Chaining
Struts Action Chaining Struts Action Chaining
Struts 2 Hello World Annotation Example
we are using Annotations to configure the
HelloWorld action class.
We use... World application in Struts 2 version 2.3.15.1.
We will use the Eclipse IDE... the action. The Convention Plugin was first added in the
Struts version 2.1
Struts 2 double validator
Struts 2 double validator
The Double validator of Struts 2 Framework checks if
the given input is double... to use double validator check the input range.
Follow the steps to develop double
The password forgot Action is invoked when you forgot your password and want to recover the password. The
forgot
Jakarta Struts & Advanced JSP Course
Using Struts actions and action mappings to take control of ....
To use JSTL and Struts custom tags to build robust and reusable JSP...)
Jakarta Struts
Action Mappings
Java Beans in Struts
Interview Questions - Struts Interview Questions
application.
Action are mapped in the struts configuration file... with the requested action. In the Struts framework this helper class... operation. the Struts Action class contains several methods, but most important
Struts Tutorials
up Apache Struts to use multiple configuration files. You'll learn about... struts-config.xml file for an existing Struts application into multiple... application programming.With the Validator, you can validate input in your Struts
Jsp Action Tags
Jsp Action Tags how can i use jsp forward action tag?i want examples
How to use JAR file in Java
to digitally sign the JAR file. Users who want to use the secured file can check... do not use JAR file, then they will have to download every single file one... file - jar cf jar-file input-file(s)
View the contents of a JAR file
I want detail information about switchaction? - Struts
I want detail information about switch action? What is switch action in Java? I want detail information about SwitchAction
how to use ajax in html file
how to use ajax in html file <!DOCTYPE html PUBLIC "-//W3C//DTD...;
<form name="frm" method="get" action="InsertServlet...;
<label>Name</label>
<input
Struts 2 Training
class and one can input properties by using any JavaBean directly to the action...
Struts 2 Training
The Struts 2 Training for developing enterprise applications with Struts 2 framework.
Course
Struts file uploading - Struts
Struts file uploading Hi all,
My application I am uploading files using Struts FormFile.
Below is the code.
NewDocumentForm... when required.
I could not use the Struts API FormFile since
Struts Configuration file - struts.xml
Struts Configuration file - struts.xml
... explains you how best you can use the struts.xml file for you
big projects.
The struts.xml File
The Struts 2 Framework uses a configuration file (struts.xml
Struts Articles
the input.
Extending Struts
In this article, we will use... application. The example also uses Struts Action framework plugins in order to initialize the scheduling mechanism when the web application starts. The Struts
Action Configuration - Struts
Action Configuration I need a code for struts action configuration in XML
STRUTS
STRUTS 1) Difference between Action form and DynaActionForm?
2) How the Client request was mapped to the Action file? Write the code and explain
Aggregating Actions In Struts Revisited
Aggregating Actions in Struts , I have given a brief idea of how to create action aggregations. An action aggregation is a grouping of a set of related actions...Aggregating Actions In Struts Revisited
How to read the contents in a file which is of input type file
-data" ACTION="upload">
File to upload: <INPUT TYPE=FILE<...How to read the contents in a file which is of input type file I have a jsp page wherein i have to passs the file as input and read the contentsn
Action tag - JSP-Servlet
Action tag Hello,
I want to help ....i hav one feedback form there is action ,
..
can i use two action at the same form because i want... action="services.html " but it only shows html page bt does not submit my data
Struts Action Class
Struts Action Class What happens if we do not write execute() in Action class
jar file not reading input from serial port
jar file not reading input from serial port i used a coding... when i execute thru jar file. but when i execute thru netbeans, data is received...);
} catch (PortInUseException e) {
System.out.println("port in use");
}
try
How to use session in struts 1.3
How to use session in struts 1.3 i want to know how to use session in Struts specially in logIn authentication
input - Java Beginners
input i want to know how to take value from user in core java.help me soon. Hi Friend,
There are lot of ways to input data.You can use... to input the data from the command prompt.
Try the following code to input name
Struts Action Classes
Struts Action Classes 1) Is necessary to create an ActionForm to LookupDispatchAction.
If not the program will not executed.
2) What is the beauty of Mapping Dispatch Action
iPhone Input Field, iPhone Input Field Tutorial
the users. In iPhone application we can use Text Field to take the input. ...
This is a very simple "iPhone input field" example that will show you how to use.... Open input_fieldViewController.xib file that resides in resources folder
3is
Testing Struts Application
started on your own application, copy the struts-blank.war to a new WAR
file... Reading:
Struts in Action .
by
Ted Husted
( Manning press/ DreamTech...Testing Struts Application
Standard Action "jsp:plugin"
Standard Action <jsp:plugin>
In this Section, we will discuss about standard action "jsp:plugin" & their
implementation using a example.
The <jsp:plugin> action is use to download a plugin (an Applet or a Bean
Action classes in struts
Action classes in struts how many type action classes are there in struts
Hi Friend,
There are 8 types of Action classes:
1.ForwardAction class
2.DispatchAction class
3.IncludeAction class
4.LookUpDispatchAction
Struts2.2.1 Action Tag Example
the Action tag in the
Struts2.2.1 --
First we create a JSP file named...;/body>
</html>
The Struts mapping file Struts.xml...Struts2.2.1 Action Tag Example
The Action tag is used to call action
Struts Guide
from
scratch. We will use this file to create our web application. -
struts..., Action, ActionForm and struts-config.xml are the part of
Controller... the official site of
Struts. Extract
the file ito
Java - Struts
in struts-config file i wrote the following action tag... doubt is when we are using struts tiles, is there no posibulity to use action class.
if i wrote 'type' attribute in action tag, it won't work., how can i use
calculation after if. user input
addition
5 errors found:
File: C:\Users\
Error: variable appleCost might not have been initialized
File: C:\Users\
Error: variable carrotCost might not have been... user input????
My apologies
good evening peoples
Once again I am
Struts2.2.1 file upload example.
Struts2.2.1 file upload example.
In this example, you will see how to upload file in struts2.2.1. Here, we are
using a struts2.2.1 file tag for uploading a file. Struts2.2.1 utilizes the service of File Upload Interceptor to add
attribute in action tag - Java Beginners
attribute in action tag I'm just a beginner to struts... used with the action class. But i`m not clear about the attribute tag(attribute="bookListForm")? could you pleas explain me the use of this tag
want to insert values in drop down menu in struts1.3
want to insert values in drop down menu in struts1.3 I am using...>
<html:errors/>
<html:form action...:root>
struts-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
action Servlet - Struts
action Servlet What is the difference between ActionServlet ans normal servlet?
And why actionServlet is required
Input And Output
byte from a file and implements an
input stream... the file or
keyboard in command line. This program illustrates you how to use... the standard I/O is
used to input any thing by the keyboard or a file. This is done using
java struts error - Struts
java struts error
my jsp page is
post the problem...*;
import javax.servlet.http.*;
public class loginaction extends Action{
public... THINK EVERY THING IS RIGHT BUT THE ERROR IS COMING I TRIED BY GIVING INPUT first example - Struts
Struts first example Hi!
I have field price.
I want to check require and input data type is int.
can you give me an example code of validation.xml file to resolve it?
thanks you so much! Hi friend,
Plz specify
Writing action classes in struts2.2.1
Writing action classes
Action Classes
AdmissionAction.java- It action...(admissionModel);
return SUCCESS;
}
else{
return INPUT...);
return SUCCESS;
}
else{
return INPUT;
}
}
@Override
;
Struts MappingDispatch Action...
Developing the Action Mapping in the struts-config.xml
Here, we...="/pages/MappingDispatchAction.jsp">Struts File
Upload</html
Struts MappingDispatchAction Example
/MappingDispatchAction.jsp">Struts File
Upload</html:link>
<... Struts MappingDispatchAction Example
Struts MappingDispatch
namespace in struts.xml file - Struts
in struts.xml file
Struts Problem Report
Struts has detected an unhandled exception:
Messages: There is no Action mapped for namespace / and action name....
--------------------------------------------------------------------------------
Stacktraces
There is no Action mapped for namespace
html input passing to jsp method
html input passing to jsp method i want code in which jsp method takes html input value which is in same page......
<html>
<head>...;input
<input type="text" name
struts - Struts
the struts.config.xml file
to determine which module to be called upon an action request.
Struts only reads the struts.config.xml file upon start up.
Struts-config.xml
Action Entry:
Difference between Struts-config.xml
How to use random access file
How to use random access file
In this section, you will learn the use...(file, "r");
and if you want to perform write operation with RandomAccessFile... specified
location in a file. Here data can be read from or written to in a random
HTML Action attribute - Java Beginners
-emp_event.java
In emp_event.jsp
I have form tag in jsp file as below
In action Attribute I want to give emp_event.java class.
But When I run I am...HTML Action attribute I have folder structure like
Advertisements
If you enjoyed this post then why not add us on Google+? Add us to your Circles | http://roseindia.net/tutorialhelp/comment/82171 | CC-MAIN-2015-48 | refinedweb | 2,504 | 67.86 |
Is it possible to add/retrieve performance related information to/from a dump?
My company is working with multithreaded processes. Sometimes it happens that a particular process (*.exe file) is taking a lot of CPU for quite a long time. When that happens, a dump is taken (using
procdump -ma <PID>) and this is sent to support, but as far as I know this dump does not contain performance related information, which makes it very difficult to know which is the thread which is taking all the performance.
Am I wrong and is there any performance related information inside the dump (if yes, please tell me how I can retrieve it), or are there ways to add this information to the dump?
See also questions close to this topic
-.
- In Tests none of the threads execute the method
I got a project, but I see difficulties. This is the project(4 files). I am worried about this test `
void areAllPeopleWithDistinctTicket() throws InterruptedException { int numberOfPeople = 50; TicketManager t = TicketManager.getTicketManager(numberOfPeople); Set<Integer> persons = new HashSet<>(); t.start(); for (Person person : t.getPersons()) { if(!persons.add(person.getTicketNumber()) && person.getTicketNumber()!=null){ fail("There are people with same tickets"); } } }
When I test it, it shows me in the console that all tickets are SoldOut and none of the people are on the bus. `
Name : Person 1 | Ticket: SoldOut Name : Person 2 | Ticket: SoldOut Name : Person 3 | Ticket: SoldOut Name : Person 4 | Ticket: SoldOut Name : Person 5 | Ticket: SoldOut Name : Person 6 | Ticket: SoldOut Name : Person 7 | Ticket: SoldOut Name : Person 8 | Ticket: SoldOut Name : Person 9 | Ticket: SoldOut Name : Person 10 | Ticket: SoldOut Name : Person 11 | Ticket: SoldOut Name : Person 12 | Ticket: SoldOut...
`
I will be happy if someone can explain me why is this happening and provide some solution to this.
- How can I tell if numpy is using threads?
I wan't to know if numpy is using threads over the available cores on my system. I know MATLAB does this under the hood. But is there any sure fire way I can find out if numpy is running threaded. My understanding is that it can, as Pythons GIL no longer applies. Is there anyway I can interrogate numpy either statically or at run-time to find whats going on?
- Loop in thread not exiting when flag is set
I'm trying to exit out of a message loop in Java (JNA) by setting a flag, but it's not working.
Here's my code:
public class MyClass() { private class MyInnerClass() implements Runnable { @Override public void run() { MSG msg = new MSG(); while(!quit && user32.GetMessage(msg, null, 0, 0) > 0) { user32.TranslateMessage(msg); user32.DispatchMessage(msg); } System.out.println("Exited message loop!"); } } // MyInnerClass private volatile boolean quit; private final User32 user32; public MyClass() { quit = false; user32 = User32.INSTANCE; Thread myThread = new Thread(new MyInnerClass()); myThread.start(); } public void quit() { System.out.println("Entered quit()!"); quit = true; } } // MyClass
The method
quit()is called in a callback that happens somewhere else in the code.
The message
Entered quit()!shows on the screen, but the message
Exited message loop!doesn't, and the thread keeps running.
Why is the message loop not stopping when I set
quitto
true?
- Will a JavaScript environment eventually recover after changing the [[Prototype]] of an object?
So, I've read the MDN disclaimers and warnings, I've read a great answer on the subject, but there's still something I want to know. This question actually came from an answer I gave to another question, here.
Let's say I decide to do the dirty deed. Something that I will regret for the rest of my life. Something that will stain me with shame forever and dishonor my family name. A purposeful, deliberate ending of --
Alright, enough of that. Anyway, here it is:
let proto = Object.getPrototypeOf(Function.prototype); Object.setPrototypeOf(Function.prototype, { iBetterHaveAGoodReasonForDoingThis : "Bacon!" }); //just to prove it actually worked let f = (function(){}); console.log(f.iBetterHaveAGoodReasonForDoingThis); // Quick, hide the evidence!! Object.setPrototypeOf(Function.prototype, proto);
Basically, what I did there, was change the prototype of
Function.prototype, an object that impacts pretty much every piece of JavaScript code you could write. Then I changed it back.
I wanted to illustrate a big change in the prototype chain that would impact a lot of code and cause a lot of optimizations to go down the drain. I don't expect changing it back would fix anything (if anything, I expect it would make things worse performance-wise). I'd love to know if it would or wouldn't, but if it does, that wasn't my intention.
I just want to know if, after a change like this, will the JavaScript environment begin to recover and starting optimizing things again? Or will it just give up forever and run everything in deoptimized mode? Are there optimizations that will never be achieved because of this? Can I trust that, eventually, after a period of recovery, it will return to its regular state?
For context, I'm talking about engines like the most recent version of V8, not the primitive crap used by stuff like Internet Explorers. I understand the answer could be different in different systems, but I hope there is some commonality among them.
- SQL left join takes too long
I need to run a sql query that takes 24s. I tried to create indices on the two datetime columns START_DATE and END_DATE but my connection gets interupted after 600s. Is there any way to write a faster query?
SELECT tbl1.*, tbl2.NAME FROM ( SELECT * FROM table1 WHERE LOC_ID IN (%s) AND START_DATE != END_DATE AND START_DATE <= '2002-01-31' AND END_DATE >= '2002-01-01') tbl1 LEFT JOIN table2 as tbl2 ON tbl1.ID = tbl2.ID
EDIT: I tried moving the where clause outside which increased the duration to 120 seconds.
I changed the query to the suggestion but it still takes the 24s, i gained a few ms only
- How fast to derive new features (pandas) shift one period or n periods at same time? (Performance issue)
I have a dataframe with some continuos freatures (about 14), and I need to derivate more 14 (shift 1 period of hour) until n hours.
Supposing that I need until 6 hours before, so I will have more 84 columns (14*6).
For example, prcp (precipitation) derivates prcp_1, prcp_2, ... prcp_6, and the same thing for the others variables.
I was using this function:
def derive_nth_hour_feature(df, feature, N): rows = df.shape[0] nth_prior_measurements = [None]*N + [df[feature][i-N] for i in range(N, rows)] col_name = "{}_{}".format(feature, N) df[col_name] = np.nan df.loc[:][col_name] = nth_prior_measurements NON_DER = ['wsid','elvt','lat', 'lon', 'yr', 'mo', 'da', 'hr'] for feature in dfm.columns: if feature not in NON_DER: for h in range(1,7): derive_nth_day_feature(dfm, feature, h)
Work fine when the base have few records like ~ 100.000. But a have millions of records (~ 10 millions).
The result expected is like this: (derivating the prcp, stp and temp in 3 periods):
My main problem is the performance, spend a lots of time to process. The complexity is high 14^6*rows. So a need another approach.
Any sugestion?
Here a partial base (with one weather station):wsid_329.csv.zip
- Specifying dump directory in mongod.cfg file
All,
Is there a system wide setting to specify the dump folder in MongoDB? I went through this link and couldn't find any.
Basically, I want C:\MongoDB\dump to be the folder where all backups are created. Currently, a dump folder is created in the folder mongodump is executed in or one has to specify a folder explicitly using --out parameter as a part of mongodump.
Instead, wherever I may execute mongodump from, I want the dumps to be always created in C:\MongoDB\dump
Thanks, rgn
- Watson Conversation: What EXACTLY is Watson training when it is "training"?
When the "try it out" box in the Watson Conversation Tool shows "training"
(for instance: when it is getting the violet status "training" label text, when for instance assigning a new intent to a user input text):
What exactly is Watson training then? What is Watson doing at that very moment? Does this have an impact on the Workspace Data and JSON Dump Files created from this workspace?
I am asking because I am wondering the following:
- When I have a Workspace "A",
- I do a lot of training on it,
- I will dump this workspace to a JSON file and
- will use this JSON file to upload it into a new created Workspace "B":
Do I have to retrain workspace "B" AGAIN (because all the training data is lost), or will the such new created workspace "B" have all the "trained" knowlege from its original source "A" workspace? Is "training" something that will be reflected in the Workspace's dump JSON file?
- Obtaining extensible attributes from Infoblox using WAPI
I am new to scripting and I want to extract the dump of
Infobloxusing
WAPI.I want to be able to obtain the extensible attributes of the DHCP IP networks. The documentation(v2.5.0) has not been of much help as I don't know how to start. I am using python in order to go about. I have been trying to establish a connection with the
Infoblox, but I am receiving:
'Failed to establish a new connection: [Errno 61] Connection refused' | http://codegur.com/46685798/is-it-possible-to-add-retrieve-performance-related-information-to-from-a-dump | CC-MAIN-2018-09 | refinedweb | 1,569 | 64 |
04 June 2010 21:10 [Source: ICIS news]
HOUSTON (ICIS news)--June cumene values tumbled by 17% on the back of weaker feedstock benzene and refinery grade propylene (RGP) prices, sources said on Friday.
Buyers and sellers said the June formula price has moved down to 44-45 cents/lb ($970-992/tonne, €795-813/tonne).
The June price was 9 cents/lb less than the May contract of 53-54 cents/lb, according to ICIS pricing.
The cumene formula price was driven by feedstocks refinery grade propylene (RGP) and benzene.
The June contract price for ?xml:namespace>
The June benzene price was agreed upon at $2.95/gal ($897/tonne) on FOB (free on board) US Gulf (USG) terms. That compared with the May contract at $3.52/gal FOB USG.
The
Meanwhile, the average RGP price fell 10 cents to 42 cents/lb.
Blue Island Phenol, Citgo, Dow Chemical, Flint Hills Resources,
( | http://www.icis.com/Articles/2010/06/04/9365366/us-cumene-prices-for-june-tumble-17-on-feedstock-drop.html | CC-MAIN-2015-06 | refinedweb | 154 | 84.27 |
Uploading Multiple Files Using Ajax Uploader?May 1, 2010
I m using CuteWebUI.AjaxUploader.dll and i want to upload multiple files in Filesystem like c:foldername at single click.how can i do this.View 1 Replies
I m using CuteWebUI.AjaxUploader.dll and i want to upload multiple files in Filesystem like c:foldername at single click.how can i do this.View 1 Replies
dropdown list second value not save in sql but images save successfully.
<ajax:ToolkitScriptManager</ajax:ToolkitScriptManager>
<asp:DropDownList</asp:DropDownList>
<ajax:AjaxFileUpload
using System;
using System.Collections.Generic;
using System.Web;
[code]....
I am using Aurigma image uploader for uploading multiple images in asp.net
i am facing a problem in aurigma image uploader when i upload images it will show error
"Thumbnails of size more than 3 MPixels are not supported in standard version of image uploader."
But this is working fine in Mozilla or other browsers. this problem is occured only with (IE6/7/8)..View 3 Replies
With the ajax file uploader, would it be possible to check the size of the image before uploading?Currently, it uploads the file to the server and then lets me know that it's bigger than the limit size.
I am using a Aynchronous file uploader control to upload files.when I click on browse file button it opens a default dialog box. But i want to open it for a folder which is created by me on my system is any way to do this.View 3 Replies
I recently came across this post:
[URL]
I've been using this setup for a while and it works great, however I'd like to integrate a drag and drop system into this so the user can just drag files into the browser window and have them upload that way....
I wanted to add to my website the feature where the user would select some file (1 or more than 1) and uplaod them to my server.View 4 Replies
uploading multiple files from client to server with asp.net.I have been looking at the asp.net upload control but that is for one file (unless someone knows a better way to do it).
For what I want to do I don't even really need a browse. I know the files off of the client are at a certain location. Is it possible to create a collection of *HttpPostedFile*s and upload those?
I don't think it is possible but would be glad to be proven wrong. Is there a different asp.net method or control that will easily allow uploading multiple files from client to server?
the bestway to handle multiple file uploads without activex,applet or flash. User should have the ability to select multiple files in one browse click.View 3 Replies
I am trying to select and upload multiple files (photos). I have seen many articles that show you how to upload multiple by either have 5-10 fileupload controls or to Automatically add the controls using JavaScript... But I want it so that I can Select Multiple files when the openFileDialogue box appears so, its like the ajaxuploader.com but free.View 2 Replies
I am facing a situation wherein i have to ask the user for the files to upload and save them as blob in the database. I have a single file upload control on the page and user can add as many files as he wants. When the user browse the file and click add button then the file gets added at some temporary location on the page and later on when the user has specified all the files to upload then I would like to insert all these files using a single insert query in the database.View 2 Replies
I creating a page where our clients can view advertising images and then able to download the images in different file formats. So I need the images and the different download types all saved into the same row in the database so that when I go to display them on the page when they select a picture the right download links will be there. So here where my problem comes in, I don't know how to code it so that I can insert mulitiple file paths into the database at once. The images are saved in a table called images. The downloads are saved in a table called Image Downloads.
Here is the code for the page I have it coded to submit the images to the database but not sure how to add the rest. I have got three different sql datasources for each table not sure if that's the way to go.
[Code]....
I have a webpage where users can create a database record and select a file they want to upload to the database server. these files can be big, like 100mb.
I dont want the user to wait, so I want the file to be uploaded in the background. So that they can continue with doing other stuff while the file is being uploaded.
Is BITS the way to go for this? Or is that only for Fatclient development? Any good tuterials
?
If BITS is not the way to go, what are my options? An ajax call to a services with the filelocation?
How to show progress bar while uploading video files using ASP.Net,C#.View 1 Replies
i want to build a custom control using javascript on client side and ashx on server side.
I know about SWFUpload, how can i configure it with ashx on server side.
any tutorial how i can use FLASH objects to transfer files from client to server. i been looking for such tutorial for a while that uses flash object on client side and sends file info using bytes array to the server. also i want to reduce the size of the file on the client side before sending to safe bandwidth.
basically my client side is pure HTML/CSS/Jquery and Javascript using Ajax and my server side is ASP.NET with C# and most ASHX
i am using a file uploader to upload files. Now when i am using this on a mobile emulator with default browser IE it is uploading only those files whose name is less than 6 character. the files with name more than 6 character is not uploading through mobile emulator or mobile phone (PDA). I need this solution very soon.View 1 Replies
In a page, I have 4 fileupload controls. The filesize should be under 3mb. When submitting the form, I checked the filesize. If any of the uploaded filesize is higher than 3mb than I warn the user. Hovever, in this case, other successful file uploads are lost. So user would have to reselect intended files. I want all the files to be uploaded when all of them are validated successfully. How can I retain selected files even if there is a validation error?View 6 Replies
I have a requirement by my client to be able to upload extremely large files.
I'm talking about 7 GB files. The website they are currently running on is a ASP.NET 4.0 app, so obviously the standard upload scheme for my web app is not going to work.
I'm tossing around multiple options trying to figure out what the best route to go would be.
One option I'm thinking about seeing if I can do would be to have a BitTorrent Uploader. The end users for this app will typically have the same file on hand, so the idea would be that an end user would go to the site, say that they wanted to upload a file. At that point, they would pick the file, and then the server would immediately mark that person as a seed for that file. Then, my web app would go to a preconfigured leech on our side, and instruct the leech to download the file. I would expect at some point during or after this process the torrent would do some magic to find other seeders on the client's network, or wherever, but that's the idea.
Is there any technology out there already that does this? Or am I describing something that I'm going to have to build from the ground up?
is there any tool that upload multiple files currently i am using jquery i don't want to use jquery because files were going when page reloads.View 2 Replies
i want to upload multiple files through file upload or file control at the same time i want to privew that file and also its size and description, only one click on browse file these above tasks must performed, and i can upload multiple files type like pdf,doc,zip and in last i want to store those all files in database binary or any any other data type which is reliable for storing such data. can any one tel me that how can i do this.View 2 Replies
I need a multiple file uploader dialog,that means I can able to select multiple files at a time in file upload window.How can I achieve this task? I gone through Google and I came to know that we can achieve this using silverlight and flash plugins,but these are not recomandable in my application. Is there any open source(i.e free) ActiveX controls for Multi file Uploader? Is it possible to create own ActiveX control to achieve this task.View 4 Replies
i have an asp.net application, i want to incorporate init the functionality of having the user select from a dropdown list a name, select multiple files (images), upload those images to a physical path on a server, save the image paths to a database on the said server.
If the user fails to select a name from the dropdown list then the user would receive an alert message stating that a name must be selected.
In addition once the files have been successfully saved to the server's physical location, then and only then should the path be uploaded to a table in the database.
i have error in CANCEL button in file uploader.The CANCEL button does't work if i tried to remove(cancel) ADD MORE FILE button.
here is the javascript code:
[code]... | http://asp.net.bigresource.com/Uploading-Multiple-Files-using-Ajax-Uploader--enblQHctz.html | CC-MAIN-2016-40 | refinedweb | 1,747 | 71.75 |
On 12-CURRENT r326527
Running a poudriere build results in high CPU load (up to 100%) for the ZFS kernel threads "arc_dnlc_evicts_thr" and "arc_reclaim_thread":
------------------------------------------------------------------------------------------------
last pid: 8708; load averages: 5.53, 1.49, 0.55 up 0+00:01:05 14:09:07
787 processes: 18 running, 728 sleeping, 2 zombie, 39 waiting
Mem: 379M Active, 72M Inact, 765M Wired, 14G Free
ARC: 250M Total, 22M MFU, 178M MRU, 314K Anon, 6575K Header, 43M Other
100M Compressed, 292M Uncompressed, 2.91:1 Ratio
Swap: 32G Total, 32G Free
PID USERNAME PRI NICE SIZE RES STATE C TIME WCPU COMMAND
17 root -8 - 0K 192K CPU6 6 0:18 70.65% zfskern{arc_dnlc_evicts_thr}
1328 root 52 0 14300K 5280K piperd 0 0:09 22.36% sh
11 root 155 ki31 0K 128K RUN 5 0:21 16.46% idle{idle: cpu5}
11 root 155 ki31 0K 128K RUN 7 0:28 16.16% idle{idle: cpu7}
11 root 155 ki31 0K 128K RUN 0 0:29 15.48% idle{idle: cpu0}
11 root 155 ki31 0K 128K RUN 1 0:28 15.38% idle{idle: cpu1}
17 root -8 - 0K 192K arc_re 1 0:09 14.79% zfskern{arc_reclaim_thread}
11 root 155 ki31 0K 128K RUN 6 0:28 14.45% idle{idle: cpu6}
11 root 155 ki31 0K 128K RUN 4 0:27 14.36% idle{idle: cpu4}
11 root 155 ki31 0K 128K RUN 2 0:28 14.06% idle{idle: cpu2}
11 root 155 ki31 0K 128K RUN 3 0:28 13.77% idle{idle: cpu3}
1513 root 52 0 13024K 3968K nanslp 4 0:00 0.49% sh
15 root -16 - 0K 48K - 3 0:00 0.10% cam{doneq1}
0 root -16 - 0K 9024K swapin 4 0:28 0.00% kernel{swapper}
0 root 8 - 0K 9024K - 3 0:00 0.00% kernel{thread taskq}
12 root -96 - 0K 624K WAIT 5 0:00 0.00% intr{irq281: hdac1}
12 root -60 - 0K 624K WAIT 0 0:00 0.00% intr{swi4: clock (0)}
15 root -16 - 0K 48K - 6 0:00 0.00% cam{scanner}
------------------------------------------------------------------------------------------------
I have 16GB of RAM and ARC is not limited - so there should be no memory pressure.
That behaviour does not exist on 11-STABLE (r326088). There, both mentioned threads only reaches about 1-2% at maximum (similar CPU).
Any ideas how to fix that?
Addendum, even a simple "svnlite up" in "/usr/src" or "/usr/ports" let "arc_reclaim_thread" grow up to 70% load...
On my colleague's notebook running 12-CURRENT r325310 that behaviour isn't as strong; during "svnlite up" his "arc_reclaim_thread" process only rises up to 6-8% load - still higher than on 11-STABLE, though...
Ok, I've tried several revisions for good and bad results:
--------------------------------------------------------------------
326398 bad
326390 bad
326362 bad
326347 bad
326346 good
326343 good
326333 good
326286 good
--------------------------------------------------------------------
So, starting with commit r326347 - "Eliminate kmem_arena and kmem_object in preparation for further NUMA commits." - my system here freaks out...
Cc: committer of r326346.
I can also reproduce this issue. In addition, my arc size hovers around arc_min now. I expect >90G uncompressed and I get <3G. This leads to terrible Poudriere performance.
(In reply to Nikolai Lifanov from comment #5)
I can confirm the low ARC usage as well (now at 1GB usage for unlimited ARC permission with 16GB RAM). Seems that every millisecond parts of ARC are being thrown away or something...
I've noticed this before r326346. Probably a week before r326346. I haven't been able to point to any commit yet.
I will try to revert r326347 and see if it makes a difference.
(In reply to Cy Schubert from comment #7)
I think I got my dates wrong. It may be r326347. I will revert and try.
I can confirm that reverting r326347 resolves the issue. My zpools no longer thrash. Performance, due to greatly reduced I/O, has vastly improved.
So far so good:
last pid: 64954; load averages: 1.87, 1.86, 2.05 up 0+00:58:45 21:12:59
71 processes: 3 running, 68 sleeping
CPU: 0.0% user, 64.0% nice, 33.3% system, 0.2% interrupt, 2.6% idle
Mem: 1285M Active, 1367M Inact, 4489M Wired, 650M Buf, 800M Free
ARC: 1997M Total, 356M MFU, 1313M MRU, 8244K Anon, 23M Header, 298M Other
1302M Compressed, 3372M Uncompressed, 2.59:1 Ratio
Swap: 20G Total, 20G Free
PID USERNAME THR PRI NICE SIZE RES STATE C TIME WCPU COMMAN
64687 root 1 52 10 10604K 1996K select 1 0:00 1.63% make
60776 root 1 52 10 14460K 6092K select 1 0:00 0.41% make
33699 root 1 20 0 14312K 5308K select 0 0:00 0.22% screen
60761 root 1 46 10 10984K 2520K select 1 0:00 0.14% make
61698 root 1 20 0 13920K 4124K CPU1 1 0:00 0.11% top
33888 root 1 30 10 10196K 1500K select 0 0:00 0.11% make
64686 root 1 52 10 11692K 3180K wait 0 0:00 0.11% sh
33914 root 1 30 10 10996K 2520K select 0 0:00 0.10% make
2712 root 1 20 0 14352K 5624K select 1 0:00 0.02% devd
3166 uucp 1 20 0 12288K 3856K nanslp 1 0:00 0.01% upsmon
3127 root 1 20 0 10860K 2456K select 0 0:00 0.01% powerd
3124 root 2 20 0 19264K 19396K select 1 0:00 0.01% ntpd
2795 root 1 20 0 11400K 2616K select 0 0:00 0.01% syslog
3358 root 1 20 0 15748K 6640K select 1 0:00 0.00% sendma
And a different machine:
last pid: 81498; load averages: 1.86, 1.88, 2.04 up 0+00:59:45 21:13:59
62 processes: 2 running, 60 sleeping
CPU: 0.4% user, 13.9% nice, 19.4% system, 0.6% interrupt, 65.7% idle
Mem: 1291M Active, 1381M Inact, 4490M Wired, 650M Buf, 778M Free
ARC: 2031M Total, 349M MFU, 1331M MRU, 8254K Anon, 24M Header, 319M Other
1313M Compressed, 3410M Uncompressed, 2.60:1 Ratio
Swap: 20G Total, 20G Free
PID USERNAME THR PRI NICE SIZE RES STATE C TIME WCPU COMMAN
81192 root 1 83 10 19976K 11788K CPU1 1 0:00 5.95% make
33699 root 1 20 0 14312K 5308K select 1 0:01 0.37% screen
33888 root 1 30 10 10196K 1500K select 0 0:00 0.29% make
81169 root 1 52 10 14320K 5936K select 0 0:00 0.22% make
33914 root 1 30 10 11016K 2524K select 0 0:00 0.16% make
61698 root 1 20 0 13920K 4124K CPU0 0 0:00 0.10% top
2712 root 1 20 0 14352K 5624K select 0 0:00 0.02% devd
3127 root 1 20 0 10860K 2456K select 1 0:00 0.01% powerd
3166 uucp 1 20 0 12288K 3856K nanslp 1 0:00 0.01% upsmon
3124 root 2 20 0 19264K 19396K select 0 0:00 0.01% ntpd
2795 root 1 20 0 11400K 2616K select 0 0:00 0.01% syslog
3358 root 1 20 0 15748K 6640K select 0 0:00 0.00% sendma
25899 root 1 20 0 12876K 3684K select 0 0:00 0.00% klogin
33698 root 1 20 0 12392K 3648K pause 1 0:00 0.00% screen
During a buildworld -DNO_CLEAN (second machine):
Total MFU MRU Anon Hdr L2Hdr Other
ZFS ARC 2001M 464M 1300M 8695K 30M 0K 198M
rate hits misses total hits total misses
arcstats : 71% 660 258 274342 697629
arcstats.demand_data : 67% 218 107 96070 81229
arcstats.demand_metadata : 25% 44 129 43412 569950
arcstats.prefetch_data : 0% 0 22 10019 27947
arcstats.prefetch_metadata:100% 398 0 124841 18503
zfetchstats : 4% 99 2013 28345 3844648
arcstats.l2 : 0% 0 0 0 0
vdev_cache_stats : 58% 7 5 9786 19927
I'm getting pretty healty hit rates where as with r326347 the hit rates were in the low single digits.
last pid: 23981; load averages: 1.85, 1.80, 1.61 up 0+00:48:45 21:50:20
133 processes: 4 running, 129 sleeping
CPU: 4.8% user, 45.2% nice, 27.7% system, 0.2% interrupt, 22.1% idle
Mem: 1509M Active, 1341M Inact, 37M Laundry, 3593M Wired, 178M Buf, 1281M Free
ARC: 1324M Total, 20M MFU, 653M MRU, 134M Anon, 19M Header, 498M Other
154M Compressed, 582M Uncompressed, 3.78:1 Ratio
Swap: 12G Total, 12G Free
PID USERNAME THR PRI NICE SIZE RES STATE C TIME WCPU COMMAN
2658 cy 6 23 0 92956K 45940K select 3 1:50 10.70% mate-t
19465 root 1 25 0 56596K 47756K zio->i 2 0:09 10.37% rsync
2503 root 1 24 0 67200K 43964K select 2 1:47 9.91% Xorg
20179 root 1 24 0 56192K 47576K db->db 2 0:07 9.54% rsync
23948 root 1 52 10 10920K 2036K select 1 0:00 3.42% make
19772 root 1 20 0 11040K 2656K select 1 0:00 0.81% moused
23213 root 1 4 10 12992K 4312K select 0 0:00 0.21% make
12248 root 1 4 10 18088K 9680K select 3 0:01 0.17% make
23492 root 1 52 10 10560K 1804K select 1 0:00 0.14% make
23860 cy 1 20 0 13940K 4152K CPU2 2 0:00 0.11% top
2591 cy 1 20 0 16804K 6684K select 2 0:02 0.09% xscree
23947 root 1 52 10 11688K 3176K wait 0 0:00 0.09% sh
2560 cy 1 20 0 21684K 9336K select 2 0:02 0.09% mwm
3205 root 1 30 10 11084K 2392K select 3 0:00 0.08% make
72684 root 1 30 10 10224K 1388K select 0 0:01 0.08% make
MFU should be much higher.
r326346 also needs to be backed out. Will try that too.
Looking at the workloads of my four systems, I'm not entirely convinced reverting r326346 will make as much difference as removing r326347 did. Though ARC is more in line with as it was before r326347, MFU fluctuates widely, from 55M to 500M. Better than single digit MB before. I will see if reverting r326346 makes a difference too.
last pid: 50534; load averages: 1.32, 0.94, 0.96 up 0+01:05:30 22:07:05
123 processes: 2 running, 121 sleeping
CPU: 1.6% user, 4.2% nice, 5.0% system, 0.6% interrupt, 88.7% idle
Mem: 1018M Active, 1310M Inact, 3670M Wired, 178M Buf, 1763M Free
ARC: 1327M Total, 177M MFU, 651M MRU, 15M Anon, 24M Header, 460M Other
283M Compressed, 943M Uncompressed, 3.33:1 Ratio
Swap: 12G Total, 12G Free
PID USERNAME THR PRI NICE SIZE RES STATE C TIME WCPU COMMAN
2503 root 1 24 0 58704K 35612K select 1 2:16 7.25% Xorg
2658 cy 5 22 0 93644K 46620K CPU0 0 2:16 6.99% mate-t
50487 root 1 4 10 10476K 1836K select 2 0:00 1.53% make
49701 root 1 52 10 17436K 9024K select 1 0:00 0.16% make
2591 cy 1 20 0 16804K 6684K select 2 0:02 0.08% xscree
50489 root 1 52 10 11668K 3172K wait 3 0:00 0.08% sh
2560 cy 1 20 0 21684K 9336K select 0 0:03 0.07% mwm
23860 cy 1 20 0 14168K 4388K CPU3 3 0:01 0.07% top
50486 root 1 52 10 11688K 3176K wait 2 0:00 0.07% sh
25264 root 1 30 10 10224K 1388K select 1 0:00 0.07% make
48259 root 1 30 10 10956K 2336K select 2 0:00 0.06% make
46730 root 1 30 10 11036K 2344K select 1 0:00 0.06% make
3041 cy 1 20 0 12708K 3704K select 0 0:01 0.05% krlogi
25290 root 1 30 10 11128K 2416K select 2 0:00 0.05% make
49044 root 1 20 0 11040K 2656K select 0 0:00 0.04% moused
So far so good (machine 1):
last pid: 47502; load averages: 1.60, 1.92, 1.69 up 0+00:34:24 22:57:38
51 processes: 2 running, 49 sleeping
CPU: 0.6% user, 0.0% nice, 9.1% system, 0.2% interrupt, 90.2% idle
Mem: 295M Active, 1858M Inact, 4233M Wired, 645M Buf, 1555M Free
ARC: 1844M Total, 516M MFU, 980M MRU, 5136K Anon, 17M Header, 325M Other
1121M Compressed, 2912M Uncompressed, 2.60:1 Ratio
Swap: 20G Total, 20G Free
PID USERNAME THR PRI NICE SIZE RES STATE C TIME WCPU COMMAN
47500 root 1 30 0 12268K 3628K CPU1 1 0:04 11.72% cpdup
18042 root 1 20 0 14132K 4340K CPU0 0 0:01 0.08% top
3127 root 2 20 0 19264K 19396K select 1 0:00 0.07% ntpd
3570 root 1 20 0 14312K 5184K select 0 0:06 0.01% screen
3130 root 1 20 0 10860K 2456K select 0 0:00 0.01% powerd
3123 root 9 52 0 29220K 5564K uwait 1 0:00 0.01% nscd
99226 root 1 20 0 12876K 3684K select 1 0:00 0.00% klogin
2911 root 1 20 0 12064K 3192K select 0 0:03 0.00% ypserv
2795 root 1 20 0 11348K 2564K select 0 0:00 0.00% syslog
2920 root 1 20 0 13448K 13536K select 1 0:00 0.00% amd
2712 root 1 20 0 14352K 5624K select 1 0:00 0.00% devd
3932 named 5 52 0 56212K 38848K sigwai 1 0:00 0.00% named
3169 uucp 1 20 0 12288K 3860K connec 1 0:00 0.00% upsmon
3359 root 1 20 0 15748K 6640K select 1 0:00 0.00% sendma
Machine 2, running buildworld -DNO_CLEAN and two rsyncs -- much better:
last pid: 4958; load averages: 3.53, 1.93, 1.21 up 0+00:38:03 23:13:38
124 processes: 6 running, 118 sleeping
CPU: 1.9% user, 83.1% nice, 12.5% system, 0.0% interrupt, 2.6% idle
Mem: 1199M Active, 840M Inact, 44M Laundry, 5251M Wired, 81M Buf, 427M Free
ARC: 3059M Total, 639M MFU, 1797M MRU, 10M Anon, 52M Header, 561M Other
1778M Compressed, 5101M Uncompressed, 2.87:1 Ratio
Swap: 12G Total, 12G Free
PID USERNAME THR PRI NICE SIZE RES STATE C TIME WCPU COMMAN
4847 root 1 90 10 98M 68872K RUN 3 0:03 91.98% cc
4949 root 1 85 10 92972K 61428K RUN 0 0:01 62.55% cc
3818 root 1 26 0 242M 234M select 2 0:02 17.95% rsync
4945 root 1 52 10 10568K 1952K select 2 0:00 8.38% make
4321 root 1 25 0 269M 261M select 1 0:01 7.72% rsync
2639 cy 5 21 0 93388K 45296K CPU3 3 0:51 3.28% mate-t
2581 root 1 22 0 69376K 46348K select 0 0:55 2.47% Xorg
2855 cy 55 22 0 7866M 468M select 3 0:45 0.62% firefo
4948 root 1 52 10 70348K 38172K wait 0 0:00 0.40% cc
4825 root 1 4 10 11052K 2460K select 0 0:00 0.27% make
3824 root 1 20 0 11004K 2504K sbwait 2 0:00 0.15% rsh
3459 root 1 20 0 11040K 2656K select 0 0:00 0.14% moused
4941 root 1 52 10 11732K 3196K wait 2 0:00 0.12% sh
4944 root 1 52 10 11696K 3184K wait 3 0:00 0.12% sh
3367 root 1 52 10 28328K 20252K select 1 0:01 0.11% make
I've done some testing with r326347 reverted and with r326346 + r326347 reverted. My test included I/O intensive operations including buildworld/buildkernel -DNO_CLEAN and parallel rsync. Removing r326346 + r326347 showed no significant improvement over removal of only r326347 (below). r326347 definitely caused the issue. Note MFU. Performance is significantly better due to improved ARC caching.
last pid: 2156; load averages: 2.56, 2.32, 1.66 up 0+00:25:52 00:32:57
89 processes: 4 running, 85 sleeping
CPU: 1.3% user, 75.8% nice, 20.5% system, 0.8% interrupt, 1.7% idle
Mem: 390M Active, 602M Inact, 5631M Wired, 63M Buf, 1317M Free
ARC: 3585M Total, 1106M MFU, 2029M MRU, 14M Anon, 60M Header, 376M Other
2734M Compressed, 6084M Uncompressed, 2.23:1 Ratio
Swap: 20G Total, 20G Free
PID USERNAME THR PRI NICE SIZE RES STATE C TIME WCPU COMMAN
63633 root 1 52 0 36720K 27164K RUN 1 2:28 7.38% pkg
2136 root 1 4 10 10548K 1932K select 0 0:00 6.32% make
1909 root 1 4 10 11808K 3144K select 1 0:00 0.36% make
2096 root 1 24 0 13804K 3952K CPU1 1 0:00 0.11% top
2135 root 1 52 10 11700K 3124K wait 1 0:00 0.11% sh
3598 root 1 20 0 14312K 5216K select 0 0:02 0.10% screen
98994 root 1 4 10 28516K 20320K select 1 0:01 0.10% make
1828 root 1 52 10 10404K 1608K select 1 0:00 0.07% make
61839 root 1 30 10 10196K 1324K select 1 0:00 0.05% make
1906 root 1 4 10 10360K 1468K select 1 0:00 0.05% make
98907 root 1 30 10 10980K 2340K select 1 0:00 0.04% make
99013 root 1 30 10 23784K 15508K select 1 0:00 0.04% make
2712 root 1 20 0 14352K 5624K select 1 0:00 0.02% devd
3137 root 1 20 0 10860K 2456K select 0 0:00 0.01% powerd
I can definitely confirm that running stock r326658 with r326347 reverted fixes the ARC under-use for me.
I think this diff will address the problem:
(In reply to Mark Johnston from comment #18)
I confirmed that the fix in D13412 resolves the problem for me.
A commit references this bug:
Author: markj
Date: Thu Dec 7 19:38:09 UTC 2017
New revision: 326664
URL:
Log:
Fix the UMA reclaim worker after r326347.
atomic_set_*() sets a bit in the target memory location, so
atomic_set_int(&uma_reclaim_needed, 0) does not do what it looks like
it does.
PR: 224080
Reviewed by: jeff, kib
Differential Revision:
Changes:
head/sys/vm/uma_core.c
(In reply to commit-hook from comment #20)
thanks for the commit. Unfortunately, the issue still is not solved for me. How to repeat:
1) freshly reboot FreeBSD 12-CURRENT r326668M
2) login as "root"
3) start "top -s 1 -P -H -S"
4) switch to another VTY
5) login as "root"
6) start "svnlite up /usr/src"
7) switch back to VTY where "top" is running
"arc_reclaim_thread" raises up to 70% CPU load...
(In reply to Nils Beyer from comment #21)
and total ARC usage stays under 1GB though "vfs.zfs.arc_max" is set to 16GB...
Can you tell me what the following two sysctls hold:
vm.kmem_map_free
vm.kmem_map_size
and then run this for a few seconds:
dtrace -n 'fbt::uma_reclaim_wakeup:entry { @[stack()] = count (); }'
(In reply to Jeff Roberson from comment #23)
--------------------------------------------------------------------------------
vm.kmem_map_free: 15830609920
vm.kmem_map_size: 801755136
#dtrace -n 'fbt::uma_reclaim_wakeup:entry { @[stack()] = count (); }'
dtrace: description 'fbt::uma_reclaim_wakeup:entry ' matched 1 probe
^C (after svnlite up finishes)
--------------------------------------------------------------------------------
I have to add that I'm not using any debug options in my kernel config...
I see another problem in arc_available_memory(): we're using vmem_size(kernel_arena, VMEM_FREE) to determine whether to reap memory. It used to be vmem_size(kmem_arena), and kmem_arena was initialized with vm_kmem_size bytes. But kernel_arena is grown on demand, so it's now bogus to use the arena's size to determine whether to reclaim memory.
We can use the new uma limit facility. I can produce a diff in a couple of hours. This is essentially the same thing that kmem_map_free does however:
static int
sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
{
u_long size, limit;
/* The sysctl is unsigned, implement as a saturation value. */
size = uma_size();
limit = uma_limit();
if (size > limit)
size = 0;
else
size = limit - size;
return (sysctl_handle_long(oidp, &size, 0, req));
}
We should make a uma accessor to compute this.
Confirmed. The latest patch partially fixes the problem.
Mem: 186M Active, 60M Inact, 2123M Wired, 103M Buf, 2572M Free
ARC: 1012M Total, 368M MFU, 487M MRU, 11M Anon, 19M Header, 128M Other
On my sandbox machine (5 GB RAM) (lets call it machine 3 now).
bob<1># sysctl vm.kmem_map_free
vm.kmem_map_free: 1089998848
bob<1># sysctl vm.kmem_map_size
vm.kmem_map_size: 520613888
bob<1># sysctl hw.physmem
hw.physmem: 5346369536
bob<1>#
bob# dtrace -n 'fbt::uma_reclaim_wakeup:entry { @[stack()] = count (); }'
dtrace: description 'fbt::uma_reclaim_wakeup:entry ' matched 1 probe
There is no output.
I'll get a chance to more fully test on on another machine (machine 2 before) tonight. I've set up a test partition to boot from to allow for quick testing.
Continuing to test on my sandbox (other machines are still busy on other builds):
ARC: 429M Total, 9067K MFU, 262M MRU, 2618K Anon, 4246K Header, 151M Other
^^^^ ^^^^^
buildworld/buildkernel -DNO_CLEAN and tar of /usr/src in progress.
ARC: 445M Total, 3880K MFU, 281M MRU, 2288K Anon, 3056K Header, 156M Other
^^^^ ^^^^^
I unset the arbitrary limits kmem_size_max andn kmem_size limits. They are now:
bob<2># sysctl vm.kmem_size
vm.kmem_size: 5181820928
bob<2># sysctl vm.kmem_size_max
vm.kmem_size_max: 1319413950874
bob<2>#
(In reply to Jeff Roberson from comment #26)
I've applied a patch similar to the one discussed here. There is some improvement but more testing and comparison with r326347 removed is needed.
On my two 8 GB machines (with zfs arc tuning removed from loader.conf) I get:
2 core + 2 threads:
CPU: 0.9% user, 95.9% nice, 3.0% system, 0.0% interrupt, 0.2% idle
Mem: 1500M Active, 318M Inact, 33M Laundry, 1762M Wired, 154M Buf, 4148M Free
ARC: 840M Total, 141M MFU, 545M MRU, 16M Anon, 12M Header, 127M Other
288M Compressed, 893M Uncompressed, 3.10:1 Ratio
slippy# sysctl vm.kmem_size
vm.kmem_size: 8138756096
slippy# sysctl vm.kmem_size_max
vm.kmem_size_max: 1319413950874
slippy# sysctl hw.physmem
hw.physmem: 8365903872
slippy#
slippy$ sysctl vfs.zfs.arc_max
vfs.zfs.arc_max: 7065014272
slippy$
2 core:
CPU: 0.0% user, 94.9% nice, 4.1% system, 0.6% interrupt, 0.4% idle
Mem: 752M Active, 269M Inact, 1705M Wired, 111M Buf, 5215M Free
ARC: 862M Total, 218M MFU, 456M MRU, 15M Anon, 15M Header, 156M Other
343M Compressed, 1079M Uncompressed, 3.15:1 Ratio
cwsys# sysctl vm.kmem_size
vm.kmem_size: 8325849088
cwsys# sysctl vm.kmem_size_max
vm.kmem_size_max: 1319413950874
cwsys# sysctl hw.physmem
hw.physmem: 8566394880
cwsys#
cwsys$ sysctl vfs.zfs.arc_max
vfs.zfs.arc_max: 7252107264
cwsys$
It appears arc is being limited to ~ 840 - 860 MB on the 8 GB machines.
The 5 GB machine (2 core):
CPU: 0.0% user, 95.1% nice, 4.7% system, 0.2% interrupt, 0.0% idle
Mem: 590M Active, 147M Inact, 1126M Wired, 101M Buf, 3077M Free
ARC: 488M Total, 50M MFU, 334M MRU, 6630K Anon, 5713K Header, 91M Other
107M Compressed, 431M Uncompressed, 4.02:1 Ratio
bob# sysctl vm.kmem_size
vm.kmem_size: 5180735488
bob# sysctl vm.kmem_size_max
vm.kmem_size_max: 1319413950874
bob# sysctl hw.physmem
hw.physmem: 5345284096
bob#
bob# sysctl vfs.zfs.arc_max
vfs.zfs.arc_max: 4106993664
bob#
We might want to consider reverting r326347 until we can fix this.
With r326347 removed and kern_size, kern_size_max and arc_max tunables removed from loader.conf:
Laptop w 8 GB with two processes each of tar of /usr/src and /usr/obj and buildworld/buildkernel -DNO_CLEAN and firefox:
CPU: 2.7% user, 95.0% nice, 2.1% system, 0.1% interrupt, 0.0% idle
Mem: 617M Active, 67M Inact, 204M Laundry, 6505M Wired, 144M Buf, 369M Free
ARC: 4879M Total, 1830M MFU, 2630M MRU, 21M Anon, 54M Header, 343M Other
3983M Compressed, 10G Uncompressed, 2.69:1 Ratio
Swap: 12G Total, 382M Used, 12G Free, 3% Inuse, 128K In
slippy$ sysctl vm.kmem_size
vm.kmem_size: 8138752000
slippy$ sysctl vm.kmem_size_max
vm.kmem_size_max: 1319413950874
slippy$ sysctl hw.physmem
hw.physmem: 8365899776
slippy$ sysctl vfs.zfs.arc_max
vfs.zfs.arc_max: 7065010176
slippy$
Server machine in basement with 8 GB also running two processes each of tar of /usr/src and /usr/obj and buildworld/buildkernel -DNO_CLEAN, no firefox:
CPU: 0.0% user, 97.0% nice, 2.6% system, 0.4% interrupt, 0.0% idle
Mem: 257M Active, 246M Inact, 36K Laundry, 6690M Wired, 110M Buf, 746M Free
ARC: 5153M Total, 1262M MFU, 3472M MRU, 20M Anon, 53M Header, 346M Other
4364M Compressed, 11G Uncompressed, 2.51:1 Ratio
Swap: 20G Total, 95M Used, 20G Free
cwsys$ sysctl vm.kmem_size
vm.kmem_size: 8325844992
cwsys$ sysctl vm.kmem_size_max
vm.kmem_size_max: 1319413950874
cwsys$ sysctl hw.physmem
hw.physmem: 8566390784
cwsys$ sysctl vfs.zfs.arc_max
vfs.zfs.arc_max: 7252103168
cwsys$
This is also with additional patch discussed in comment #26 removed.
Created attachment 188780 [details]
Proposed fix
Please test this fix for arclowmem et all
Currently running on four amd64 machines. Initial tests indicate this PR is fixed. Thanks Jeff.
I can test on an i386 machine this weekend.
On i386 this probably needs a cast.
/opt/src/svn-current/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/arc.c:6115:2
1: error: ordered comparison between pointer and integer ('uint64_t' (aka 'unsig
ned long long') and 'long (*)(void)') [-Werror]
available_memory = MIN(available_memory, uma_avail);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/opt/src/svn-current/sys/sys/param.h:305:23: note: expanded from macro 'MIN'
#define MIN(a,b) (((a)<(b))?(a):(b))
~~~^~~~
arc.c line 6115 s/b,
available_memory = MIN(available_memory, uma_avail());
^^
That'll fix i386 build.
(In reply to Jeff Roberson from comment #31)
thank you.
Confirmed - with this patch, "arc_reclaim_thread" stays quiet and ARC usage raises accordingly. Disk usage has become normal and CPU power goes into user processes.
"arclowmem" tests anyone?
I can comfirm that uma_avail) should've been uma_avail()) on all architectures. pho has reported that this patch gives him identical performance to code pre-dating the change.
There is also the rpi2 and UFS tied list submittals against
-r326347 causing booting to hang, starting with:
and ending with:
There are tied to boot hangs with the kernel
thread (100001) involving:
. . .
uma_zcreate() at uma_zcreate+0x10c
pc = 0xc052b024 lr = 0xc050cc90 (ffs_mount+0x80)
sp = 0xd42a5858 fp = 0xd42a5980
r4 = 0xd7844000 r5 = 0x00000000
r6 = 0x00000003 r7 = 0xc09a99c0
r8 = 0x00000000 r9 = 0xd429f000
r10 = 0xd828c400
ffs_mount() at ffs_mount+0x80
pc = 0xc050cc90 lr = 0xc032e1d4 (vfs_donmount+0xeec)
sp = 0xd42a5988 fp = 0xd42a5b38
r4 = 0xffffffff r5 = 0xd74ec120
r6 = 0xd429f000 r7 = 0x00000000
r8 = 0x00000000 r9 = 0xc425acd0
r10 = 0xd828c400
. . .
and the uma thread involving:
. . .
uma_reclaim_locked() at uma_reclaim_locked+0x200
pc = 0xc052d9f8 lr = 0xc052de70 (uma_reclaim_worker+0x4c)
sp = 0xd87dadf0 fp = 0xd87dae20
r4 = 0xc09a9c68 r5 = 0xc4242d80
r6 = 0xc06df86e r7 = 0x00000000
r8 = 0x00000100 r9 = 0xc09b3d08
r10 = 0xc09a9c7c
uma_reclaim_worker() at uma_reclaim_worker+0x4c
pc = 0xc052de70 lr = 0xc0230f10 (fork_exit+0xa0)
sp = 0xd87dae28 fp = 0xd87dae40
r4 = 0xd7ad8740 r5 = 0xd70ce000
r6 = 0xc052de24 r7 = 0x00000000
r8 = 0xd87dae48 r9 = 0xd7ada3a0
r10 = 0xc0824e8c
. . .
(extracted from the last of those messages).
bisect activity was used to isolate -r326347
as the version the problem started in.
(In reply to Mark Millard from comment #37)
It probably makes sense to track this as a separate incident. It's easier to find this through keywords. What do you think?
(In reply to Cy Schubert from comment #38)
I can extract from the prior list messages and make a submittal
if desired.
There is also a complaint for pine64 from Emmanuel Vadot:
reporting that as of -r326347 :
The board just hang when plugin usb device
That would seem to match my rpi2 reports: I have
a USB SSD on a powered hub for the root file
system on the rpi2 that I was using.
(Recently the mmcsd0 mechanism to hold in the
sdcard is broken but the eject mechanism
still works. I hold in the sdcard during
the early boot. But I've used a USB SSD
for such small boards for a long time.)
(In reply to Cy Schubert from comment #38)
I've submitted bugzilla 224330 for Emmanuel Vadot
and my list messages tied to USB on pine64
(Emmanual) and rpi2 (me).
Mostly I referenced the list messages instead of
copying over the information.
I do not have access to the Keywords field there.
Nor to See Also here in bugzilla 224080.
Another -r326347 and zfs combination list report
is part of the material in the pair:
These folks might be able to test for if their
problems have been fixed when things are ready
for such.
The first report says r326347 was the last known good kernel. There may be other unrelated bugs.
(In reply to Jeff Roberson from comment #42)
You may well be correct about unrelated bugs. But. . .
Looks like I Parse the 067613.html report differently
than you do:
A) First it says:
Most recent CURRENT, as with r326363, crashes on booting the kernel
This is different than it later reports about -r326347 as I
parse the statements.
B) Then it says
The last known half-ways good kernel is 12.0-CURRENT #157 r326347
Note the "half-ways" part. It then continues with what I
interpreted as a description of "half-ways" in a booted
-r326347 context (so, not for -r326363).
When performing buildworld/buildkernel/relaese/package
or poudriere on a ZFS filesystem, I can now bring down
the system almost in a reproducible way.
I could be wrong but I do not see that as a report of the
"the last known good kernel".
I have sent the patch and a short description to the person who made the report. I agree I may have misparsed.
A commit references this bug:
Author: jeff
Date: Tue Jan 2 04:35:57 UTC 2018
New revision: 327485
URL:
Log:
Fix arc after r326347 broke various memory limit queries. Use UMA features
rather than kmem arena size to determine available memory.
Initialize the UMA limit to LONG_MAX to avoid spurious wakeups on boot before
the real limit is set.
PR: 224330 (partial), 224080
Reviewed by: markj, avg
Sponsored by: Netflix / Dell EMC Isilon
Differential Revision:
Changes:
head/sys/cddl/compat/opensolaris/sys/kmem.h
head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/arc.c
head/sys/vm/uma.h
head/sys/vm/uma_core.c
head/sys/vm/uma_int.h | https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=224080 | CC-MAIN-2019-35 | refinedweb | 5,053 | 84.07 |
Unity 5.3.5
The Unity 5.3.5 public release brings you a few improvements and a large number of fixes. Read the release notes below for details.
For more information about the previous main release, see the Unity 5: IL2CPP - Stripping of symbols and debug info is now enabled by default. Development builds still have symbols which makes for a slightly larger binary.
- Asset Bundles: Added offset argument to AssetBundle.CreateFromFile and AssetBundle.LoadFromFile methods.
- Asset Bundles: Output the CRC value for the manifest asset bundle.
- Asset Management: Introduced AssetDatabase.GetAssetDependencyHash method which returns the hash of all the dependencies of an asset.
- Cluster Rendering: Improved cluster networking layer and reduced instability while using cluster input.
- Graphics: Dynamic batching was reintroduced for particles, lines and trails. (766802)
- IL2CPP: Reduce the binary size and build time for projects which make use of many C# attributes.
- iOS: Added a compile flag in the trampoline code in order to allow disable the filtering of emoji characters.
- iOS: Added device support for iPhone SE and iPad Pro 9.7".
- OpenGL: ComputeBuffer now uses the same data layout as Direct3D.
- Networking: Added support for IPv6 networks in UdpClient. (767741)
- VR: Updated Oculus API and plugin to version 1.3.2. Downloading 1.3.2 OVRPlugin from Oculus is no longer necessary.
- Windows Store: On IL2CPP scripting backend, Unity players are now shipped as DLLs rather than static libraries. This significantly reduces platform support module installation size as well as decreases generated C++ code linking time.
Changes
- Android: IL2CPP - Full debug version of IL2CPP libraries are stored in Temp/StagingArea/Il2Cpp/Native.
- OpenGL: ComputeBuffer data layout changes to match Direct3D; see Improvements section for details.
- Installer: Updated EULA.
Fixes
- Analytics: Fixed a rare crash. Only occurs when analytics is on and importing a complete project from asset store with analytics off.
- Android: Audio - Fixed OpenSL output not selected when default buffer size selected. (784899)
- Android: Buildpipe - Don't make use of preview SDK tools installed. (788040)
- Android: Buildpipe - Fixed AAPT errors on project export. (786918)
- Android: Buildpipe - Fixed AAR plugin and resource issues on exported projects. (765396)
- Android: Disabled Debug markers on PowerVR Series5 devices due to driver issues. (780958)
- Android: Fix for EGL_BAD_NATIVE_WINDOW error on resume. (747898)
- Android: Fix for GPU skinning on Adreno GPUs. (763755)
- Android: Fix for syncing to low framerate with VSync off. (777167)
- Android: Fixed a crash in the Development build for some Android devices with PowerVR GPUs (e.g. Asus Memo Pad). (787491)
- Android: Fixed blending with background on Unity splash screen.
- Android: Fixed crash on Nvidia Shield tablet. (765744)
- Android: Fixed crash when loading scenes intermittently. (751530)
- Android: Fixed immersive mode switching off on some KitKat devices when pressing volume buttons. (779338)
- Android: Fixed incorrect width/height when changing orientation after changing anti-aliasing settings. (771542)
- Android: Fixed potential crash when using WWW without having Internet permission (also affects use of Unity Analytics). (779877)
- Android: Fixed potential race condition in atomic operations on ARM processors.
- Android: Fixed Standard Shader lighting issue caused by half-precision overflow on Mali GPUs. (761744)
- Android: Fixed value of trackingEnabled.
- Android: Workarounds for OpenGL ES 3 shader compiler problems on Adreno GPUs. (777617)
- Animation Window: Fixed Null Reference Exception in Curve Editor. (775565)
- Animation Window: Disabled animation sampling of an optimized game object hierarchy in the animation window. (753270)
- Animation Window: Fixed custom components not appearing in the Add Property menu of the Animation Window. (760809, 759069)
- Animation Window: Fixed selection loss in animation window when pasting keyframes. (715416)
- Animation: Fixed a crash related to exposed skeleton. (784942)
- Animation: Fixed a crash when importing an animation where a whole curve was corrupted. (774052)
- Animation: Fixed a performance issue for AnimatorOverrideController rebind. (779058)
- Animation: Fixed an issue where instantiating a prefab with an Animator Component for the first time took longer than the subsequent times. (771609)
- Animation: Fixed an issue where rotation curves would be created as Euler curves by default when using the Animation Component. (772668)
- Animation: Fixed an issue where the scale was not working in editor on GameObject with OptimizeGameObject. (774484)
- Animation: Fixed animation event inheriting from ScriptableObject not getting triggered. (762952)
- Animation: Fixed crash when an animation key tried to activate a game object which had animator attached to it. (786873)
- Animation: Fixed crash when calling Animator.Update(0) in an AnimationEvent. (783821)
- Animation: Fixed crash when GameObject with Animator is instantiated in StateMachineEnter/Exit. (770045)
- Animation: Fixed crash when shutting down standalone app with Script Playables. (775677)
- Animation: Fixed error message in console while optimizing animation hierarchy from the inspector. (775773)
- Animation: Fixed issue where Animation was distorted when animated object was scaled and Optimize Game Objects was selected. (766898, 758322)
- Animation: Fixed scale value getting zeroed when removing scale curve components in AnimationWindow. (689644)
- APIUpdater: Fixed AssemblyUpdater crash when verifying WSA / Windows Phone assemblies. (767506)
- APIUpdater: Fixed ScriptUpdater crash when processing Boo / UnityScript containing Hash literals. (769880)
- Asset Bundles: Fixed issue where would not take into account space on device, and could hang. (762829)
- Asset Bundles: Fixed the error messages when building variant asset bundles. (769858)
- Asset Bundles: Fixed an issue where unloading an asset bundle with animated objects (legacy animation) during play mode crashes the editor. (775822)
- Asset Bundles: Added back scene asset bundles compression statistics. (768965)
- Asset Bundles: Fixed a crash while loading asset bundle asynchronously. (747800)
- Asset Bundles: Fixed a potential crash when decompressing corrupted LZMA bundles. (782773)
- Asset Bundles: Fixed Compress Assets On Import setting ignored when switching platform (762739)
- Asset Bundles: Fixed CreateFromMemory not working with "." in filenames. (734216)
- Asset Import: Fixed a crash on FBX import in some rare circumstances. (768846)
- Asset IMport: Fixed issue where changing date modified on directory meta file caused all files below that directory to be reprocessed. This was also affecting VCS. (756559)
- Audio: Don't try to load any sounds when Unity audio is disabled. (776044, 763036)
- Audio: Fixed an issue where Low Pass Filter didn't work on Audio Listener. (732854)
- Batch mode: Fixed an issue where BuildPlayer calls might cause compilation errors to be logged in subsequent runs. (703290, 786195)
- Cache Server: Upgraded the node.js version 0.12.7. (760234)
- Compute: Do not log warnings/errors when current build target does not support compute shaders.
- Core: Added stacktrace for logging statements and exceptions called on threads. (697872, 633905)
- Core: ArgumentCache.TidyAssemblyTypeName is now alloc-free if the type name is already clean. (738249)
- Core: Fixed crash when scaling prefab with mesh that is not read/write enabled. (766019)
- Core: When exporting a package with scene's dependencies, checkboxes are available next to folder icon. (752733)
- Core: is now a case-insensitive Dictionary, as per RFC2616 spec. (770155)
- D3D11: Fixed a deadlock which would occur when trying to restore focus to a minimized standalone player running in Fullscreen Exclusive mode. (523691)
- D3D11: Fixed exclusive mode window reactivation issues after focus has been lost. (788555)
- D3D11: Fixed some rare crashes on memory constrained systems (log would contain resource creation failure messages).
- D3D9: Player loop will now be processed in the background again when the graphics device is lost (Windows are locked, window is minimized, etc.). (752626)
- Editor: Fix for core assemblies not being reloaded after encountering errors in user scripts. (750423)
- Editor: Added support for resizing the height of the preferences window. (763313)
- Editor: Adjusted the width of the 'Build Settings' window so that it properly display its contents, even if support for some of the players is not currently available. (728634)
- Editor: Files with invalid names can no longer be dragged into a project. (663994)
- Editor: Fixed a crash that could happen when animation window is open, and playmode is entered. (696623)
- Editor: Fixed a crash when locking cursor from constructor or static initializer. (765466)
- Editor: Fixed a crash when padding ASTC texture when building from command line. (759288)
- Editor: Fixed an inconsistency between visible and hidden meta file modes, where empty folders were recreated in 'visible' mode. (588531)
- Editor: Fixed an issue that could cause scenes containing prefab instances with driven transforms to immediately become dirty. (709639)
- Editor: Fixed an issue that was causing transformations to be modified when entering and subsequently coming back from play mode. (759115)
- Editor: Fixed an issue where compression wasn't being applied in calls to BuildPipeline.BuildStreamedSceneAssetBundle(). (781866)
- Editor: Fixed an issue where unloaded scenes were removed from hierarchy after exiting playmode. (769613)
- Editor: Fixed an issue with dragging a Sprite/Texture2D into the inspector causing a PolygonCollider2D to use it even though it is not dropped on the component editor itself. (778125, 780607)
- Editor: Fixed changing order of components not getting saved. It now also support undo. (764986)
- Editor: Fixed crash on launch if "metadata" folder is deleted before launching. (746964)
- Editor: Fixed newly installed Unity command line activation issue. (790345)
- Editor: Fixed performance issue in Sprite Inspector. (709059)
- Editor: Fixed Target Support module download URLs in Build Settings.
- Editor: Fixed the asset importer error when calling Refresh() during an assembly import. (730559)
- Editor: Fixed WebViewWindow's freed memory access. (775366)
- Editor: Fixed wrong error message when returning license via command line. (784727)
- Editor: Fixed an issue when logging off and opening the Service Window would be missing. (781863)
- Editor: If a read only file or folder is duplicated, the read only status is no longer duplicated. (730245)
- Editor: Improved error messages for unsupported target platform in batch mode. (782752)
- Editor: Now show alert popover for invalid serial format. (775898)
- Editor: Remove SelectionBase from LOD Group. (763231)
- Editor: Sped up importing of some Fonts by updating progress bar less often than "crazy often".
- Editor: Fixed access to destroyed window during shutdown. (775244)
- Editor: Fixed access violation in some editor GUIView operations. (769833)
- GI: Fixed incorrect normal mapping on Directional Specular lightmaps; shader code was not matching up what Enlighten was baking. (755421, 766533, 766546, 779696, 756020, 780025)
- GI: Clamped DynamicGI.indirectScale to allowed range. (664953)
- GI: Disabled LightProbeGroup components no longer display visualization in the scene view. (662572)
- GI: Fixed errors when using baked lightmaps & multi-scene editing. (753822)
- GI: Fixed realtime GI texture coordinates sometimes going wrong on static-batches meshes. (743273)
- GI: Fixed some cases of scenes not referencing the correct lighting data asset after bake. (757575)
- GI: Improved wording of various Enlighten error messages.
- GI: Now properly initialize baked scenes in some code paths to avoid error on console. (753822)
- GI: Upgraded to Enlighten3.02p4. Fixes direct lighting getting baked into lightmap (697565). Fixes a precision issue and out-of-bounds texture access in baking, which could lead to a crash in the Final Gather stage. (767110)
- GI: Changing Reflection Probe component positioning in the inspector makes realtime probe black. (653592)
- GI: Fixed a Reflection Probe baking issue when multiple scenes are used in a project.
- GI: Fix for baking a scene with objects added before saving the scene not being included in the result. (728610)
- GI: Fixed a crash when building reflection probe data on specific scenes containing Canvas elements. (767560, 763045)
- Graphics: Fixed a glitch in Crunch format compressed non-alpha texture after using sprite packer. (774638, 768171)
- Graphics: Fixed internal profiler for static batching on Android, iPhone and Windows Store. (769539)
- Graphics: Fixed material index not being used when calling Graphics.DrawMeshNow with rotation. (765378)
- Graphics: Fixed MovieTexture crash when loading a video with no audio stream.
- Graphics: Fixed potential crash in SetGpuProgramName.
- Graphics: Fixed static batching errors when meshes have additional vertex data streams with mismatching vertex count. (775261)
- Graphics: Fixed TrailRenderer showing a gap between current position and the last update. (779129)
- Graphics: Upgrading a shader with a DX11 [annotation] at the start of the file now doesn't crash. (766992)
- IL2CPP: Correct an intermittent crash when Environment.GetCommandLineArguments is called. (775804)
- IL2CPP: Emit proper C++ code for COM marshaling of methods that have at least one parameter that cannot be marshaled. (789905)
- IL2CPP: Fixed a rare deadlock during Resources.UnloadUnusedAssets. (756912)
- IL2CPP: Fixed an intermittent crash in the experimental memory profiler. (776152)
- IL2CPP: Fixed an issue with Socket.Select and IL2CPP where a socket could be reported as being in an error state when it should have been reported as being in a write state. (759488)
- IL2CPP: Generate C++ code to properly handle circular references for field types in unsafe C# code. (780472)
- IL2CPP: Generate proper C++ code for a C# class with the StructLayout attribute when its base class does not have a StructLayout attribute. (767367)
- IL2CPP: Generate proper C++ code for a method that is marked as both an internal call and a runtime call. (781439)
- IL2CPP: Generate proper C++ code for the OnSerialize method injected by UNET in classes deriving from NetworkProximityChecker. (786499)
- IL2CPP: Generate proper C++ code for the p/invoke wrapper for a delegate that accepts another delegate as an output parameter. (778146)
- IL2CPP: Generated proper C++ code for assemblies compiled with Visual Studio when a method returning an IntPtr returns an integer value. (787687)
- IL2CPP: Improved message for PathTooLongException being encountered in IL2CPP. (717343)
- IL2CPP: Increased maximum heap size.
- IL2CPP: Now correctly return the remote end point from a UDP socket receive call in an IPv6 network. (767741)
- IL2CPP: Now generate proper code for COM marshaling of a struct that contains a field of type object array. (781921)
- IL2CPP: Prevent a compile error in the generated C++ code due to a missing header when we generic exception type is used in a catch statement. (776087)
- IL2CPP: Properly handle numeric conversion from an unsigned integer to floating point types in some edge cases. (780659)
- IL2CPP: Properly handle type casts and check for value type arrays when they are casted to generic collection interfaces. (782653)
- IL2CPP: Support proper default marshaling of string parameters and return values when the CharSet attribute is provided on a method with a value of Unicode. (692653)
- IL2CPP: Throw informative exception when MonoPInvokeCallback delegate type is incompatible with target method signature. (732438)
- Input: Input.mousePosition is no longer clamped to the client area on windows standalone, the last position is kept instead. (769666)
- iOS: Added Xcode 7.3 Build & Run support.
- iOS: Allow IPv6 to work on iOS with the .NET 2.0 profile. (730146)
- iOS: Allow third party plugins that use PLCrashReporter library. (768572)
- iOS: Apple Pencil pressure will now be exposed the same way 3D Touch pressure already is.
- iOS: Do not export non-prefixed freetype2 symbols now. (778668)
- iOS: Ensure asset bundles are not flagged for iCloud backup by default upon download. (771597)
- iOS: Ensure that our symbols are not overridden by user libraries. (774685)
- iOS: Fixed a crash when playing a scene in the Editor with an iOS device attached as a Unity Remote. (771132)
- iOS: Fixed GLES error 0x0506 and various graphics corruption when using WebCam textures. (763342)
- iOS: Fixed incompatible pointer cast warning in trampoline. (776105)
- iOS: Fixed memory leak when using On Demand Resources. (776528)
- iOS: Fixed support for non-native resolutions in GLES 2. (779738)
- iOS: Fixed the incorrect ABI for int64 types on iOS. (774544)
- iOS: Fixed UnityWebRequest hanging on responses > 64k when using a custom DownloadHandlerScript. (780329)
- iOS: Made Social.ShowLeaderboardUI to show the leaderboards tab, instead of achievements tab. (777596)
- iOS: Pause application on GameCenter dialogs on tvOS. (767633)
- iOS: Switching between different input fields will not leave input accessory fields on screen. (775710)
- iOS: TouchInputModule and StandaloneInputModule will now handle all touch phases preventing unwanted module switches. (764054)
- iOS/IL2CPP: Prevent unnecessary changes to the timestamps of the libil2cpp headers during a build. This allows incremental builds to work correctly in Xcode.
- iOS/tvOS: AdSupport is now removed from Default Frameworks and needs to be explicitly selected under Framework Dependencies in Platform Settings if required. (732878)
- iOS/tvOS: Fixed a regression which caused artefacts when using GLES2 Graphics API. (785036)
- JsonUtility: Fixed EditorJsonUtility throwing MissingMethodException (769085)
- Linux: Don't query displays when running in nographics mode.
- Linux: Exit with nice message instead of crashing when GPU/driver doesn't meet minimum requirements. (777564, 783842)
- Linux: Fixed a crash when stereoscopic mode is requested on non-stereoscopic display. (784075)
- Linux: Fixed an occasional crash when creating texture properties.
- Mac Editor: Added functionality in order to prevent the processing of folders that contain the ".unity" extension, as this was causing the editor to crash when executing in batch mode. (761639)
- MacDownloadAssistant: Fixed window focus issue after security prompt.
- Mac Editor: Fixed UI text rendering on Radeon HD 4000 series and older AMD GPUs. (783713)
- Mac Editor: Application.version now returns the application's version. It no longer returns Application.unityVersion. (764054)
- MemoryProfiler: Added toggle to exclude references in detailed memory dump to reduce memory footprint used. (783527)
- Mono: Fixed GC related test instability in OSX Editor. (777945)
- Mono: Make the Personal folder be the same on all profiles. (776268)
- Networking: Fixed issue with SyncList change callback where the old value was given there instead of the updated one. (774970)
- Networking: Fixed problem when transferring data via reliable sequenced QoS channel could lose messages in "bad" network conditions. (781177)
- Networking: Fixed problem where HostTopology.MessagePoolSizeGrowthFactor was ignored. (773411)
- Networking: Fixed WebGL client unable to free connections in NetworkServer when using WebSocket. (768030)
- OpenGL: Fixed a bunch of compute shader structured buffer access corner case issues. (767348)
- OpenGL: Fixed invalid shader code generation when using gl_PrimitiveID or bitFieldInsert().
- OpenGL: Fixed mislocated fragment shader default float precision. Now also basing the default precision on actual GPU capabilities. (763638)
- OpenGL: Fixed multiple simultaneous append/consume compute buffers usage.
- OpenGL: Fixed rendering when Graphics.Blit is being called after WaitForEndOfFrame. (784880)
- OpenGL: Shader compiler, added unused global uniform pruning.
- OpenGL: Shader compiler, avoid temporary variable name collisions. (780831)
- OpenGL: Shader compiler, fixed shader translation bugs. (782514)
- OpenGL/ES: Fixed GPU profiler on Android for Tegra 2/3/4 devices. (776539)
- Particles: Do not restart simulation when becoming visible, and use bigger timesteps, to reduce performance spikes. (765905)
- Particles: Fixed a case where if OnWillRenderObject renders, it breaks the main scene. (773226)
- Particles: Fixed a crash caused when using Inherit Velocity Module. (783433)
- Particles: Fixed a crash when material is missing and mesh colors are requested. (774931)
- Particles: Fixed a crash when using SubEmitters with separate rotation axes. (757377)
- Particles: Fixed an issue where the Material Property Blocks not working with mesh particles. (776143)
- Particles: Fixed batching issues when using multiple cameras in the same position. (788023)
- Particles: Fixed culling when using SetParticles. (496494)
- Physics: Cloth deletes MeshRenderer component when entering playmode fixed. (769137)
- Physics: Disabling cloth component doesn't seem to really disable it fixed. (669622)
- Physics: Ensure that OnTriggerExit2D is not called when changing Rigidbody2D.isKinematic property.
- Physics: Fix for Collision2D.relativeVelocity being reported with incorrect values. (758422)
- Physics: Fixed an issue for 2D collider: line & ray casting not detecting initial overlapped state.
- Physics: Fixed an issue with Box2D changes slowing the editor down when lots of changes are made without entering play-mode. (777591)
- Physics: Fixed cloth issue where adding cloth to an object throws GetLocalizedString error. (769136)
- Physics: Provide feedback to allow working around crashes occurring when input meshes contain invalid vertices. (766891)
- Physics2D: Fix to ensure that changing a Collider2D property via the inspector doesn't reset the OnCollision or OnTrigger state back to 'Enter'. (786032)
- Physics2D: Fixed a problem where both AreaEffector2D and PointEffector2D scaled-up forces for each additional collider on a rigidbody. (780257)
- Physics2D: Fixed a problem where constantly changing an Effector2D collider would mean that no contacts were ever processed stopping the effector from working.
- Prefabs: Implemented OnWillSaveAssets callback when applying prefabs. (754351)
- Profiler: Fixed a crash when adding data from thread which was started during a frame. (758264)
- Resources: Enable warnings for and prevent crashes and memory corruptions when non-assets, or non-unloadable assets are tried to be unloaded through Resources.UnloadAsset in release builds. (767120)
- Samsung TV: Enabled a "Show Unity Splash Screen" check box on Samsung TV's PlayerSettings.
- Samsung TV: Fixed multiple crashes on the NT14U TV that would prevent games from launching.
- SpeedTree: Fixed "GetLocalizedString is not allowed to be called" error message when using the Tree Editor. (779965)
- Terrain: Fixed crash when exiting Editor after creating TerrainData with HideAndDontSave flag. (780365)
- Tizen: Fixed issue deploying after upgrading to the Tizen 2.4rev4 SDK. (743653)
- tvOS: Enabled game controller in tvOS on-screen keyboard. (776446)
- tvOS: Fixed a bug that caused splash screen properties being not applied. (775008)
- tvOS: Fixed a crash when calling OnDemandResourcesRequest.Dispose() in a coroutine.
- tvOS: Fixed build targeting tvOS 9.2 with Xcode 7.3 beta. (770115)
- tvOS: Separated tvOS SDK and OS version settings from iOS. (749311)
- UI: Fix for child UI elements not being rendered when scaling World Space Canvas from zero. (768807)
- UI: Fixed ArgumentOutOfRange exception sometimes being thrown when editing InputField on mobile. (762080)
- UI: Fixed dropdown destroy coroutine being started when the component is not active. (758873)
- UI: Fixed issue with crash due to dirty renderer being in the dirty list after being destroyed. (764711)
- UI: Fixed issue with double rendering of canvas on Vive VR.
- UI: Fixed object culling when unparenting from a mask type. (740604)
- UI: Fixed Selectable not handling when the EventSystem is null. (788037)
- UI: Fixed setting Input Field text when in Decimal/Integer with invalid values.
- UI: Setting Input field text through script will now be validated.
- UnityWebRequest: Downgrade to HTTP GET on 302 and 303 redirect codes (751798)
- UnityWebRequest: Honor negative redirectLimit. (751794)
- UWP: Build & Run will correctly work with Universal Windows 10 Apps. (771326)
- UWP: Screen.currentResolution will return desktop resolution when application is in windowed mode. (771541)
- VisualStudio: Fixed a crash that could sometimes happen when opening Visual Studio.
- VR: Fixed an issue with incorrect Render Texture size being used. Most notable with deferred rendering.
- VR: VRFocus now respects RunInBackground. Run In Background value of true will now disable rendering if VRFocus is lost.
- WebGL: Fixed SimpleWebServer bug causing 'Uncaught incorrect header check'. (770266)
- Wii U: Added crash fixes, memory efficiency and 16-bit texture support.
- Wii U: Fixed issues causing known crashes.
- Windows: SystemInfo.deviceModel will now report model name and manufacturer. (784466)
- Windows Standalone: P/Invoke will work correctly with native libraries which reference other native libraries, if those libraries are located in the same directory. (776918)
- Windows Store: Assembly-CSharp-firstpass will no longer reference itself. (775216)
- Windows Store: Correctly generate Visual Studio namespace when product name contains ' symbol. an underscore will be used instead. (754102)
- Windows Store: Disable Generate C# option when scripting backend is set to il2cpp. (775344)
- Windows Store: Files located in Assets\Resources won't end up in generated Assembly-CSharp-firstpass project, but will be correctly placed in Assembly-CSharp project.
- Windows Store: Fixed $(OutDir) and $(IntDir) paths for generated IL2CPP Visual Studio solutions which prevented appx bundles to build correctly.
- Windows Store: Fixed a rare crash at startup related to serialization on debug mode. (778905)
- Windows Store: Fixed an assert happening during mesh compression.
- Windows Store: Fixed an exception while marshalling UnityEngine.NavMeshTriangulation.
- Windows Store: Fixed an issue with populating visual assets (tiles, logos, etc.) to Visual Studio solution (correct file names, manifest entries) and check format consistency (JPEG vs PNG). (775592, 775624, 777575, 777580)
- Windows Store: Fixed Build & Run for Universal 8.1 solution. (789538)
- Windows Store: Fixed generics related AssemblyConverter failure and give better error messages. (762780)
- Windows Store: Fixed incorrect orientation of extended splash screen on Windows Phone 8.1. (770092)
- Windows Store: Fixed marshaling of UnityEngine.HumanDescription, previously the field hasTranslationDoF was not mashaled at all.
- Windows Store: Fixed marshaling of UnityEngine.SplatPrototype, previously fields specularMetallic, smoothness were not marshaled, because of this sometimes terrain would be rendered incorrectly. (786889)
- Windows Store: Fixed Screen.orientation returning AutoRotation on startup. (787522)
- Windows Store: Fixed stacktraces on IL2CPP scripting backend. (781907)
- Windows Store: Fixed Tab key duplication in XAML controls when Unity input is enabled. (775931)
- Windows Store: Fixed return result, previously it would return only an error code, now it will also contain error message returned by the server.
- Windows Store: Having many generic types in the project no longer makes .NET Native compiler run out of memory.
- Windows Store: Help SerializationWeaver find references which have Windows SDK specified when building to Universal 8.1. (781994)
- Windows Store: Hindi characters will show up correctly, Nirmala UI from Windows fonts will be used. (779136)
- Windows Store: Package.appxmanifest for Universal Windows 10 Apps will be produced correctly when protocol for association launching is specified. (780971)
- Windows Store: RuntimeInitializeOnLoadMethod will work correctly. (777878)
- Windows Store: Screen.SetResolution will correctly work on Windows Phone 10. (773877)
- Windows Store: Slightly fix generated Assembly-CSharp* projects to fix "System.BadImageFormatException: Duplicate type with name 'UnityEngine.Internal.$FieldNamesStorage' .. " (781935)
- Windows Store: EventType.ScrollWheel is now properly detected. (784975)
- Windows Store: The maximum amount of characters for short name for tiles will be 40 now. (789439)
- Windows Store/IL2CPP: Allow the MapFileParser utility to handle input and output files with paths containing non-ASCII characters. (779968)
- Windows Store/IL2CPP: Fixed a crash on windows when using asynchronous socket APIs (.BeginSend/.BeginReceive/etc). (771883)
- Windows: Fixed standalone Windows player position when bigger than primary monitor. (760215)
- WindowsDownloadAssistant: Fixed setting VisualStudio 2015 as Unity script editor.
- WindowsDownloadAssistant: Fixed the bug which was freezing installation UI during bad network connection. (732955)
Revision: 960ebf59018a
Changeset: 960ebf59018a
Unity 5.3.5 | https://unity3d.com/ru/unity/whats-new/unity-5.3.5 | CC-MAIN-2021-04 | refinedweb | 4,210 | 50.33 |
Red Hat Bugzilla – Bug 970203
Unable to use some options for int sub-fields in Guvnor
Last modified: 2014-02-24 11:06:28 EST
Created attachment 756412 [details]
before-saving
The configuration is reverted back to its original state after saving a rule which contains an int sub-field that uses some options such as "less than", "greater than", "less than or equal to" and "greater than or equal to" in Guvnor. The only options available after saving are: "equal to", "not equal to", "is null" and "is not null" (see before-saving.png and after-saving.png attached). Follow the steps to reproduce:
1) Created a model object which has an object attribute. This class has an int attribute as follows:
public class Customer {
private Contact contact;
...
}
public class Contact {
private int tel1;
...
}
2) After importing the jar to guvnor, I created a rule adding the "tel1" sub-field. I selected "greater than" option and saved the rule.
3) It has reverted to "---please choose---" and now I can only choose "equal to", "not equal to", "is null" and "is not null".
Created attachment 756413 [details]
after-saving | https://bugzilla.redhat.com/show_bug.cgi?id=970203 | CC-MAIN-2018-34 | refinedweb | 190 | 61.97 |
Need to edge out the competition for your dream job? Train for certifications today.
Submit
namespace Service1Area
{
[WebService(Namespace = "")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
// ... your code goes are two very simple solutions for the problem, after which you shouldn't have any problems compiling (from this issue):
1. Change the name of your second service to something other than EticDownEplan when you recreate or rename it.
2. Use the namespace feature (in the .cs file!) to group objects into separate "spaces". The structure is
Open in new window
It sounds like there's some similar naming of objects in your project, and when you do that you have to be somewhat careful of how you "path" your objects. Specifically, I mean the namespace "path" that an object has inside its assembly.
Does the second .asmx file have the same namespace "path" as an .edmx file in the project?
Let's eliminate that possibility before we look elsewhere.
Thank you very much for your answer, thank you for the tip,
correcte me if i missunderstood please: i shouldn't have the same namespace for both files as i'm doing.
for my first asmx created by default in the project :
//[WebService(Namespace = "")]
[WebService(Namespace = "")]
...
[System.Web.Script.Service
public class Service1 : System.Web.Services.WebSer
second asmx:
//[WebService(Namespace = "")]
[WebService(Namespace = "")] //avec dns
...
[System.Web.Script.Service
public class EticDownEplan : System.Web.Services.WebSer
as you can see, i toogle uncomment the namespace for compiling for the server
and when i'm working locally i toogle the comment again.
question : can i just let localhost as it seems to work in the server? or the other ? what is a good habit to get concerning ws ?
could you advice me on how to change the links names or whatever need to change to be able to have both in server machine as expected and not only locally.
Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.
i've changed as follow:
first asmx created by default :
[WebService(Namespace = "")]
second asmx :
[WebService(Namespace = "")] //avec dns
but when compiling i receive the same error:
C:\WINDOWS\Microsoft.NET\F
--------------------------
second test
i've deleted the first amsx file that was created by default,
and the error stilll the same for the file, the project compile with success though.
========== Rebuild All: 1 succeeded, 0 failed, 0 skipped ==========
thank you for further help, i dont know what to do .
===
[WebService(Namespace = "")]
[WebServiceBinding(Conform
[System.ComponentModel.Too
[System.Web.Script.Service
public class Service1 : System.Web.Services.WebSer
===
[WebService(Namespace = "")]
[WebServiceBinding(Conform
[System.ComponentModel.Too
[System.Web.Script.Service
public class Service2 : System.Web.Services.WebSer
===
... so you can see the namespace probably isn't the problem. That's a good thing. Let's adjust your code to make sure both namespaces are the same in the [WebService(Namespace = "")]. Doesn't matter which one you pick; just keep them consistent.
At this point I think something else is causing your build to fail. It seems like there is another file somewhere in your project that has the same name as your EticDownEplan() class. To test this, please...
1. Exclude the current EticDownEplan.asmx service (if you haven't already).
2. Add another service to your project but DON'T change anything in it.
3. Attempt a build and let me know what happens.
OK, i set both namespace at the same url.
i have excluded EticDownEplan, added the new webservice, and compile,
compilation without error,
thank you for further help.
i still not know what to do ;)
[assembly:AllowPartiallyTr
namespace Ecowaste.E_plan.ede
now i dont know if my web site is dynamically compiled, as i compiled it before deploy.
another question is : when i convert my project to webapplication, the contextual "change to web application" still there after ???? does it mean that the change did not work?
......
thank you for further help
now this is the file that get opened, i paste it if it can be of some help :
<Project xmlns="">
<!-- This .targets file can be used by updating Microsoft.Common.targets to
include the line below (as the last import element just before the end project tag)
<Import Project="$(MSBuildBinPath)
-->
<!-- The below ensures that "EntityDeploy" is available in the VS Build Action dropdown -->
<ItemGroup>
<AvailableItemName Include="EntityDeploy" />
</ItemGroup>
<UsingTask TaskName="EntityDeploy"
AssemblyFile="$(MSBuildBin
</UsingTask>
<UsingTask TaskName="EntityClean"
AssemblyFile="$(MSBuildBin
</UsingTask>
<PropertyGroup>
<!-- EntityDeployDependsOn deliberately left empty so others can override this -->
<EntityDeployDependsOn></E
<BuildDependsOn>
EntityDeploy;
$(BuildDependsOn)
</BuildDependsOn>
</PropertyGroup>
<PropertyGroup>
<CleanDependsOn>
$(CleanDependsOn);
EntityClean;
</CleanDependsOn>
</PropertyGroup>
<Target Name="EntityDeploy"
DependsOnTargets="$(Entity
<EntityDeploy
Sources="@(EntityDeploy)"
OutputPath="$(OutputPath)"
<Output TaskParameter="EntityDataM
ItemName="EmbeddedResource
</EntityDeploy>
</Target>
<Target Name="EntityClean">
<EntityClean
Sources="@(EntityDeploy)"
OutputPath="$(OutputPath)"
/>
</Target>
</Project>
thank you for your help,
what i did:
once i' clicked on the error in the output window of vs, some code displayed , i deleted that code.
i then try to restart a new project but was impossible! i did not what to do since i lookup for the file
that was "Microsoft.Data.Entity.tar
i deleted since it was empty -> 0Kg in the explorer.
after that , i restart a new app, recompile, and the problem was gone. i could deploy the web app.
until now i just connect to the two files in the web site, things seem ok.
what can be the consequences of having deleted such file?
is there a way to set this kind of basic file back?
Erwin
I assume that the section you're talking about was generated by Visual Studio, so if necessary I expect that it would regenerate the code (if you followed the same steps as before).
Congratulations on fixing your problem!
btw, could you just tell me how you consider "Entity Framework" ? only in a couple of lines.
for the code i've deleted it was not regenerate:
he was in place at : "C:\WINDOWS\Microsoft.NET\
if you're using the same framework, could you push your file to this thread in order to have a hand on it if i need it later ;o) it's a few kb only.
i succeed to fix my problem but help me a lot, so i'm allowing you the points.
Erwin
You may actually have to repair the v3.5 framework to make sure that everything will work correctly again. That's the route I would take.
On the whole I think that ORMs like the Entity Framework are a good idea if they fit the project need and timeline you're trying to use them for. If the project doesn't have the time for it (meaning you're learning while you're actively working) then it may not be a great idea to implement just then. | https://www.experts-exchange.com/questions/25956424/when-i-create-2-asmx-files-in-the-same-project-one-seems-not-to-be-compiled-what's-wrong.html | CC-MAIN-2018-26 | refinedweb | 1,163 | 57.67 |
The QState class provides a general-purpose state for QStateMachine. More...
#include <QState>
Inherits QAbstractState.
Inherited by QStateMachine.
This class was introduced in Qt 4.6. assignProperty() function is used for defining property assignments that should be performed when a state is entered.
Top-level states must be passed a QStateMachine object as their parent state, or added to a state machine using QStateMachine::addState().).
This enum specifies how a state's child states are treated.
This property holds the child mode of this state.
The default value of this property is QState::ExclusiveStates.
Access functions:
This property holds the error state of this state.
Access functions:
This property holds the initial state of this state (one of its child states).
Access functions:
Constructs a new state with the given parent state.
Constructs a new state with the given childMode and the given parent state.
Destroys this state.
Adds the given transition. The transition has this state as the source. This state takes ownership of the transition.
Adds a transition associated with the given signal of the given sender object, and returns the new QSignalTransition object. The transition has this state as the source, and the given target as the target state.
Adds an unconditional transition from this state to the given target state, and returns then new transition object.
Instructs this state to set the property with the given name of the given object to the given value when the state is entered.
See also propertiesAssigned().
Reimplemented from QObject::event().
This signal is emitted when a final child state of this state is entered.
See also QFinalState.
Reimplemented from QAbstractState::onEntry().
Reimplemented from QAbstractState::onExit().().
Removes the given transition from this state. The state releases ownership of the transition.
See also addTransition(). | http://doc.qt.nokia.com/4.6-snapshot/qstate.html | crawl-003 | refinedweb | 293 | 61.83 |
I've been trying some modern OpenGL tutorials, and I came across what seems to be strange behaviour. Here is the code, reduced to its (almost) bare essentials.
#include <iostream> #include <GL/glew.h> #include <GLFW/glfw3.h> using std::cout; using std::endl; int main(){ std::cout << "Begin program" << std::endl; glfwInit();_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); GLFWwindow* window = glfwCreateWindow(800, 600, "OpenGL", 0, 0); // Windowed glfwMakeContextCurrent(window); glewExperimental = GL_TRUE; glewInit(); while(!glfwWindowShouldClose(window)) { glfwSwapBuffers(window); glfwPollEvents(); } cout << "before glfwTerminate()" << endl; glfwTerminate(); cout << "after glfwTerminate()" << endl; cout.flush(); std::cout << "End program" << std::endl; return 0; }
Looking at the GLFW docs, the call to
glfwTerminate() should not exit the program, but nothing is output to the console after "
before glfwTerminate()" and the program ends.
I'm on ArchLinux (freshly updated) and I tried with both xfce4 and KDE (minimal install for the latter, just to make sure it wasn't an xfce4 issue).
Would someone have a hint as to what is going on? | http://www.howtobuildsoftware.com/index.php/how-do/Ez1/c-eclipse-opengl-glfw-glew-code-after-glfwterminate-never-runs | CC-MAIN-2019-09 | refinedweb | 165 | 55.24 |
Read data from a message
#include <sys/neutrino.h> int MsgRead( int rcvid, void* msg, int bytes, int offset ); int MsgRead_r( int rcvid, void* msg, int bytes, int offset );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.:
When you're finished using MsgRead(), you must use MsgReply*() to ready the REPLY-blocked process and complete the message exchange.
None. In the network case, lower priority threads may run.
The MsgRead() function has increased latency when it's used to communicate across a network — a message pass is involved from the server to the network manager (at least). Depending on the size of the data transfer, the server's lsm-qnet.so and the client's lsm-qnet.so may need to communicate over the link to read more data bytes from the client.
The only difference between the MsgRead() and MsgRead_r() functions is the way they indicate errors:
If you try to read past the end of the thread's message, the functions return the number of bytes they were actually able to read.
QNX Neutrino
MsgReadv(), MsgReceive(), MsgReceivev(), MsgReply(), MsgReplyv(), MsgWrite(), MsgWritev()
Message Passing chapter of Getting Started with QNX Neutrino | http://www.qnx.com/developers/docs/6.5.0/topic/com.qnx.doc.neutrino_lib_ref/m/msgread.html | CC-MAIN-2020-34 | refinedweb | 203 | 62.27 |
Linus Torvalds wrote:> > On Wed, 6 Dec 2000, Miles Lane wrote:> >> > Here is what goes wrong:> >> > Dec 6 04:21:32 agate kernel: eth0: Host error, FIFO diagnostic register 0000.> > But it continues to work, right?> > I bet that your ethernet card is just unhappy that it couldn't get DMA in> time, because the bus was so busy. Many of the busmastering ethernet> devices will start the packet send early, happy in the knowledge that> they'll usually have plenty of time to DMA the data by the time they need> it.> > This works fine most of the time, but if you have a busy PCI bus and> you're doing things over a (potentially slow) PCI bridge like the Cardbus> bridge, you're taking chances. And sometimes those chances do not work out> ok.. Especially if you have slow memory, which most laptops have.> > I suspect that the worst result of this is just a noisy driver: both on> the network (runt packets) and on the console. And it obviously will cause> performance to suffer too, due to retransmitting packets that failed,> and/or losing packets.> > There may be some rule for the threshold for sending packets or something> else to make this happen less, so this is probably tweakable. But it> doesn't sound deadly (unless the driver causes this to result in a dead> network - does it?)> We initialise the 3com NICs so that the DMA of Tx frames doesn'tcommence until 1536 free bytes are available in the Tx FIFO. I assumethis is to make the most of the NIC's ability to bus-master-transfer anentire frame in one slurp. But this is irrelevant.We initialise the NIC so it starts putting data on the wire after 128bytes are in the Tx FIFO. So yes, there is an opportunity for anotherbus master to interrupt the slurp and to hold the bus for so long thatthe NIC gets a TX underrun. But surely not by just wiggling the mousearound?I have seen just one report of a person getting Tx underruns. Thedriver recovered OK. But Miles is reporting "Host error". This isdifferent. The 3com datasheet says: This bit is set when a catastrophic error related to the bus interface occurs. The errors that set this bit are PCI target abort and PCI master abort. This bis is cleared by issuing the GlobalReset command...This is a very rare problem. Trolling the vortex archives comes upwith a few comments from Das Nicmeisters: > Donald Becker write: > Another PCMCIA setup bug, except this one is much harder to track down. > The CardBus bridge chip isn't configured correctly. > This is a real bus problem, not a false report. > David Hinds wrote: > I've gotten a few reports of these PCI bus errors. They have indeed > been very hard to track down, since they are specific to particular > hardware combinations, and I've never been able to reproduce them. > Donald Becker wrote: > I've gotten this error on my Vaio 505TR, but I've never been able to > reproduce it when I'm ready to observe it.Miles, could you please apply the below patch? It'll give us alittle more info about the PCI error. Bit 31 of `bus status' isMasterAbort and bit 30 is TargetAbort.Also, you can disable the start-tx-after-128-bytes feature by uncommenting// wait_for_completion(dev, SetTxStart|0x07ff);near the end of vortex_up(). With this change the NIC won't starttransmitting until it has the entire frame onboard. It shouldn't makeany difference (hah). This does look like a Cardbus bridge problem.--- linux-2.4.0-test12-pre7/drivers/net/3c59x.c Tue Nov 21 20:11:20 2000+++ linux-akpm/drivers/net/3c59x.c Fri Dec 8 02:24:11 2000@@ -203,7 +203,7 @@ #include <linux/delay.h> static char version[] __devinitdata =-"3c59x.c:LK1.1.11 13 Nov 2000 Donald Becker and others. " "$Revision: 1.102.2.46 $\n";+"3c59x.c:LK1.1.11 13 Nov 2000 Donald Becker and others. " "$Revision: 1.102.2.40 $\n"; MODULE_AUTHOR("Donald Becker <becker@scyld.com>"); MODULE_DESCRIPTION("3Com 3c59x/3c90x/3c575 series Vortex/Boomerang/Cyclone driver");@@ -843,10 +843,15 @@ { int rc; - rc = vortex_probe1 (pdev, pci_resource_start (pdev, 0), pdev->irq,- ent->driver_data, vortex_cards_found);- if (rc == 0)- vortex_cards_found++;+ /* wake up and enable device */ + if (pci_enable_device (pdev)) {+ rc = -EIO;+ } else {+ rc = vortex_probe1 (pdev, pci_resource_start (pdev, 0), pdev->irq,+ ent->driver_data, vortex_cards_found);+ if (rc == 0)+ vortex_cards_found++;+ } return rc; } @@ -863,7 +868,7 @@ struct vortex_private *vp; int option; unsigned int eeprom[0x40], checksum = 0; /* EEPROM contents */- int i;+ int i, step; struct net_device *dev; static int printed_version; int retval;@@ -912,12 +917,6 @@ vp->must_free_region = 1; } - /* wake up and enable device */ - if (pci_enable_device (pdev)) {- retval = -EIO;- goto free_region;- }- /* enable bus-mastering if necessary */ if (vci->flags & PCI_USES_MASTER) pci_set_master (pdev);@@ -1025,6 +1024,13 @@ dev->irq); #endif + EL3WINDOW(4);+ step = (inb(ioaddr + Wn4_NetDiag) & 0x1e) >> 1;+ printk(KERN_INFO " product code '%c%c' rev %02x.%d date %02d-"+ "%02d-%02d\n", eeprom[6]&0xff, eeprom[6]>>8, eeprom[0x14],+ step, (eeprom[4]>>5) & 15, eeprom[4] & 31, eeprom[4]>>9);++ if (pdev && vci->drv_flags & HAS_CB_FNS) { unsigned long fn_st_addr; /* Cardbus function status space */ unsigned short n;@@ -1148,14 +1154,19 @@ return retval; } -static void wait_for_completion(struct net_device *dev, int cmd)+#define wait_for_completion(dev, cmd) _wait_for_completion(dev, cmd, __LINE__)++static void _wait_for_completion(struct net_device *dev, int cmd, int line) {- int i = 4000;+ int i; outw(cmd, dev->base_addr + EL3_CMD);- while (--i > 0) {- if (!(inw(dev->base_addr + EL3_STATUS) & CmdInProgress))+ for (i = 0; i < 4000000; i++) {+ if (!(inw(dev->base_addr + EL3_STATUS) & CmdInProgress)) {+ if (i > 1000)+ printk("wait_for_completion: line=%d, count=%d\n", line, i); return;+ } } printk(KERN_ERR "%s: command 0x%04x did not complete! Status=0x%x\n", dev->name, cmd, inw(dev->base_addr + EL3_STATUS));@@ -1331,6 +1342,7 @@ set_rx_mode(dev); outw(StatsEnable, ioaddr + EL3_CMD); /* Turn on statistics. */ +// wait_for_completion(dev, SetTxStart|0x07ff); outw(RxEnable, ioaddr + EL3_CMD); /* Enable the receiver. */ outw(TxEnable, ioaddr + EL3_CMD); /* Enable transmitter. */ /* Allow status bits to be seen. */@@ -1663,6 +1675,12 @@ dev->name, fifo_diag); /* Adapter failure requires Tx/Rx reset and reinit. */ if (vp->full_bus_master_tx) {+ int bus_status = inl(ioaddr + PktStatus);+ /* 0x80000000 PCI master abort. */+ /* 0x40000000 PCI target abort. */+ if (vortex_debug)+ printk(KERN_ERR "%s: PCI bus error, bus status %8.8x\n", dev->name, bus_status);+ /* In this case, blow the card away */ vortex_down(dev); wait_for_completion(dev, TotalReset | 0xff);-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgPlease read the FAQ at | https://lkml.org/lkml/2000/12/7/29 | CC-MAIN-2020-50 | refinedweb | 1,082 | 55.13 |
Bob, They are actually the same thing. Lift's processing directives are simply built-in snippets. You can, if you dare, override their functionality. :-)
Thanks, David On Fri, Apr 10, 2009 at 11:23 AM, bob <rbpas...@gmail.com> wrote: > > if I see <lift:XXXX/>, it could mean one of two things: a directive, > e.g., <lift:bind/> or <lift:surround/> or shorthand for a snippet, eg > <lift:myClass> represents <lift:snippet > > i guess I would like to see these disambiguated a shorthand for > snippets that doesn't overlap with the directive namespace. > > some possible solutions: > > 1. <lift:bind/> would be the directive and <lift:.bind/> would be the > snippet. please don't get hung up on my use of dot. it is only an > example, and not an actual suggestion. > > 2. <lift:bind/> maps to a real class, not some internal code, much the > way <lift:msgs/> maps to net.liftweb.builtin.snippets.Msgs (thanks > Jorge) > > 3. <lift:bind> is the directive, and <liftsnippet:bind> is the snippet > > comments? > > thanks, bob > > > > > -- Lift, the simply functional web framework Beginning Scala Follow me: Git some: --~--~---------~--~----~------------~-------~--~----~ -~----------~----~----~----~------~----~------~--~--- | https://www.mail-archive.com/liftweb@googlegroups.com/msg04707.html | CC-MAIN-2022-05 | refinedweb | 184 | 69.07 |
This is the presentation I would like to have given at Alliance 2012 this year in Nashville.
I admit, I’ve been a fan of Java for various reasons since the mid-90′s. When I read in the pre-release notes for PeopleTools 8 (pretty sure that was September or October of 2001) that we would be able to make calls to Java classes from PeopleCode, I got a little giddy. Of course, the giddiness faded when we discovered some of the limitations, particularly around calling overloaded methods, that made using even basic language-native classes difficult. Chris Heller of GreyHeller Solutions has written fairly extensively (Part 1, Part 2, Part 3) about the quirks and workarounds for using Java in PeopleCode. Jim Marion of Oracle has also contributed significantly to the PS community in this area on his blog.
One of the primary workarounds for this problem is to build a Java class with simple input and outputs to accomplish whatever task you need Java to do. This is the approach I took with a client where we needed to use Java to open a network socket and validate a “web signon system” token in Sign-on PeopleCode. The class took a string as an input and passed back a pipe-delimited string of values as a return value. Simple! We compiled the class and deployed it in all 3 Application Server domains. All was well until, in a panic, the server admins stood up a new AppServer domain and forgot to deploy the custom Java class to the new PS_HOME. Can you guess the result? 25% of all login attempts failed at a critical load time. Ouch… Still stings a bit.
For years, I have preached the virtues and vices of Java and PeopleCode. If you need to get something done that PeopleCode can’t do, chances are nearly certain that you can do it in Java. However, if you get into the habit of haphazardly deploying compiled Java classes to your AppServers and Process Scheduler Servers, the collection can become difficult to manage. Also, when developers are working on their Java code, deploying a new version of a class to the development AppServer usually required a domain restart for the change to be recognized (caching!)
So, I wanted to develop a solution that provided the power Java to a PeopleCode developer and would also minimize some of the downsides of the PeopleCode-Java mixture:
- Compile, deploy, test & repeated, usually involving server admins (grouchy types that don’t like developers bothering them… hehehehe!)
- Trying to use a Reflection API that makes all but the most brilliant developers cross-eyed and dizzy, which creates a maintenance nightmare
- Needing a robust discipline to building, deploying & migrating Java classes to AppServers and Process Schedulers, something most PeopleSoft shops are not familiar with
I propose a solution that eliminates some problems, and minimizes the rest: Use Groovy!
Groovy is a scripting language that’s based on Java. It’s ideal for building better glue for PeopleCode because:
- Its syntax is very similar to Java, with some interesting (groovy?) extensions, making it easily accessible to those inclined to write a Java-PeopleCode solution
- It has full access to the entire Java API
- It can be dynamically compiled on the fly!!!
I tried a few approaches to using Groovy in PeopleCode. Here’s the solution in a few steps:
- Write a Groovy class (nearly identical to a Java class) that does the Java-type stuff you want to do, with one limitation: the inputs and outputs need to be strings. They can be comma/pipe/whatever delimited strings, JSON, or even XML strings, so this really isn’t much of a limitation. You can bundle anything into a XML string! (Reminds me a little of the old Business Interlinks API…)
- Put that Groovy class source code into and HTML object in Application Designer. Yes, you can now migrate your Java as an AppDesigner object! Also, any changes you make to the source code are instantly available without AppServer domain restarts.
- Use an Application Package (PeopleCode) class to dynamically load and compile your Groovy class, pass your input string to it, and get a string returned back from it.
The key to the whole thing is also its disadvantage: you do need to deploy the Groovy Jar file and ONE adapter class to your AppServers and Process Scheduler Servers. Sorry, it’s not perfect. Consider deploying one set of compiled Java files in exchange for possibly never needing to deploy and migrate to these locations again, not to mention avoiding the need to meddle in the affairs of server administrators when you need to make a code change…
So here are the basic steps for installing and testing this solution:
- Install the Groovy Jar and the PSGroovyAdapter class on your AppServer (and Process Scheduler)
- Create the GroovyAdapter PeopleCode Application Class
- Create an HTML object containing the source code for a Groovy class that takes a single string as an argument to a method called execute which also returns a string
- Use the PeopleCode GroovyAdapter class to dynamically load, compile, and execute the Groovy code
Let’s walk through the details.
Install Groovy Java Classes and Adapter
Download the latest Groovy zip file here. Extract the contents and look in the embeddable folder for a file named similar to “groovy-all-1.8.6.jar”.
Next, take the following Java source and compile it into a class file. You’ll need to include the groovy-all-1.8.6.jar file in your classpath to get it to compile.
import groovy.lang.*; class PSGroovyAdapter { GroovyObject gobj; public PSGroovyAdapter(String src) throws Exception { GroovyClassLoader gcl = new GroovyClassLoader(); Class gclass = gcl.parseClass(src); gobj = (GroovyObject) gclass.newInstance(); } public String invokeWithString(String methodName, String arg) { String result = (String) gobj.invokeMethod( methodName, new Object[] {arg} ); return result; } }
Finally, copy (or ask your your server admin, nicely and with great humility, to copy for you) the jar file and compiled PSGroovyAdapter.class to the classes directory on the AppServers and Process Schedulers. Note that the servers probably need to be restarted to recognize the new Jar file! This is a one-time deal. You won’t need to inconvenience you server admins for Java-related issues any longer, once you master Groovy!
The rest of the changes are all in Application Designer.
Create a GroovyAdapter PeopleCode Application Class
In Application Designer, create a new Application Package (I’ll call mine “GROOVY”) and add a new class to the root called, “GroovyAdapter”. This will be an nice abstraction layer that will do two things:
- Load and Parse your Groovy source code from an HTML Object
- Call methods on your Groovy object once it’s built
class GroovyAdapter method GroovyAdapter(&GroovySource As string); method execute(&methodName As string, &inputString As string) Returns string; property JavaObject jAdapter; end-class; method GroovyAdapter /+ &GroovySource as String +/ Local string &htmlObject; /* Compile the Groovy Source Code contained in the named HTML object */ &htmlObject = "HTML." | &GroovySource; &jAdapter = CreateJavaObject("PSGroovyAdapter", GetHTMLText(@&htmlObject)); end-method; method execute /+ &methodName as String, +/ /+ &inputString as String +/ /+ Returns String +/ /* use the PSGroovyAdapter java object to invoke the specified method with a string input parameter */ Return &jAdapter.invokeWithString(&methodName, &inputString); end-method;
Create a Groovy class as an HTML Object
Create an HTML Object called “GROOVYBASE64″ and paste the following Groovy class into it:
class PSBase64 { String encode(String input) { return input.bytes.encodeBase64().toString() } String decode(String input) { byte[] decoded = input.decodeBase64() String s = new String(decoded) return s } }
This simple little class provides two methods: “encode” takes a string and encodes it into Base64, while “decode” performs the reverse operation.
Use the GroovyAdapter in a PeopleCode Program to Dynamically Execute Groovy Code
Now you can use the GroovyAdapter PeopleCode class to load and use the PSBase64 Groovy class. You can do this in any PeopleCode event or IScript. Below, I’ve included a basic PSUnit test class showing you how to use the GroovyAdapter class. (Wait, not using PSUnit, you say? You should! Mike Kennedy, currently with CedarCrestone but formerly Director of Architecture for PeopleSoft Campus Solutions at Oracle, and Ben Harr, Campus Solutions Architect with Oracle, taught me to use this tool a couple of years ago. It’s a fantastic way of prototyping and testing PeopleCode!) I’ll plan on writing a future post on PSUnit.
import TTS_UNITTEST:*; import GROOVY:GroovyAdapter; class TestPSGroovyAdapter extends TTS_UNITTEST:TestBase method TestPSGroovyAdapter(); method setup(); method teardown(); method run(); end-class; method TestPSGroovyAdapter %Super = create TTS_UNITTEST:TestBase("TestPSGroovyAdapter"); %This.Msg("TestPSGroovyAdapter: constructor"); end-method; method run /+ Extends/implements TTS_UNITTEST:TestBase.Run +/ Local string &plaintext, &encoded, &decoded; Local GROOVY:GroovyAdapter &g; /* We'll Base64 encode and then decode the following string */ &plaintext = "DoSaveNow() still doesn't work in Component Interfaces..."; %This.Msg("Text to be Base64 encoded: " | &plaintext); /* create an instance of the GroovyAdapter PeopleCode class */ /* specify that the Groovy source is in the GROOVYBASE64 HTML object */ &g = create GROOVY:GroovyAdapter("GROOVYBASE64"); /* call the 'encode' method and pass a string parameter to be encoded into Base64 */ &encoded = &g.execute("encode", &plaintext); %This.Msg("Result of Groovy 'encode': " | &encoded); /* Now, call the decode method on the Groovy object passing in the encoded string*/ &decoded = &g.execute("decode", &encoded); %This.Msg("Result of Groovy 'decode': " | &decoded); /* use the PSUnit assert functionality to test the expected result */ %This.AssertStringsEqual(&plaintext, &decoded, "Decoded data does not match original text"); end-method; method setup /+ Extends/implements TTS_UNITTEST:TestBase.Setup +/ %This.Msg("TestPSGroovyAdapter: Setup()"); end-method; method teardown /+ Extends/implements TTS_UNITTEST:TestBase.Teardown +/ %This.Msg("TestPSGroovyAdapter: Teardown()"); end-method;
So,why go through all this trouble? Here’s my view of the upsides:
- I don’t have to bother server admins to deploy my Java code to the servers.
- I can make changes to the Groovy source code, save the HTML object, and my changes take effect immediately. It is not necessary to request a restart of server domains for the changes to be visible, as is needed when you deploy a new version of a Java class to the servers.
- The Groovy code is migrated along with the PeopleCode. No separate build/deploy/migrate process for Java class files on the servers (except for the one-time setup.) One less thing to manage and/or forget about!
What might we use Groovy to accomplish? Here are some ideas:
- Any encryption/decryption for algorithms not supported by PeopleTools
- Raw network socket communication
- Making HTTP POST requests without having to use the Integration Broker or Business Interlinks APIs (this is something I’ve been planning to do for quite some time. I’ll write a followup post on this one.)
- Binary file manipulations
Keep in mind this was a simple demo with very simple inputs and outputs. You can have multiple inputs and outputs by creating, for example, pipe-delimited strings, parsing it in your Groovy code, passing another delimited string back to your PeopleCode, and using the PeopleCode Split function to parse the return into an array of strings. Voila! Multiple input & output parameters. More on that later…
When writing Groovy classes, I highly recommend using the Groovy console for prototyping and testing. I’ll include one last bit of code and sign off: this is a Groovy script that declares the PSBase64 class, instantiates an object, and tests the two methods. Paste it into the Groovy console and run.
class PSBase64 { String encode(String input) { return input.bytes.encodeBase64().toString() } String decode(String input) { byte[] decoded = input.decodeBase64() String s = new String(decoded) return s } } PSBase64 b64 = new PSBase64(); String result = b64.encode("This is A Test"); println result; result = b64.decode(result); println result;
Good, I had issues with using the java reflection this is different to addresses.
Grooy, totally new to me, not sure if i can really try this one.
Hi,
My requirement is to convert peoplecode to java. I happened to see below blog link psguyblog.blogspot.com/2006/03/peoplecode-to-java.html, In one of the comment it is mentioned that using groovy we can get the Java bytecode. Did you have any idea on the same please let me know.
Thanks and Regards
NK
Thank you – great article.
Chris, this is very, very well done. Thank you for sharing your work in this regard. I am a HUGE fan of “scripting PeopleSoft” and you have shown a very valid way of accomplishing this.
Jim, thank you. This is high praise coming from you. You and Mr. Heller laid an excellent foundation, making the case for a simpler way to use Java from PeopleCode. I appreciate the feedback. | http://optimyzed.com/2012/03/try-groovy-baby/ | CC-MAIN-2014-15 | refinedweb | 2,102 | 61.16 |
[sec review] wordpress plugin to set admin language different from blog language
VERIFIED FIXED
Status
▸
Security Assurance: Review Request
People
(Reporter: craigcook, Assigned: mfuller)
Tracking
Attachments
(1 attachment)
1. Who is/are the point of contact(s) for this review? Myself 2. Please provide a short description of the feature / application (e.g. problem solved, use cases, etc.): We have a few blogs in non-English languages that need to be administrated by English speakers (currently blog.mozilla.org/laguaridadefirefox with more to come). To properly localize a blog we need to specify the language in a configuration file, which sets the language for the entire blog, both front-end and back-end. We also have English blogs whose authors may prefer to read the admin panel in their native language even if they're blogging in English. This plugin allows a blog's front-end to be a different language from its back-end, and lets the individual user select her/his preferred admin language. 3. Please provide links to additional information (e.g. feature page, wiki) if available and not yet included in feature description: The only available documentation is at or in German. You can browse the code repository at including revision history, if that's at all helpful. The plugin hasn't been updated in some time, but that may just mean it hasn't needed it. It works with current versions of WP in my own local testing and it's not much code (a single PHP file less than 300 lines). 4. Does this request block another bug? If so, please indicate the bug number Blocks bug 772418 - Portuguese version of The Den 5. This review will be scheduled amongst other requested reviews. What is the urgency or needed completion date of this review? We need to get the Portuguese Den online by the end of Q3. To allow some lead time it would be great to get this plugin reviewed by the end of August. 6. To help prioritize this work request, does this project support a goal specifically listed on this quarter's goal list? If so, which goal? We're releasing Firefox OS in Brazil at the end of Q3 (or is it early Q4?) so Brazil is a priority locale. The pt-BR Den is part of the engagement strategy for that launch. 7. Please answer the following few questions: (Note: If you are asked to describe anything, 1-2 sentences shall suffice.) > Does this feature or code change affect Firefox, Thunderbird or any product or service the Mozilla ships to end users? No. > Are there any portions of the project that interact with 3rd party services? No. > Will your application/service collect user data? If so, please describe No.
Time to break out my (non existent) German :) I'll take this and have it for you shortly. Thanks, Matt Fuller
Assignee: nobody → mfuller
Status: NEW → ASSIGNED
I've finished the review of this plugin; only one issue was found: an XSS vulnerability which I am creating a blocking bug for. The way the plugin uses the URL variable to set the language (such as en-US) allows an XSS by using an XSS payload. The selected language is included in a comment on every admin page, meaning it is saved and reflected. This will have to be fixed; either our devs can do it, or we can contact the plugin author to do so before we install. Thanks, Matt
I'm attaching my review notes. Once the blocking bug is fixed, feel free to proceed with installation. Thanks, Matt
Created attachment 646738 [details] Security Review Report
Wow, thanks for the speedy turnaround! I would have been happy if you got to it some time next week. I'm glad the issues were minor, and I was hoping as much given how simple the plugin is. If we don't hear from the author in the next week or so we'll just fix it ourselves.
No problem! So I've tried to find contact info for the dev, and unfortunately, I cannot find any contact info for them besides a Twitter account and Facebook page. I think it'd be quickest if we just fix this issue before installation ourselves. Do you know who would be installing this? I can work with them to point out the exact location of the issue. Thanks, Matt
(In reply to Matt Fuller :mfuller from comment #6) > So I've tried to find contact info for the dev, and unfortunately, I cannot > find any contact info for them besides a Twitter account and Facebook page. I found his contact page at including an e-mail address, bernhardkau [at] kau-boys.de I'll let you contact him since you're the expert and can explain the issue better. If he doesn't respond I can edit the code (and I'll file a separate bug for IT to push it to production). In that event I'd probably want to make our own fork with a different namespace, just to prevent possible conflicts down the road.
Thanks, didn't see that - I'll go ahead and email him about this and I'll update this if he replies. If he doesn't, I'll give it a day or two and then we can try editing it ourselves.
Hi Craig, Just an update on this - the developer replied to the email I sent and released a fix. However, the fix still had a couple issues so I'm working with him to get a full fix and it should be finished in 1-2 days (he literally has to change one word in the code). I'll update this and resolve the blocking bug as soon as he does. Thanks! Matt
Hi - the plugin has been updated (see 2.0.2 at) We should be good to go now :) Thanks! Matt
Status: ASSIGNED → RESOLVED
Last Resolved: 6 years ago
Resolution: --- → FIXED
Keywords: sec-review-needed → sec-review-complete
Whiteboard: [pending secreview] → [completed secreview][start 2012/07/27][end 2012/08/02]
Keywords: sec-review-complete
Status: RESOLVED → VERIFIED | https://bugzilla.mozilla.org/show_bug.cgi?id=778244 | CC-MAIN-2018-13 | refinedweb | 1,025 | 71.55 |
Herby's virtualplastic site has the answer
Basically, you're looking to create a namespace icon, with / without text. Take a look at - it gives you the way to do so, and also has several pre-made icons - but the best part is that with the tutorial you can make your own - I have already made several for mine, and currently have 12 textless icons on my desktop (you *can* have text on them, I just prefer not to).
Use GP
to enable Active desk top, create your shortcut change the icon using properties, prohibit changes to active desktop and other appropriate action!!
Creating a icon on desktop that cannot be deleted
Thanks in advance. If you need me to be clearer I, let me know and I will try.
This conversation is currently closed to new comments. | https://www.techrepublic.com/forums/discussions/creating-a-icon-on-desktop-that-cannot-be-deleted/ | CC-MAIN-2018-51 | refinedweb | 138 | 65.56 |
In a pyGame application, I would like to render resolution-free GUI widgets described in SVG.
What tool and/or library can I use to reach this goal ?
(I like the OCEMP GUI toolkit but it seems to be bitmap dependent for its rendering)
This is a complete example which combines hints by other people here. It should render a file called test.svg from the current directory. It was tested on Ubuntu 10.10, python-cairo 1.8.8, python-pygame 1.9.1, python-rsvg 2.30.0.
#!/usr/bin/python import array import math import cairo import pygame import rsvg WIDTH = 512 HEIGHT = 512 data = array.array('c', chr(0) * WIDTH * HEIGHT * 4) surface = cairo.ImageSurface.create_for_data( data, cairo.FORMAT_ARGB32, WIDTH, HEIGHT, WIDTH * 4) pygame.init() window = pygame.display.set_mode((WIDTH, HEIGHT)) svg = rsvg.Handle(file="test.svg") ctx = cairo.Context(surface) svg.render_cairo(ctx) screen = pygame.display.get_surface() image = pygame.image.frombuffer(data.tostring(), (WIDTH, HEIGHT),"ARGB") screen.blit(image, (0, 0)) pygame.display.flip() clock = pygame.time.Clock() while True: clock.tick(15) for event in pygame.event.get(): if event.type == pygame.QUIT: raise SystemExit
The question is quite old but 10 years passed and there is new possibility that works and does not require
librsvg anymore. There is Cython wrapper over nanosvg library and it works:
from svg import Parser, Rasterizer def load_svg(filename, surface, position, size=None): if size is None: w = surface.get_width() h = surface.get_height() else: w, h = size svg = Parser.parse_file(filename) rast = Rasterizer() buff = rast.rasterize(svg, w, h) image = pygame.image.frombuffer(buff, (w, h), 'ARGB') surface.blit(image, position)
I found Cairo/rsvg solution too complicated to get to work because of dependencies are quite obscure to install. | https://pythonpedia.com/en/knowledge-base/120584/svg-rendering-in-a-pygame-application | CC-MAIN-2020-16 | refinedweb | 292 | 64.27 |
The code in string/strcoll_l.c that computes a memory allocation size as (s1len + s2len) * (sizeof (int32_t) + 1) fails to allow for possible integer overflow in this computation. On a 32-bit host this can cause too-small allocations and consequent buffer overflow if the strings total more than 0.8GB. Testcase:
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 429496730
int
main (void)
{
char *p = malloc (1 + SIZE);
if (setlocale (LC_COLLATE, "en_GB.UTF-8") == NULL)
{
puts ("setlocale failed, cannot test for overflow");
return 0;
}
if (p == NULL)
{
puts ("malloc failed, cannot test for overflow");
return 0;
}
memset (p, 'x', SIZE);
p[SIZE] = 0;
printf ("%d\n", strcoll (p, p));
return 0;
}
It looks like the same issue is also present in strxfrm (not tested).
*** Bug 14552 has been marked as a duplicate of this bug. ***
Although this bug report regards the serious security vuln in strcoll, even if the overflow issues are fixed, a serious bug will remain. The strcoll interface does not permit failure. It must yield a consistent ordering. If it can fail sporadically from memory exhaustion, it can cause other interfaces using it (such as qsort) which rely on it to be a consistent ordering to invoke undefined behavior. While an immediate security fix is needed for the issues reported here, the implementation of strcoll calls for drastic redesign to be completely free of malloc or any other operation that could fail.
I've detailed another strcoll() security vulnerability below, which is an unbounded alloca() call.
alloca() stack overflow
If the malloc() call in alloca() fails (i.e. OOM conditions), strcoll() will failsafe to alloca() for allocating its memory, which could result in unbounded alloca() calls and exploitable
conditions if the stack pointer is shifted over the guard area and into the
heap. See vulnerable code below.
if (idx1arr == NULL)
/* No memory. Well, go with the stack then.
XXX Once this implementation is stable we will handle this
differently. Instead of precomputing the indeces we will
do this in time. This means, though, that this happens for
every pass again. */
goto try_stack;
use_malloc = 1;
}
else
{
try_stack:
idx1arr = (int32_t *) alloca (s1len * sizeof (int32_t));
idx2arr = (int32_t *) alloca (s2len * sizeof (int32_t));
rule1arr = (unsigned char *) alloca (s1len);
rule2arr = (unsigned char *) alloca (s2len);
[ ... ]
Here's my testcase / proof-of-concept for the issue.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
#define LEN 500000
int main() {
char *ptr1 = malloc(LEN + 1);
char *ptr2 = malloc(LEN + 1);
char *wasted = NULL;
int i = 0, ret = 0;
if(!ptr1 || !ptr2) {
printf("memory allocation failed\n");
return -1;
}
memset(ptr1, 0x61, LEN);
memset(ptr2, 0x61, LEN);
ptr1[LEN] = 0;
ptr2[LEN] = 0;
printf("strings allocated\n");
char *ptr = setlocale(LC_ALL, "en_US.UTF-8");
if(!ptr) {
printf("error setting locale\n");
return -1;
}
/* malloc() big chunks until we're out of memory */
do {
wasted = malloc(1000000);
printf("%p\n", wasted);
i++;
} while(wasted);
ret = strcoll(ptr1, ptr2);
if(!ret) {
printf("strings were lexicographically identical\n");
}
else {
printf("strings were different\n");
}
return 0;
}
Cheers,
Shaun
The unbounded alloca issue also appears to be present in strxfrm.
Patches to fix this issue:
Fixed in master:
commit 303e567a8062200dc06acde7c76fc34679f08d8f
Author: Siddhesh Poyarekar <siddhesh@redhat.com>
Date: Mon Sep 23 11:24:30 2013 +0530
Check for integer overflow in cache size computation in strcoll
strcoll is implemented using a cache for indices and weights of
collation sequences in the strings so that subsequent passes do not
have to search through collation data again. For very large string
inputs, the cache size computation could overflow. In such a case,
use the fallback function that does not cache indices and weights of
collation sequences.
Fixes CVE-2012-4412.
commit 141f3a77fe4f1b59b0afa9bf6909cd2000448883
Author: Siddhesh Poyarekar <siddhesh@redhat.com>
Date: Mon Sep 23 11:20:02 2013 +0530
Fall back to non-cached sequence traversal and comparison on malloc fail
strcoll currently falls back to alloca if malloc fails, resulting in a
possible stack overflow. This patch implements sequence traversal and
comparison without caching indices and rules.
Fixes CVE-2012-4424.!
get_next_seq_nocache() that is.
?
It should finish a few minutes before forever :)
The *_nocache code is O(n^3) (IIRC), so it's very very slow. If it has to crash due to a buffer or stack overflow, it ought to be gone in a few minutes based on some arbitrary tests I did by introducing buffer overflows and accesses beyond bounds in the code.
I've added an xtest (i.e. an optional test, which you can run using `make xcheck`) that does exactly this - run the reproducer and signal a success if the program doesn't crash in about five minutes.
If you want to do a correctness test then I'd suggest commenting out the get_next_seq_cached paths so that get_next_seq_nocache is called all the time and then run your usual strcoll correctness tests.
Maybe we could add some internal test hooks that allow us to do this seamlessly.
(In reply to Siddhesh Poyarekar from comment #10)
> It should finish a few minutes before forever :)
>
> The *_nocache code is O(n^3) (IIRC), so it's very very slow.
Hi. Thanks for your quick reply. With that kind of complexity I'll adopt your heuristic: if no failure in 5 minutes, assume success.
> If you want to do a correctness test then I'd suggest commenting out the
> get_next_seq_cached paths so that get_next_seq_nocache is called all the
> time and then run your usual strcoll correctness tests.
Thanks for the suggestion, I'll force get_next_seq_nocache and run my strcoll faithfulness tests.
*** Bug 260998 has been marked as a duplicate of this bug. ***
Seen from the domain
Page where seen:
Marked for reference. Resolved as fixed @bugzilla. | https://sourceware.org/bugzilla/show_bug.cgi?id=14547 | CC-MAIN-2017-51 | refinedweb | 953 | 63.8 |
How do you put the database on?
There's a local whale of a river that's going to decorate the hosting, how can the database be similarly demolished?
Normally, no one copies a database from one server to another, including because test data are used in the developers ' database and the combat database is real, which cannot be rewritten.
In fact, it is necessary for developers to change the OBD scheme and to provide background data (country lists, city telephone codes, etc.). The migration mechanism is used.
Under different platforms, this can be done differently. I'll tell you from my experience how this is done in Entity Framework.
First, in order to avoid duplication, the structure of the base is not stored in the form of DDL scruples (in order to avoid duplication).
CREATE TABLEand other) and classes .NET.
[Table("Users")] public class User { [Key] public Guid Id { get; set; }
public string Login { get; set; } [MaxLength(512)] public byte[] PasswordHash { get; set; }
All tables that are included in the OBD are listed in the assigned class, which is known as database context:
public class BlogDbContext : DbContext
{
public DbSet<User> Users { get; set; }
}
At the beginning of the work, we need to create the first BD Blind for work (first migration). In fact, the Entity Framework code is investigating
BlogDbContextand
Userand prepare violators to generate the table
Usersand the necessary indices. PowerShell-comanda is used to create migration
Add-Migration♪
Add-Migration Initial
The violette will look like this:
public partial class Initial : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Users",
c => new
{
Id = c.Guid(nullable: false),
Login = c.String(nullable: false),
PasswordHash = c.ByteArray(maxlength: 512),
})
.PrimaryKey(t => t.Id);
}
public override void Down() { DropTable("dbo.Users"); }
As you can see, the crypt comprises two branches: to move forward on the list of migrations (method)
Up) and to roll back (method)
Down)
Now, please note, the OBD scheme is part of the entire rest of the project reference code and is distributed with it.
If we need to change the scheme, we do it, for example, add a new class tablet or a new field, and we start again.
Add-Migration♪ Entity Framework generates again a class that updates the scheme. In the vast majority of cases, you won't need to manually rule the code, but you can do it, for example, if you need a non-standard index.
What now? You publish your code on the combat server. In the next address to your server, the diagram is checked and, if necessary, all updates to the diagram are rolled out transparently.
Up)
As a result, the database is being upgraded with all the other codes and, by the way, not only on the combat server, but also between the developers.
Suggested Topics
-
-
-
-
-
Path is wrong while running a job created for GitHub repository using webhook
Automated Testing • • baileigh
-
What does the database cast() function call in the ORDER method of a database in a LINQ expression in C# C#?
Software Programming • • Saumya
-
-
-
-
CHECKDB found 0 allocation errors and 0 consistency errors in database sql server found 0 allocation errors and 0 consistency errors in database
Software Programming • • Rossere
-
- | https://software-testing.com/topic/891743/how-do-you-put-the-database-on | CC-MAIN-2022-21 | refinedweb | 533 | 59.23 |
26 April 2007 08:57 [Source: ICIS news]
SINGAPORE (ICIS news)--Dutch storage firm Vopak on Thursday reported a 28% year-on-year rise in first quarter operating profit excluding exceptionals as it filled more of its terminals and flagged an expected 15%-20% rise in 2007.
The company said it was raising its earnings forecast for the year due to an excellent first quarter and a healthy outlook.
Operating profit for the three months ending 31 March 2007 was €67.6m ($91.9m), up from €52.8m in the same period a year earlier. Before exceptionals, operating profit rose 31% to €69m.
The company attributed the earnings growth to increased capacity, higher occupancy rates and improved margins.
Its Chemicals Europe, Middle East & Africa division further improved occupancy rates and margins, and increased operating profit for the quarter by 69% to €20.9m.
Additional capacity was commissioned at the ?xml:namespace>
Operating profit at the Asia division rose 14% to €19.2m due to commissioning of new chemicals terminals in Banyan (
In
($1 = €0 | http://www.icis.com/Articles/2007/04/26/9023932/vopak-q1-op-profit-up-28-with-healthy-outlook.html | CC-MAIN-2013-48 | refinedweb | 174 | 56.45 |
cant get my upit() function to work! cant find anything wrong.
ive made 2 attempts in the upit() both of them dont work. can anyone give me a kick in the face to the right direction? thanks in advance.ive made 2 attempts in the upit() both of them dont work. can anyone give me a kick in the face to the right direction? thanks in advance.Code:#include<iostream> #include<cctype> #include<cstring> using namespace std; class String //user-defined string type { private: char* str; //pointer to string public: String(char* s) { int length = strlen(s); //length of string argument str = new char[length+1]; //get memory strcpy(str,s); //copy string } ~String() { cout << "Deleting str.\n"; delete[] str; } void upit() //convert to uppercase if necessary { int length = strlen(str); for(int i = 0; i <= length; i++) toupper(*str+i); //int i = 0; //while( *(str+i) != '\0' ) //{ // toupper(*(str+i)); // i++; //} } void display() //display the string { cout << str << endl; } }; | http://cboard.cprogramming.com/cplusplus-programming/61622-my-upit-using-toupper-cctype-h.html | CC-MAIN-2014-52 | refinedweb | 160 | 75.61 |
Raspberry gPIo button presses.
This tutorial applies to the Raspberry Pi Model B, the Raspberry Pi Model B+ and the new Raspberry Pi 2 Model B.
Driving the Raspberry Pi's I/O lines requires a bit of programming. Programming in what language? Take your pick! A quick glance at the Raspberry Pi GPIO examples shows that there are dozens of programming-language-choices. We've pared that list down, and ended up with two really solid, easy tools for driving I/O: Python and C (using the WiringPi library).
If you've never driven an LED or read in a button press using the Raspberry Pi, this tutorial should help to get you started. Whether you're a fan of the easily-readable, interpretive scripting language Python or more of a die-hard C programmer, you'll find a programming option that suits our needs.
Covered In This Tutorial
In this tutorial we'll show two different approaches to reading and driving the Raspberry Pi's GPIO pins: python and C. Here's a quick overview of what's covered:
- GPIO Pinout -- An overview of the Pi's GPIO header.
- Python API and Examples
- RPi.GPIO API -- An overview of the Python functions you can use to drive GPIO.
- of the basic functions provided by the WiringPi library.
- WiringPi Example -- A simple example program that shows off WiringPi's input and output capabilities.
- Using an IDE -- How to download and install Geany. Our favorite IDE for programming on the Raspberry Pi.
Each programming language has it's share of pros and cons. Python is easy (especially if your a programming novice) and doesn't require any compilation. C is faster and may be easier for those familiar with the old standby.
What You'll Need
Here's a wishlist-full of everything we used for this tutorial.
Some further notes on that bill of materials:
- Your Raspberry Pi should have an SD card with Raspbian installed on it. Check out our How to Install Raspbian tutorial for help with that.
- We're also assuming you have the necessary mouse, keyboard and display hooked up to your Pi.
- Your Pi will need an Internet connection to download WiringPi. You can use either Ethernet or WiFi (check out our Raspberry Pi WiFi tutorial for help with that.
- The Pi Wedge isn't quite required, but it does make life a lot easier. If you want to skip the breakout, you can instead use Male-to-Female jumpers to connect from Pi to breadboard.
- Of course, feel free to swap in your preferred button and LEDs.
Suggested Reading
This tutorial will assume you have Raspbian installed on your Raspberry Pi. Raspbian is the most popular, well-supported Linux distribution available for the Pi. If you don't have Raspbian set up, check out our Setting Up Raspbian tutorial before continuing down this rabbit hole.
Other, more general purpose tutorials you might be interested in reading include:
- Pulse-Width Modulation -- You can use PWM to dim LEDs or send signals to servo motors. The RPi has a single PWM-capable pin.
- Light-Emitting Diodes (LEDs) -- To test the output capabilities of the Pi, we'll be driving a lot of LEDs.
- Switch Basics -- And to test inputs to the Pi, we'll be using buttons and switches.
- Pull-Up Resistors -- The Pi has internal pull-up (and pull-down) resistors. These are very handy when you're interfacing buttons with the little computer.
Suggested Viewing
Check out our Raspberry Pi video tutorials if you want a more visual introduction to the Pi!
GPIO Pinout
The Raspberry Pi offers up its GPIO over a standard male header on the board. Over the years the header has expanded from 26 pins to 40 pins while maintaining the original pinout.
If you're coming to the Raspberry Pi as an Arduino user, you're probably used to referencing pins with a single, unique number. Programming the Pi's hardware works much the same, each pin has its own number...and then some.
There are (at least) two, different numbering schemes you may encounter when referencing Pi pin numbers: (1) Broadcom chip-specific pin numbers and (2) P1 physical pin numbers. You're usually free to use either number-system, but many programs require that you declare which scheme you're using at the very beginning of your program.
Here's a table showing all 26 pins on the P1 header, including any special function they may have, and their dual numbers:
This table shows the Pi pin header numbers, element14 given names, wiringPi numbers, Python numbers, and related silkscreen on the wedge.
Note: The Broadcom pin numbers above relate to Pi Model 2 and later only. If you have an older Rev1 Pi, check out this link for your Broadcom pin numbers.
As you can see, the Pi not only gives you access to the bi-directional I/O pins, but also Serial (UART), I2C, SPI, and even some PWM ("analog output").
Hardware Setup
To get a head start you can assemble the circuit now. We'll use this setup for both the C and Python examples. We'll use two LEDs to test the output functionality (digital and PWM), and a button to test the input.
Our two LEDs are connected to the Pi's GPIO 18 and GPIO 23 -- those are the Broadcom chip-specific numbers. If you're basing your wiring off the P1 connector pin numbers, that'd be pins 12 and 16.
The button is connected to Broadcom GPIO 17, aka P1 pin 11.
If you have Pi Wedge, the hookup should be pretty straight-forward. It'll look a little something like this when you're done:
If you don't have a Pi Wedge, male-to-female jumper wires help to make an easy transition from Pi to breadboard.
Python (RPi.GPIO) API
We'll use the RPi.GPIO module as the driving force behind our Python examples. This set of Python files and source is included with Raspbian, so assuming you're running that most popular Linux distribution, you don't need to download anything to get started.
On this page we'll provide an overview of the basic function calls you can make using this module.
Setup Stuff
In order to us RPi.GPIO throughout the rest of your Python script, you need to put this statement at the top of your file:
language:Python import RPi.GPIO as GPIO
That statement "includes" the RPi.GPIO module, and goes a step further by providing a local name --
GPIO -- which we'll call to reference the module from here on.
Pin Numbering Declaration
After you've included the RPi.GPIO module, the next step is to determine which of the two pin-numbering schemes you want to use:
GPIO.BOARD-- Board numbering scheme. The pin numbers follow the pin numbers on header P1.
GPIO.BCM-- Broadcom chip-specific pin numbers. These pin numbers follow the lower-level numbering system defined by the Raspberry Pi's Broadcom-chip brain.
If you're using the Pi Wedge, we recommend using the
GPIO.BCM definition -- those are the numbers silkscreened on the PCB. The
GPIO.BOARD may be easier if you're wiring directly to the header.
To specify in your code which number-system is being used, use the
GPIO.setmode() function. For example...
language:Python GPIO.setmode(GPIO.BCM)
...will activate the Broadcom-chip specific pin numbers.
Both the
import and
setmode lines of code are required, if you want to use Python.
Setting a Pin Mode
If you've used Arduino, you're probably familiar with the fact that you have to declare a "pin mode" before you can use it as either an input or output. To set a pin mode, use the
setup([pin], [GPIO.IN, GPIO.OUT] function. So, if you want to set pin 18 as an output, for example, write:
language:Python GPIO.setup(18, GPIO.OUT)
Remember that the pin number will change if you're using the board numbering system (instead of 18, it'd be 12).
Outputs
Digital Output
To write a pin high or low, use the
GPIO.output([pin], [GPIO.LOW, GPIO.HIGH]) function. For example, if you want to set pin 18 high, write:
language:Python GPIO.output(18, GPIO.HIGH)
Writing a pin to
GPIO.HIGH will drive it to 3.3V, and
GPIO.LOW will set it to 0V. For the lazy, alternative to
GPIO.HIGH and
GPIO.LOW, you can use either
1,
True,
0 or
False to set a pin value.
PWM ("Analog") Output
PWM on the Raspberry Pi is about as limited as can be -- one, single pin is capable of it: 18 (i.e. board pin 12).
To initialize PWM, use
GPIO.PWM([pin], [frequency]) function. To make the rest of your script-writing easier you can assign that instance to a variable. Then use
pwm.start([duty cycle]) function to set an initial value. For example...
language:Python pwm = GPIO.PWM(18, 1000) pwm.start(50)
...will set our PWM pin up with a frequency of 1kHz, and set that output to a 50% duty cycle.
To adjust the value of the PWM output, use the
pwm.ChangeDutyCycle([duty cycle]) function.
[duty cycle] can be any value between 0 (i.e 0%/LOW) and 100 (ie.e 100%/HIGH). So to set a pin to 75% on, for example, you could write:
language:Python pwm.ChangeDutyCycle(75)
To turn PWM on that pin off, use the
pwm.stop() command.
Simple enough! Just don't forget to set the pin as an output before you use it for PWM.
Inputs
If a pin is configured as an input, you can use the
GPIO.input([pin]) function to read its value. The
input() function will return either a
True or
False indicating whether the pin is HIGH or LOW. You can use an
if statement to test this, for example...
language:Python if GPIO.input(17): print("Pin 11 is HIGH") else: print("Pin 11 is LOW")
...will read pin 17 and print whether it's being read as HIGH or LOW.
Pull-Up/Down Resistors
Remember back to the
GPIO.setup() function where we declared whether a pin was an input or output? There's an optional third parameter to that function, which you can use to set pull-up or pull-down resistors. To use a pull-up resistor on a pin, add
pull_up_down=GPIO.PUD_UP as a third parameter in
GPIO.setup. Or, if you need a pull-down resistor, instead use
pull_up_down=GPIO.PUD_DOWN.
For example, to use a pull-up resistor on GPIO 17, write this into your setup:
language:Python GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
If nothing is declared in that third value, both pull-resistors will be disabled.
Etc.
Delays
If you need to slow your Python script down, you can add delays. To incorporate delays into your script, you'll need to include another module:
time. This line, at the top of your script, will do it for you:
language:Python include time
Then, throughout the rest of your script, you can use
time.sleep([seconds]) to give your script a rest. You can use decimals to precisely set your delay. For example, to delay 250 milliseconds, write:
language:Python time.sleep(0.25)
The time module includes all sorts of useful functions, on top of
sleep. Check out the reference here.
Garbage Collecting
Once your script has run its course, be kind to the next process that might use your GPIOs by cleaning up after yourself. Use the
GPIO.cleanup() command at the end of your script to release any resources your script may be using.
Your Pi will survive if you forget to add this command, but it is good practice to include wherever you can.
Now then. Lets incorporate everything we learned here into an example script to try everything out..
C (WiringPi) API
On this page we'll discuss some of the most useful functions provided by the WiringPi library. It's tailored to look a lot like Arduino, so if you've done any Arduino programming some of this may look familiar.
Setup Stuff
To begin, you'll need to include the library. At the beginning of your program, type:
language:c #include <wiringPi.h>
After you've included the library, your first steps should be to initialize it. This step also determines which pin numbering scheme you'll be using throughout the rest of your program. Pick one of these function calls to initialize the library:
language:c wiringPiSetup(); // Initializes wiringPi using wiringPi's simlified number system. wiringPiSetupGpio(); // Initializes wiringPi using the Broadcom GPIO pin numbers
WiringPi's simplified number system introduces a third pin-numbering scheme. We didn't show it in the table earlier, if you want to use this scheme, check out their pins page for an overview.
Pin Mode Declaration
To set a pin as either an input or output, use the
pinMode([pin], [mode]) function. Mode can be either
INPUT,
OUTPUT, or
PWM_OUTPUT.
For example, to set pin 22 as an input, 23 as an output, and 18 as a PWM, write:
language:c wiringPiSetupGpio() pinMode(17, INPUT); pinMode(23, OUTPUT); pinMode(18, PWM_OUTPUT);
Keep in mind that the above example uses the Broadcom GPIO pin-numbering scheme.
Digital Output
The
digitalWrite([pin], [HIGH/LOW]) function can be used to set an output pin either HIGH or LOW. Easy enough, if you're an Arduino user.
To set pin 23 as HIGH, for example, simply call:
language:c digitalWrite(23, HIGH);
PWM ("Analog") Output
For the lone PWM pin, you can use
pwmWrite([pin], [0-1023]) to set it to a value between 0 and 1024. As an example...
language:c pwmWrite(18, 723);
...will set pin 18 to a duty cycle around 70%.
Digital Input
If you're an Arduino veteran, you probably know what comes next. To read the digital state of a pin,
digitalRead([pin]) is your function. For example...
language:c if (digitalRead(17)) printf("Pin 17 is HIGH\n"); else printf("Pin 17 is LOW\n");
...will print the status of pin 22. The
digitalRead() function returns 1 if the pin is HIGH and 0 if it's LOW.
Pull-Up/Down Resistors
Need some pull-up or pull-down resistors on your digital input? Use the
pullUpDnControl([pin], [PUD_OFF, PUD_DOWN, PUD_UP]) function to pull your pin.
For example, if you have a button on pin 22 and need some help pulling it up, write:
language:c pullUpDnControl(17, PUD_UP);
That comes in handy if your button pulls low when it's pressed.
Delays
Slowing down those blinking LEDs is always useful -- assuming you actually want to differentiate between on and off. WiringPi includes two delay functions to choose from:
delay([milliseconds]) and
delayMicroseconds([microseconds]).
The standard delay will halt the program flow for a specified number of milliseconds. If you want to delay for 2 seconds, for example, write:
language:c delay(2000);
Or you can use
delayMicroseconds() to get a more precise, microsecond-level delay.
Now that you know the basics, let's apply them to an example piece of code.
C (WiringPi) Example
The intention of WiringPi is to make your I/O code look as Arduino-ified as possible. However keep in mind that we're no longer existing in the comfy confines of Arduino -- there's no
loop() or
setup(), just
int main(void).
Follow along here as we create an example C file, incorporate the WiringPi library, and compile and run that program.
Create blinker.c
Using the terminal, navigate to a folder of your choice and create a new file -- "blinker.c". Then open that file in a text editor (Nano or Leafpad are included with Raspbian).
pi@raspberrypi ~/code $ mkdir c_example
pi@raspberrypi ~/code $ cd c_example
pi@raspberrypi ~/code/c_example $ touch blinker.c
pi@raspberrypi ~/code/c_example $ leafpad blinker.c &
The commands above will open your "blinker.c" file in Leafpad, while leaving your terminal functioning -- in-directory -- in the background.
Program!
Here's an example program that includes a little bit of everything we talked about on the last page. Copy and paste, or write it yourself to get some extra reinforcement.
language:c #include <stdio.h> // Used for printf() statements #include <wiringPi.h> // Include WiringPi library! // Pin number declarations. We're using the Broadcom chip pin numbers. const int pwmPin = 18; // PWM LED - Broadcom pin 18, P1 pin 12 const int ledPin = 23; // Regular LED - Broadcom pin 23, P1 pin 16 const int butPin = 17; // Active-low button - Broadcom pin 17, P1 pin 11 const int pwmValue = 75; // Use this to set an LED brightness int main(void) { // Setup stuff: wiringPiSetupGpio(); // Initialize wiringPi -- using Broadcom pin numbers pinMode(pwmPin, PWM_OUTPUT); // Set PWM LED as PWM output pinMode(ledPin, OUTPUT); // Set regular LED as output pinMode(butPin, INPUT); // Set button as INPUT pullUpDnControl(butPin, PUD_UP); // Enable pull-up resistor on button printf("Blinker is running! Press CTRL+C to quit.\n"); // Loop (while(1)): while(1) { if (digitalRead(butPin)) // Button is released if this returns 1 { pwmWrite(pwmPin, pwmValue); // PWM LED at bright setting digitalWrite(ledPin, LOW); // Regular LED off } else // If digitalRead returns 0, button is pressed { pwmWrite(pwmPin, 1024 - pwmValue); // PWM LED at dim setting // Do some blinking on the ledPin: digitalWrite(ledPin, HIGH); // Turn LED ON delay(75); // Wait 75ms digitalWrite(ledPin, LOW); // Turn LED OFF delay(75); // Wait 75ms again } } return 0; }
Once you've finished, Save and return to your terminal.
Compile and Execute!
Unlike Python, which is an interpreted language, before we can run our C program, we need to build it.
To compile our program, we'll invoke gcc. Enter this into your terminal, and wait a second for it to finish compiling:
pi@raspberrypi ~/code/c_example $ gcc -o blinker blinker.c -l wiringPi
That command will create an executable file -- "blinker". The "-l wiringPi" part is important, it loads the wiringPi library. A successful compilation won't produce any messages; if you got any errors, try to use the messages to track them down.
Type this to execute your program:
pi@raspberrypi ~/code/c_example $ sudo ./blinker
The blinker program should begin doing it's thing. Make sure you've set up the circuit just as modeled on the hardware setup page. Press the button to blink the LED, release to have it turn off. The PWM-ing LED will be brightest when the button is released, and dim when the button is pressed.
If typing all of that code in a bland, black-and-white, non-highlighting editor hurt your brain, check out the next page where we introduce a simple IDE that makes your programming more efficient.
Using an IDE!
Thus far we've been using simple text-editors -- Leafpad or Nano -- to write our Python and C programs. So seasoned programmers are probably missing a whole lot of features assumed of even the most basic editors: auto-tabbing, context-highlighting, even automated building. If you want to incorporate any of those features, we recommend using an IDE (integrated development environment). One of our favorite Pi IDE's is Geany, here's how to get it up and running.
Download and Install Geany
Geany isn't included with Raspbian, so you'll need an Internet connection to download it. You can use the magical
apt-get utility to install it with this command:
pi@raspberrypi ~/code $ sudo apt-get update
pi@raspberrypi ~/code $ sudo apt-get install geany
Once installed, you can run Geany by going to the "Start" menu, and looking under the "Programming" tab.
Or, from the terminal, you can type
sudo geany. You can even open a file in Geany, directly from the command line. To open our previous C file, for example, type
sudo geany blinker.c.
Using Geany...
Once Geany is running, you can create a new file by going to File > New. Saving the file as either ".c" or ".py" (or any other common language file extension) will immediately inform Geany what kind of language you're working with, so it can start highlighting your text.
Geany can be used with most languages, including the Python and C examples we've just examined. Some tweaks to the default IDE options are necessary, though. Here's an overview of using Geany with each language.
...with C and WiringPi
Let's recreate our WiringPi Example with Geany. Open the "blinker.c" created earlier within the confines of Geany. You should immediately be presented with some very pleasant color-coding.
Before trying to compile the code, though, you'll need to tweak some of the build options. Go up to Build and Set Build Commands. Inside the "Compile" and "Build" text blocks, tack this on to the end of the default command:
-l wiringPi. That will load the wiringPi library.
While you're here, add "sudo" to the beginning of your execute command. Make sure your build commands look like the window above and click "OK".
Once you've adjusted that setting, you should be ready to go. Click the Build menu, then click Build (or click the red cinder-block-looking icon up top). Upon building, the IDE will switch focus to the bottom "Compiler" tab, and relay the results of your compilation. If the build was successful, go ahead and run with it.
To run your built file, click Build > Execute (or click the gear icon up top). Executing will bring up a new terminal window, and start your program running. You can stop the program by pressing CTRL+C in the terminal window.
...with Python
You can also use Geany with Python. To test it out, go ahead an open up the "blinker.py" file we created earlier. As with the C file, you'll be greeted with some pleasnt context highlighting.
No building required with Python! Once you're script is written, simply click the "Execute" gear up top. Again, running will produce a separate terminal to pop up. To exit, simply press CTRL+C.
Geany has tons of features beyond what we've covered here. Check out the tabs at the bottom. Check out the menus up top. Experiment and see how the IDE can make your programming life easier!
Resources and Going Further.
If you're looking for some project inspiration, here are some more SparkFun tutorials where you'll be able to leverage your newfound Pi programming skills:
- Raspberry Pi Twitter Monitor -- How to use a Raspberry Pi to monitor Twitter for hashtags and blink an LED.
- Getting Started with the BrickPi -- How to connect your Raspberry Pi to Lego Mindstorms, using the BrickPi. | https://learn.sparkfun.com/tutorials/raspberry-gpio | CC-MAIN-2020-16 | refinedweb | 3,797 | 65.62 |
On Wed, Dec 23, 2009 at 2:36 PM, Kenneth Russell <kbr@google.com> wrote: > [...] > The WebGL working group's intent with this interface was to allow a > JavaScript object literal to be passed in for this argument. (Someone > please correct me if I'm misspeaking.) > > How would we need to change the IDL to allow this? From looking at the > WebIDL spec you pointed to, it looks like the issue is the presence of > the setters / getters, and that this would satisfy the requirements: > > interface WebGLContextAttributes { > attribute boolean alpha; > attribute boolean depth; > attribute boolean stencil; > attribute boolean antialias; > attribute boolean premultipliedAlpha; > }; Going by <>, I think you'd need "[Callback] interface WebGLContextAttributes { ...as above... }" and then it might be right. But I'm definitely not an expert on WebIDL, so it'd probably be good to ask someone who is :-) One difficulty with that context attribute syntax is what happens when someone writes: c.getContext('webgl', { get alpha() { alert('alpha'); return false; } }); because the getter function will be called whenever the implementation tries to retrieve the attribute value, and it ought to be specified when and how often that happens. (e.g. is it only called during the getContext call, or could it be run at an arbitrary time in the future?) I believe there have been similar discussions about how to design an API with key/value pairs in the W3C public-webapps mailing list (related to selector namespaces) but I don't know if there was any conclusion about good or bad ways to do it. > By the way, I and perhaps others have been looking at > , which it looks like is out of date. Yeah, I think it'd be better to use the latest editor's draft rather than the year-old snapshot, since it's likely to be much more correct and stable. HTML5 already uses the syntax and definitions from the editor's draft. -- Philip Taylor excors@gmail.com ----------------------------------------------------------- You are currently subscribe to public_webgl@khronos.org. To unsubscribe, send an email to majordomo@khronos.org with the following command in the body of your email: | https://www.khronos.org/webgl/public-mailing-list/archives/0912/msg00027.php | CC-MAIN-2015-40 | refinedweb | 352 | 60.45 |
SVG is a language for describing two-dimensional graphics in XML [XML10]. SVG allows for three types of graphic objects: vector graphic shapes (e.g., paths consisting of straight lines and curves), multimedia (such as raster images and video) and text. Graphical objects can be grouped, styled, transformed and composited into previously rendered conformance with the Web Architecture SVG Mobile 1.1 specificationatic.
This specification describes a collection of abstract modules that provide specific units "Structure Module".
Modules define a named collection of either elements or attributes. These collections are used as a shorthand when describing the set of attributes allowed on a particular element (eg. the "Style" attibute collection) or the set of elements allowed as children of a particular element (eg. the "Shape" element collection). All collections have names that begin with an uppercase character.
When defining a profile, it is assumed that all the element and attribute collections are defined to be empty. That way, a module can redefine the collection as it is included in the profile, adding elements or attributes to make them available within the profile. Therefore, it is not a mistake to refer to an element or attribute collection from a module that is not included in the profile, it simply means that collection is empty..
SVG Tiny 1.2 is a backwards compatible upgrade to SVG Tiny 1.1 . A few key differences from SVG Tiny 1.1 should be noted:
The namespace for SVG Tiny 1.2 is the same as that of SVG 1.0 and 1.1,
Here is an example of an SVG 1.2 file:
< PUBLIC "-//W3C//DTD SVG 1.2 Tiny//EN" [ <=""> <desc>This example shows an entity from a DOCTYPE declaration being used.<. | http://www.w3.org/TR/2005/WD-SVGMobile12-20050413/intro.html | CC-MAIN-2018-13 | refinedweb | 288 | 58.79 |
insertion sort
insertion sort write a program in java using insertion sort
bubble sort
bubble sort write a program in java using bubble sort
Extra Storage Merge Sort in Java
Extra Storage Merge Sort in Java
...]
Where n must be even number.
Steps of Merge Sort:
Say...
In this example we are going to sort integer values of an array using
EVEN NUMBERS - Java Interview Questions
EVEN NUMBERS i want program of even numbers?i want source code plz reply? Hi Friend,
Try the following code:
class EvenNumbers... counter = 0;
System.out.println("Even Numbers are:" );
for (int i
bubble sort - Java Beginners
bubble sort how to write program
The bubble-sort algorithm in double... Hi friend,
Bubble Sort program :
public class...[] = {10,5,3,89,110,120,1,8,2,12};
System.out.println("Values Before the sort:\n
even more circles - Java Beginners
even more circles Write an application that compares two circle objects.
? You need to include a new method equals(Circle c) in Circle class. The method compares the radiuses.
? The program reads two radiuses from the user
Selection Sort In Java
Selection Sort In Java
... are going to sort the values of an array using
selection sort.In selection sorting.... Sort the
remaining values by using same steps. Selection sort
Post your Comment | http://www.roseindia.net/discussion/18537-Odd-Even-Transposition-Sort-In-Java.html | CC-MAIN-2014-52 | refinedweb | 218 | 59.7 |
Opened 3 years ago
Closed 3 years ago
Last modified 3 years ago
#20006 closed Bug (worksforme)
Converting a datestring into a proper date from and AJAX call
Description
When an AJAX call passes a date in a Django L10N/I18N site, the date will be a string, formatted according to the current users locale.
This means that on the server, Django needs to convert this string into a proper date, taking the locale of the user into account. I can't find a way to do so.
The only lead I have found was to use Python's time.strptime() function, and use Django's django.utils.formats.get_format() function to pass it the correct format. However, Django's get_format() function returns "j-n-Y" for me (user with Dutch locale), which is not a valid format for the strptime() function.
USE_L10N is True, and USE_I18N is also True.
def StringToDate(datestring): from django.utils.formats import get_format from time import strptime short_datetime_format = get_format("SHORT_DATE_FORMAT") return strptime(datestring, short_datetime_format)
ValueError: time data u'08-03-2013' does not match format 'j-n-Y'
Change History (2)
comment:1 Changed 3 years ago by claudep
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
- Resolution set to worksforme
- Status changed from new to closed
comment:2 Changed 3 years ago by erik@…
Thank you claudep,
For anyone Googling, the solution would be something like this:
from django.forms.fields import DateField dt = request.GET.get('date', '') fld = DateField() formatted_datetime = fld.to_python(dt)
If you are passing your value through the forms API (and a DateField), you should be safe. Otherwise, see django.forms.fields.BaseTemporalField.to_python method if you want to emulate a similar behaviour in custom code.
If you still think there is a bug somewhere, please try to provide a test case to reproduce it. | https://code.djangoproject.com/ticket/20006 | CC-MAIN-2016-26 | refinedweb | 308 | 54.12 |
Hey smart peeps!
Please help me figure out what I'm doing wrong here, code below:
// include the library code:
#include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(19, 23, 18, 17, 16, 15);
void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("circuitschools.");
}
void loop() {
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 1);
// print the number of seconds since reset:
lcd.print(millis() / 1000);
}
10k potentiometer
This is the tutorial I followed: Interfacing 16X2 LCD Module with ESP32 with and without I2C – Circuit Schools
More images to follow!
Thanks in advance | https://forum.arduino.cc/t/please-help-me-figure-out-what-im-doing-wrong-printing-to-the-lcd/917098 | CC-MAIN-2021-49 | refinedweb | 130 | 64.91 |
In this Quick Tip on the Flash Professional Components, we will be taking a look at the CheckBox and RadioButton Components.
Brief Overview
In the preview you see a single checkbox at the top. When this checkbox is selected the checkbox's label will change to say "Checked" or "Not Checked".
With the bottom six checkboxes you can select what sports you are interested in and the text area below will update to show the changes. With the radio buttons on the right you are only able to select one option; the label will change each time you make a selection and update to say which option you have chosen.
Step 1: Setting up the Document
Open a new Flash Document and set the following properties:
- Document Size: 550x400px
- Background Color: #FFFFFF
Step 2: Add Components to the Stage
Open the Components panel (Menu > Window > Components or CTRL+F7).
Drag four labels, seven checkboxes, three radio buttons and one text area to the stage.
In the Properties panel give the first checkbox the instance name "toggleCheckBox".
If the Properties panel is not showing go to Menu > Window > Components or press CTRL+F3.
Set the checkbox's X to 5.00 and its Y to 21.00.
Note: Now follows a fairly repetitive process until we have all our components set up - hang in there :)
In the Properties panel give the second checkbox the instance name "swimmingCheckBox". Set the checkbox's X to 5.00 and its Y to 91.00.
In the Properties panel give the third checkbox the instance name "footBallCheckBox". Set the checkbox's X to 116.00 and its Y to 191.00.
In the Properties panel give the fourth checkbox the instance name "hikingCheckBox". Set the checkbox's X to 5.00 and its Y to 127.00.
In the Properties panel give the fifth checkbox the instance name "soccerBox". Set the checkbox's X to 116.00 and its Y to 127.00.
In the Properties panel give the sixth checkbox the instance name "boxingCheckBox". Set the checkbox's X to 5.00 and its Y to 161.00.
In the Properties panel give the seventh checkbox the instance name "baseballCheckBox". Set the checkbox's X to 116.00 and its Y to 161.00.
In the Properties panel give the first label the instance name "sportsLabel". Set the label's X to 5.00 and its Y to 57.00.
In the Properties panel give the second label the instance name "interestLabel". Set the label's X to 5.00 and its Y to 191.00.
In the Properties panel give the third label the instance name "attendingLabel". Set the label's X to 278.00 and its Y to 21.00.
In the Properties panel give the fourth label the instance name "willAttendLabel". Set the label's X to 278.00 and its Y to 143.00.
In the Properties panel give the first radio button the instance name "yesRadio". Set the radio button's X to 278.00 and its Y to 51.00.
In the Properties panel give the second radio button the instance name "noRadio". Set the radio button's X to 367.00 and its Y to 51.00.
In the Properties panel give the third radio button the instance name "notSureRadio". Set the radio button's X to 278.00 and its Y to 88.00.
In the Properties panel give the text area the instance name "sportsTA". Set the text area's X to 5.00 and its Y to 223.00.
Step 3: Preparing the .as File and Importing the Classes
Create a new ActionScript file and give it the name "Main.as".
We will be declaring our components in this Main.as file so we need to turn off "auto declare stage instances". The benefit of
doing this is that you get code hinting for the instance.
Go to Menu > File > Publish Settings. Click on Settings next to "Script[Actionscript 3]"
Uncheck "automatically declare stage instances".
In Main.as, open the package declaration and Import the classes we will be using by adding the following code:
package { //Import our controls import fl.controls.Label; import fl.controls.CheckBox; import fl.controls.TextArea; import fl.controls.RadioButton; //Needed to AutoSize the Text in our Labels import flash.text.TextFieldAutoSize; //Need to put our radio Buttons into a Group import fl.controls.RadioButtonGroup; //Need to extend Movie Clip import flash.display.MovieClip; //Need for our checkboxes import flash.events.Event;
Step 4: Set up the Main Class
Add the Class, extend Movie Clip and set up our Constructor Function.
Add the following to Main.as:
public class Main extends MovieClip { //The components public var interestLabel:Label; public var sportsLabel:Label; public var attendingLabel:Label; public var willAttendLabel:Label; public var toggleCheckBox:CheckBox; public var labelCheckBox:CheckBox; public var swimmingCheckBox:CheckBox; public var hikingCheckBox:CheckBox; public var boxingCheckBox:CheckBox; public var footballCheckBox:CheckBox; public var soccerCheckBox:CheckBox; public var baseballCheckBox:CheckBox; public var sportsTA:TextArea; public var yesRadio:RadioButton; public var noRadio:RadioButton; public var notSureRadio:RadioButton; //Need an array for the sports CheckBoxes private var sportsCheckBoxes:Array; public function Main() { setupLabels(); setupCheckBoxes(); setupRadioButtons(); }
Step 5: Functions in the Main Constructor
Here we define the
setupLabels(),
setUpCheckBoxes(), and
setupRadioButtons() functions.
In the
setupCheckBoxes() function we put all the sports checkboxes into an array; this way we can loop through them and add a single event listener to each one of them, saving us from having to manually type
addEventListener() each time.
For the
setupRadioButtons() we have used a
radioButtonGroup. Radio buttons are intended for only one of a group to be selected at a time. When we add a radio button to a group we are stating which radio buttons it belongs with.
Add the following to the Main.as:
private function setupLabels():void { //Sets the text on the label sportsLabel.text = "What sports interest you?"; interestLabel.text = "Your Interests Are:"; attendingLabel.text="Will you be attending the event?"; willAttendLabel.text="Will be attending = Yes"; //Use autosize so our labels can hold all the text sportsLabel.autoSize = sportsLabel.autoSize = TextFieldAutoSize.LEFT; interestLabel.autoSize = interestLabel.autoSize = TextFieldAutoSize.LEFT; attendingLabel.autoSize = attendingLabel.autoSize = TextFieldAutoSize.LEFT; willAttendLabel.autoSize = willAttendLabel.autoSize = TextFieldAutoSize.LEFT; } private function setupCheckBoxes():void { //sets the text on the labels toggleCheckBox.label = "Checked"; swimmingCheckBox.label = "Swimming"; hikingCheckBox.label = "Hiking"; boxingCheckBox.label = "Boxing"; footballCheckBox.label = "Football"; soccerCheckBox.label = "Soccer"; baseballCheckBox.label = "BaseBall"; toggleCheckBox.width = 250; toggleCheckBox.selected = true; toggleCheckBox.addEventListener(Event.CHANGE,toggleChange); //here we put the checkboxes into an array so we can loop through them //and easily add the same eventListener to each of them sportsCheckBoxes = new Array(swimmingCheckBox,hikingCheckBox,boxingCheckBox,footballCheckBox,soccerCheckBox,baseballCheckBox); for (var i:int=0; i<sportsCheckBoxes.length; i++) { sportsCheckBoxes[i].addEventListener(Event.CHANGE,sportsSelected); } } private function setupRadioButtons():void { yesRadio.label="Yes"; noRadio.label="No"; notSureRadio.label="Not Sure"; yesRadio.selected = true; //Radio Buttons are intended have only one selected at a time //by putting them into a group we say which belong with eachother var attending:RadioButtonGroup = new RadioButtonGroup("attending"); //here we assign the radio buttons to the group yesRadio.group = attending; noRadio.group = attending; notSureRadio.group = attending; yesRadio.addEventListener(Event.CHANGE,willBeAttending); noRadio.addEventListener(Event.CHANGE,willBeAttending); notSureRadio.addEventListener(Event.CHANGE,willBeAttending); }
Step 6: Event Listeners
Here we'll code our Event Listeners. Add the following to Main.as
private function toggleChange(e:Event):void { if (e.target.selected == true) { e.target.label = "Checked"; } else { e.target.label = "Not Checked"; } } private function sportsSelected(e:Event):void { //we clear the textarea and add the new options below sportsTA.text = ""; for (var i:int=0; i<sportsCheckBoxes.length; i++) { //if the current checkbox is selected we add it to the textArea if (sportsCheckBoxes[i].selected == true) { sportsTA.text += sportsCheckBoxes[i].label + "\n"; } } } private function willBeAttending(e:Event):void { //we use the currently selected radios button label to set Will be attending //to "Yes","No",or "Not Sure" willAttendLabel.text ="Will be attending = "+e.target.label; } }//close out the class }//close out the package
Conclusion
Using radio buttons and checkboxes is a great way to allow your users to make a selection.
You'll notice in the "Component Parameters" panel of the components that you can check and select certain properties:
This image is for the checkbox component.
The properties are as follows for the checkbox component:
- enabled: a Boolean value that indicates whether the component can accept user input.
- label: the text label for the component.
- labelPlacement: Position of the label in relation to the checkBox.
- selected: a Boolean value that indicates whether a checkbox is toggled in the on or off position.
- visible: a Boolean value that indicates whether the component instance is visible.
The properties for the radioButton are as follows:
- enabled: a Boolean value that indicates whether the component can accept user input.
- groupName: The group name for a radio button instance or group.
- label: the text label for the component.
- labelPlacement: Position of the label in relation to the radioButton..
- selected: a Boolean value that indicates whether a radioButton is toggled in the on or off position.
- value: A user-defined value that is associated with a radio button..
- visible: a Boolean value that indicates whether the component instance is visible.
Thanks for reading and keep your eyes open for upcoming component tutorials!
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/quick-introduction-flash-checkbox-and-radiobutton-components--active-6496 | CC-MAIN-2017-26 | refinedweb | 1,573 | 52.05 |
#include "univ.i"
#include "log0log.h"
#include "sync0sync.h"
#include "os0sync.h"
#include "que0types.h"
#include "trx0types.h"
#include "srv0conc.h"
#include "buf0checksum.h"
#include "ut0counter.h"
Go to the source code of this file.
The server main program
Created 10/10/1995 Heikki Tuuri
The buffer pool dump/load file name
Maximum number of srv_n_log_files, or innodb_log_files_in_group
Types of raw partitions in innodb_data_file_path
Alternatives for the file flush option in Unix; see the InnoDB manual
about what these mean
Alternatives for file i/o in Windows
Alternatives for srv_force_recovery. Non-zero values are intended
to help the user get a damaged database up so that he can dump intact tables and rows with SELECT INTO OUTFILE. The database must not otherwise be used with these options! A bigger number below means that all precautions of lower numbers are included.
Types of threads existing in the system.
Tells the Innobase server that there has been activity in the database and wakes up the master thread if it is suspended (not sleeping). Used in the MySQL interface. Note that there is a small chance that the master thread stays suspended (we do not protect our operation with the kernel mutex, for performace reasons).
Check whether any background thread are active. If so print which thread is active. Send the threads wakeup signal.
Boots Innobase server.
Check if there has been any activity.
in: a dummy parameter required by os_thread_create
Function to pass InnoDB status variables to MySQL
Frees the data structures created in srv_init().
Initializes the synchronization primitives, memory system, and the thread local storage.
Check whether any background thread is active. If so, return the thread type.
Get current server activity count. We don't hold srv_sys::mutex while reading this value as it is only used in heuristics.
Get count of tasks in the queue.
Increment the server activity counter.
Initializes the server.
The master thread controlling the server.
A thread which prints the info output by various InnoDB monitors.
Outputs to a file the output of the InnoDB Monitor.
Purge coordinator thread that schedules the purge tasks.
Wakeup the purge threads.
Enqueues a task to server task queue and releases a worker thread, if there is a suspended one. in: query thread
Releases threads of the type given from suspension in the thread table. NOTE! The server mutex has to be reserved by the caller!
Resets the info describing an i/o thread current state.
Sets the info describing an i/o thread current state. in: constant char string describing the state
Wakes up the master thread if it is suspended or being suspended.
Tells the purge thread that there has been activity in the database and wakes up the purge thread if it is suspended (not sleeping). Note that there is a small chance that the purge thread stays suspended (we do not protect our operation with the srv_sys_t:mutex, for performance reasons).
Worker thread that reads tasks from the work queue and executes them.
Status variables to be passed to MySQL
Mutex protecting some server global variables.
The buffer pool dump/load thread waits on this event.
current size in bytes
requested number of buffer pool instances
previously requested size
requested size in bytes
Boolean config knobs that tell InnoDB to dump the buffer pool at shutdown
and/or load it during startup.
If this is 1, do not do a purge and index buffer merge. If this 2, do not even flush the buffer pool to data files at the shutdown: we effectively 'crash' InnoDB (but lose no committed transactions).
The file format to use on new *.ibd files.
store to its own file each table created by an user; data
dictionary tables are in the system tablespace 0
whether or not to flush neighbors of a block
Place locks to records only i.e. do not use next-key locking except
on duplicate key checking and foreign key checking
Scan depth for LRU flush batch
Whether to check file format during startup. A value of
UNIV_FORMAT_MAX + 1 means no checking ie. FALSE. The default is to set it to the highest format we support.
Prefix used by MySQL to indicate pre-5.1 table name encoding
number of locks to protect buf_pool->page_hash
Maximum modification log file size for online index creation
Set if InnoDB must operate in read-only mode. We don't do any
recovery and open all tables in RO mode instead of RW mode. We don't sync the max trx id to disk either.
Sort buffer size in index creation
Global counters
Sleep delay for threads waiting to enter InnoDB. In micro-seconds.
Server undo tablespaces directory, can be absolute path.
Number of undo tablespaces to use.
The number of UNDO tablespaces that are open and ready to use. | http://mingxinglai.com/innodb-annotation/srv0srv_8h.html | CC-MAIN-2018-51 | refinedweb | 800 | 67.55 |
Suzanne Cook - Developing the CLR, Part I
- Posted: Feb 11, 2005 at 12:53 AM
- 140,744 Views
- 44 quality of audio is quite bad. When can we see Chris Brumme?
To download the video click the "save" link underneath the video.
Also, good to see this round of "who invented what" ended quickly. You know how much I love that game
What's to stop you from throwing together a BSD machine to play with rotor on?
Also, I think it's important to note that for most people, understanding exactly how the CLR loads a dll (and I mean exactly, it's always good to have a vague understanding) isn't that useful. While you and I may be interested, it's mostly an intellectual curiosity rather than a deal-breaker when it comes to platform choice.
I've traded emails in the past with Suzanne (I'm the current owner of InstallUtil.exe and InstallUtilLib.dll; we're some of those people that use LoadFrom when we probably shouldn't) but I've never seen her or heard her voice until this video
I've also seen her answer questions on internal mailing lists about .Net. Thanks to her blog, she almost never has to type a reply, just a link to a blog post. I'm convinced that after years of answering the same questions over and over, it was just easier to blog about it and point people over to that.
And to hear her talk about going to the doc guys and getting them to beef up the MSDN when it comes to the loader, getting bad practice methods depricated, etc. is just 10 kinds of cool. Suzanne is my hero
Managed code is code that executes in a virtual machine that automatically handles memory allocation and object lifetime among other nifty things.
In our case, this VM is the CLR and this is typically what we mean when you hear us say "managed" code around here.
* The suave geek male had to ask all the questions. The other geek male could barely hold the camera.
* Suzanne C. was not lecturing---she had to be interrogated. These events could be caused by her personality but is very, very different from most Channel 9 subjects.
* Suzanne C. seemed extremely tense but that could just be geek non-physicality.
The Amanda Silver interview was different.
perl and python are interpreters (like the original non-JIT JVM). Although you could call code running under it 'managed' it certainly doesn't mean the same thing as saying the CLR runs managed code.
I think managed referrs to code that runs in the CLR as part of a garbage collected object (as either a class or instance method). Note that you can have a mixed assembly that also contains native code - actual x86 instructions. Note also that code isn't managed just because it is JITed by the CLR. For example Visual C++ can compile any old C++ program into MSIL instead of native code just by using the /CLR switch. The code is only managed when it is part of a class marked with the Managed C++ extension __gc (or ref class in VisualC++ 2005).
That also leads me to a key difference in philosophy between .NET and Java. While they are pretty much the same technology-wise they come at it from a different angle. The idea with Java was to create a virtual machine that ran a standard set of bytecodes and a virtual OS as part of the class library. The idea for the .NET framework was just to make Windows development easier. There's a good reason why the code generated by .NET compilers is called MSIL - Microsoft Intermediate Language. The message is that this code is just seen as an intermediate stage between the compiler and the processor the same way many traditional compilers use an intermediate code internally (in GCC it is called RTL for example). MSIL is flexible enough to enable unmanaged ANSI C++ to be compiled into it. Even that model of .NET languages C# has a little used unsafe mode which you can use to write code that looks and works pretty much the same as C.
what's that?
I remember when I was at university before Java had broken cover we were using a system called poplog. It was sort of like a runtime that supported CLisp as well as its own langauge called pop11 which was like Lisp but with Pascal like syntax. Anyway, back then there was a discussion about how to refer to languages that required a memory management infrastructure like a garbage collector as well as a big runtime, to differentiate them from languages like C, Pascal and C++. 'Managed' would have been a good term to have at the time as I don't believe the discussion ever came to anything. Mostly it consisted of stupid arguments about what it meant to rely on a memory manager, i.e. C has malloc which can be as complex as some garbage collectors even though it doesn't do anything nearly as useful. C++ in all but its simplest guises needs a certain amount of library support, esp. for features like RTTI and exceptions.
I will state again becuase I think beer28 missed it the first time: The fact that a language is compiled into an intermediate code does not make it 'managed'. As I said before ANSI C++ can be compiled into MSIL by using the /CLR, but that doesn't make it managed. Likewise the UCSD p-system which first popularised the concept of p-codes wasn't managed because it ran pascal - the users program still have to manage memory allocations itself like you do in any pascal as far as I know.
Where the border really lies between managed and unmanaged is: does the runtime need to know the type and layout of all the classes/structures in your program? The runtime has to know in order to run a proper garbage collector (rather than the Bohem hack), to provide type reflection and late binding support. Languages like LISP, Smalltalk and Pop11 were managed as it Java, C# and VB.NET. Pascal, C++, Delphi (save for the latest version) are unmanaged whether they are compiled to machine code, p-code or MSIL. Languages like Perl and PHP which are interpreted could be described as managed: They are interpreted and the interpreter has to know the layout of any data structures they use in order the implement them so they are managed, but it's a moot point really.
Most people really aren't comfortable speaking in front of crowds because we all know we're being judged.
My hat is off to Suzanne, though. She's very smart. I think the second part of the video is a little better.
I'd say that "interrogation" is an entirely incorrect expression for how the interview was conducted.
When you sit down to have an informal, casual chat with somebody do you give them a list of quetions ahead of time so they know what they are going to say before you ask questions?
We don't do this type of thing on Channel 9, and we won't. Perhaps I need to do a better job of making people feel comfortable. What do you all think? I'd appreciate feedback.
Charles
Thank you. This is helpful. I will work on getting better at this. This is all pretty off the cuff and very often my questions are born during the interview (there is nothing as pure and honest as spontaneity). I try to keep the technical stuff approachable since we want these interviews to appeal to a wide audience.
Please always feel free to give feedback on what we do and how we do it.
Thanks again.
Charles
To the extent that it is possible, yes. There are a few situations in which a function will be left as native code (embedded asm springs to mind) but it'll mostly spit out MSIL and the framework will be required to run it.
A lot of times in interviews I'm just trying to mentally keep up with the interviewee.
She's a developer on the .NET CLR team. I'm nowhere near as smart as she is.
So... thumbs up for Suzanne!
And for Robert and Charles too! I actually like your style better than Robert Hess's, because it is so natural and informal.
Keep up the great work guys, we LOVE these videos! And really, Channel9 has become one of the very few sites that I visit daily, even in weekends (only to see that it wasn't updated yet
What's more, Channel9 changes the perception of Microsoft in a way that you just cannot imagine. Seeing all these nice and intelligent people behind the products that we use, creates a very strong bond. This unique inside view into a corporation achieves much more than even millions of dollars of marketing money ever could...
Greetings from Belgium,
dotnetjunkie
I would like to hear more about StrongName (SN) improvements that may be coming in loader or other. Not about the FQ Assem Name per se, but protecting the assembly signature and the public key, and hence the bits, somehow. Today, you can resign any assembly by changing the public key hex and using SN -R. See .
That pretty much allows you to change assem and resign. You can also zero out the signature and use SN -V to skip verify. As you can resign assemblies with a new key pair, I don't see the need for Delayed signed assemblies anymore. As you can just sign your assems with a tmp key pair during dev, and have the "Key" team resign with real key before shipping and key testing. That way, I ~think, you could do away with SN -V and the Delayed Signed process all togeter to remove the "skip" attack. Any work on better protecting the public key and the signature (maybe CLR and meta data in assem working together to provide a solution)? I realize there is a circular problem here with protecting x to protect y to protect z, but just interested if anyone is working on something new and interesting. TIA!!!
--
William Stacey [MVP]
in my opinion robert and charles try really hard to create this 3-person-friendly-chat style so people don't feel the pressure of talking infront of a camera and infront of an online audience. i also think that they really succeed in that. not only the public speaking warriors like don box (no offence! don's speeches are among my favourites (i must say i like 'the ballmer' most on stage)) but also people who don't give public presentations all day feel comfortable being on channel9.. and i think you can see that throughout all of the videos. i wouldn't judge based on a few interviews where the private atmorphere didn't really work out. that happens.
roberts interjectional
charles has obviously a tendency to ask some indepth technical questions. and i do think that they are always of general interest for the niners. asking indepth questions to a guy who's developed OSes and file systems his whole life is not the easiest thing! charles does it. after all we're geeks.
the one thing i would like to add is that maybe if you gave the interviewees notice so they knew you are about to visit them in a week or so. i think this would also be the rersponsibility of the PMs in charge to make sure the team knows about channel9... not so that they can prepair themselves.. we all don't need that and they don't need that, more importantly... but to make them comfortable with the idea of being on camera. PMs shouldn't surprise the interviewees in those "tour-style" videos. Just let them spread the word of channel9. if they see that we're a bunch of friendly geeks ( sounds hard i know +g+) they won't hesitate to sit infront of the camera.
i'm sorry this post has gotten so long.. but i feel that the mood and style of the channel9 interviews is just the right thing. let robert hess do his thing.. he won't achieve this style we have here on channel9.
(i respect robert hess and his team very much. i've just got a little tired of his discussions about concepts and philosophies behind something that might be aswell seen as geeky stuff).
best regards
- martin.
While I understand its much more effort to arrange, I find the videos where you get the Guest and someone the Guest knows (manager or whatever) together, there is less chance for the silent parts where your thinking whats the next smart question, as the other person who knows the subject area you are talking about with the guest can then chime in. There's many videos already where we have seen this work best I think, like
Kevin Schofield - Tour of Microsoft Research
Herb Sutter, the Future of Visual C++
Kit George - Tour of .NET CLR Base Class Library Team (Part II)
This tour with expert + a good conversation with guests format is very good as there can both be expert conversation and novice questions and less chance for akward silence. And the guest may even feel more comfortable when theres someone (s)he knows better to help out if the question is going a bit out of his/her area of knowledge etc..
And my hidden agenda: Less of The Scobleizer laughing and more of the interesting conversation between people who know what they're talking about - if they go too much rocket science, you can always let them know.
But actually I feel stupid whining about this, most of the videos lately have been like I've hoped here, for this video I guess you just could not arrange the better setup?
There was some tense energy
to be felt, but I don't necessarily think it's anybody's fault. I'm not sure how much can be ascribed to gender dynamics, but gender dynamics are what they are and some people might get caught in
a cross-fire of contradictory expectations (or what
they imagine society expects), especially if they are a minority gender in a given field. Especially if they are smart.
Certainly, the "geek" image is male-centered and
might be alienating for techy women i guess...
If I were Robert, I wouldn't push the geekiness talk so much... There's some gender issues with it, like with the image of hip-hop homies and the surrounding narrative.
All in all I think Suzanne did a pretty good job and I liked those interviews a lot.
I noticed that Suzanne was kind of sweating visibly (I guess I was viewing full-screen rather than in a mini window) so I had the sense she felt put on the spot for an impromptu talk. That stuff is definitely not easy for most people. But that's how I like it - a raw and uncut view of the people at Microsoft to some extent.
Dan Lipsy
Stevens Institute of Technology
Student Ambassador to Microsoft
Yeah, I don't want to bring up the Amanda interview and the Suzanne interview like they must go together because they are both of the same gender. People are allowed to be different.
In an effort to not accuse you guys of having bad experiences with female interview subjects I cannot avoid making sexist observations. But the great thing about these 'new days' of American "liberty" and "freedom" my sexist remarks are totally insignificant to the "good people of Texas" all over the world.
I'm not sure if such comments are part of the solution or part of the problem.
I disregard political correctness for its ficticious character - trying to conjure the problem by putting enough tokens on the front page (analyze the demographics on pictures on ms.com)
But I also disregard the right-wing version of political correctness which dismisses equality as a ficticious issue. It is not.
Managed comes about from some runtime features that currently aren't exploited in common scenarios. The guts of the runtime can be thought of as a request/response cycle with messages. So when you make a call on a method, the call is packaged as a message and follows a request/response cycle. Just like it's possible to 'manage' messages in a TCP/IP environment it's equally possible to 'manage' runtime messages.
Spend some time spelunking around System.Runtime.Remoting.Context and System.Runtime.Remoting.Messaging.
So it goes alot more further than simply managing memory etc... It's more about having an environment where programming messages can be managed.
I won't even answer the rest. It's pretty clear you don't understand how the CLR works. Everything is represented a message inside of the CLR. Spend some time investigating those namespaces and then we can talk.
Also messsages != managed. The managed aspect comes into play with this notion of an omnipresent thing, a manager if you will, looking down at message paths saying yes you can do this, no you can't do that. Oops you actually need to go here.
Finally anyone who doesn't acknowledge that the CLR is COM done right (or COM version 3.0) is deluded. In fact IIRc the original name for the CLR was COM+2.
Feel free to scan whatever, it isn't going to change the way it works.
Don't let the fact that all this stuff lives in a remoting namespace confuse you.
If you really want to understand how it works, download rotor and navigate to \sscli\clr\src\vm\. You will find a unmanaged counterpart to every single call construct used in the managed environment. The critical class is message.cpp basically what it does is well... here's the comments
/*============================================================
**
** File: message.cpp
**
** Purpose: Encapsulates a function call frame into a message
** object with an interface that can enumerate the
** arguments of the message
**
** Date: Mar 5, 1999
**
===========================================================*/
The runtime views everything as a message and the runtime manages these messages. Again, it's pretty clear to me that you have no idea what you are talking about.
My comments were by definition sexist. Your wish is to extend my assertions into the phrase you have been taught, "political correctness." So I agree with you that you are not sure. And I am no "problem" for the "good people of Texas" because I have no nuclear weapons. The data have been transmitted. Please parse the data. Use quotes. Do not use the uncertainty of loyal captivity.
Which parser do you use? Mine barfed on this.
And which definition are you talking about? You didn't import any definitions. Your stuff doesn't compile.
So what you are saying is you are going to study an inferior virtual machine that supports a lowest common denominator threading model?
The fundametal difference between the CLR virtual Machine and the Java Virtual Machine is this message based architecture. Like I said, while this is not commonly exploited it does open up an incredible array of possibility.
You will see, in a few years Microsoft is going to 'flip the script' and all this message stuff is going to make a whole lot of sense. When that happens I suspect your little penguin will start to shake and ultimatly implode.
Maybe, just maybe if you studied what Microsoft is doing with the runtime you would get it and help the communist duck live to see a future in the computing arena. But in your arrogance I doubt that will happen, so let me wish you fairwell; because by 2010 you won't be relevant at all.
Maybe you should just buy a Mac. At least they understand a: good threading models b: good network stacks and c: the future of the personal computer.
You are totally missing the point of it. In a message based system, there is really no need for a module to be local. If you would like me to explain it to you, don't hesitate to ask.
And FWIW, I've never built Rotor - I just know how to read the code and I've spent alot of time programing with IMessage on the managed side.
Sorry if I sound so harsh but I've been reading your back log of posts and find you to be an arrogate, uninformed blabber mouth would really doesn't understand the Microsoft platform at all and who has no intention of doing anything other make inflamatory comments that are designed to make noobs feel stupid.
If fact the only reason why I started posting here was to shut you up, or at least force you to make sense.
I dyslexic. Get used to it.
Yes. That's exactly how it works. Let me give you an analogy.
Consider a router. When a packet comes into a router on an interface the router looks at that packet and makes some decisions about what to do with that packet. In some cases it might need to wrap that packet (e.g. nat), In some cases it might need to unwrap that packet (e.g. nat again). It does this by using some internal state (a routing table).
The runtime can be thought of in a similiar fashion. So as method messages calls are coming into the runtime some state tables are used to load and execute code, which in turn generate return messages.
more than one year and the video is not available to download
Remove this comment
Remove this threadclose | http://channel9.msdn.com/Shows/WM_IN/Suzanne-Cook-Developing-the-CLR-Part-I?format=progressive | CC-MAIN-2014-42 | refinedweb | 3,653 | 71.34 |
I am creating some code that displays an
array
import java.util.Scanner;
public class Assign3
{
public static void carMake(String bmw)
{
Scanner input = new Scanner(System.in);
//declare and intialize parallel arrays, Services and Prices and display them to the user
String[] services = {"Oil Change" , "Tire Rotation", "Air Filter", "Fluid Check"}; //intialize list of services
double[]price = {39.99, 49.99, 19.99, 10.99}; //initialize corresponding price for services
for(int i= 0; i < services.length; i++)
{
System.out.print( services[i]+ "...." );
System.out.print( price[i] + "\t");
}
System.out.println("What service do you want done?: ");
String service= input.nextLine();
}
public static void main(String[]args)
{
String bmw = "fancy car";
carMake(bmw);
}
}
Although I'm not submitting a full program, I can give you all the information you need to finish this project. First, you have to decide how to incorporate the connection between a service and it's price.
A better approach instead of two arrays would be to create a "Service" object. For example:
public class Service { // Variables to use String name = ""; double price = 0.0; // Constructor of the 'Service' class public Service(String inputName, double inputPrice) { name = inputName; price = inputPrice; } }
This would allow you to then make the call:
// Create the oilChange service Service oilChange = new Service("Oil Change", 39.99); // Get the oilChange values: System.out.println(oilChange.name); // Displays 'Oil Change' System.out.println(oilChange.price); // Displays '39.99'
From there, you have to determine whether or not to use a
for-loop or a
while- loop. A
for-loop requires you to know how many times the loop will run. However, for your example, this is something you won't know. So therefore, you will have to use a
while-loop. An example of a
while-loop for your program would look like:
double totalPrice = 0.0; boolean userIsDone = false; Service listOfServices = [] // Contains created service objects from above while (userIsDone == false) { System.out.println("What service do you want done? (Type 'quit' to exit): "); String service= input.nextLine(); if (input.equalsIgnoreCase("quit")) { userIsDone = true; } else { /* 1.) Loop through the 'listOfServices' array finding a service with the name that matches user input 2.) Then retrieve the price of that service and add it to the 'totalPrice' counter */ } } System.out.println(totalPrice); // Updated total price!
Hope this helps! | https://codedump.io/share/3ifHJPpaJ7dI/1/user-input-incorporating-arrays-and-while-loops | CC-MAIN-2018-09 | refinedweb | 385 | 60.31 |
I'm often in need of either the full path+filename or just the filename for copy/pasting. I see that full path is available via right click in the document body. I'd love to see both of these options added to the file name in the Side Bar, file name in the tabs AND in the body (or at least one of the three).
Brilliant app btw...
It is available when you right click inside the view as "Copy File Path"
As I said, full path is available; I want full path AND just the filename as I use both often. It would be nice if they were both available via right click anywhere the name of the file is. Eg. in the sidebar and on the tab when the file is open.
Thanks. Brian
Why not make it yourself? Sounds simple enough. Just create a small plugin the copies the filename to the clipboard and add it to the context menu.
sublimetext.com/docs/2/api_reference.html
COOL, what i am locking for, thanks.
sublimetext.com/docs/menus
SideBarEnhancements package already add the menus to the sidebar. And now these are available via: Tools -> Commands Palette or via the shortcut which is faster.
If you still want these in some menu, with that package installed, you can copy the file
"../Packages/SideBarEnhancements/Commands.sublime-commands"
to
"../Packages/User/Context.sublime-menu""../Packages/User/Tab Context.sublime-menu"
and customize the entries ( deleting these you don't use). ( notice these files ends with "sublime-menu" instead of "sublime-commands"
Thanks Tito... that did the trick.
Solution:
First install SideBarEnhancements
Then copy:"../Packages/SideBarEnhancements/Commands.sublime-commands"to"../Packages/User/Context.sublime-menu""../Packages/User/Tab Context.sublime-menu"
Just made a plugin command for this in case it helps anyone else.
{ "keys": "ctrl+alt+c"], "command": "filename_to_clipboard" },
{ "keys": "ctrl+alt+shift+c"], "command": "path_to_clipboard" },
import sublime, sublime_plugin, os
class FilenameToClipboardCommand(sublime_plugin.TextCommand):
def run(self, edit):
sublime.set_clipboard(os.path.basename(self.view.file_name()))
class PathToClipboardCommand(sublime_plugin.TextCommand):
def run(self, edit):
sublime.set_clipboard(self.view.file_name())
just found this, the code for copy file path is "copy_path"
The copy-file-name plugin does the job very nicely, as long as you install it "properly", as described in this issue: github.com/nwjlyons/copy-file-name/issues/3
On Right Click on the file not on the title of file.
you will get pop up like this | https://forum.sublimetext.com/t/file-name-and-full-path-to-clipboard/4833/6 | CC-MAIN-2017-22 | refinedweb | 409 | 58.48 |
Table of Contents:
Introduction
Hosting Environments
· ASMX Services
· WCF Services
· Different Hosting Environments
WAS Hosting Environment
· A Simple Hosted Service
· Service Configuration
· Service Addressing
· Service Activation
· Service Recycling
Let me start with something simple for this topic. I first make a few assumptions here:
That is all what you need to know before reading the following!
Below I will write about how to host a WCF service in a special “hosting” environment.
There are tons of articles and blogs out there talking about Service Oriented Architecture (SOA), Web Services, and WCF. Never mind if you have not read them. So I will make things as simple as possible. Basically, WCF, as the next generation of service-oriented programming platform, provides a set of .NET APIs in its Version 1 (V1) for developers to use. It will be released as part of a larger package WinFX. You can download the most recent PDC release from here.
Every service-oriented programming model is also a client-server model. WCF has no difference. Both the client and service counterparts of WCF are based on the so-called “ABC” model: Address, Binding, and Contract. People also call this as “WHW” model: Address stands for “Where”, Binding stands for “How”, and Contract stands for “What”. Among the three, Binding is the most complicated part in this model. It tells WCF how to transfer data between the client and the service:
For each WCF service, there is a host that manages service instances and lifetime. The base type of the host is System.ServiceModel.ServiceHost. It provides events and extensibility points for you to programming with. Actually I am lying here. ServiceHost is not the most basic service host type, but System.ServiceModel.ServiceHostBase is. However, you will never touch this base type if you do not want to re-create the whole channel stack to replace WCF underlying implementations.
How far have I diverted from my topic? Aren’t we talking about WCF service hosting? No, not yet! The concept of “host” has relative meanings in different programming plug-in layers. The “host” that I will talk about here has a broader meaning: it is application-level “host”. That is, a host is an application that loads one or more WCF ServiceHosts, which we will call services in the following, and manages their lifetime. In some cases, it provides an environment that works as the entry point for all messages that are routed to the services. Am I clear here? If not, please read on.
There are different types of hosting environments for WCF services. To understand how these hosting environments work, we need to go back to see how the predecessor of WCF, a.k.a., ASMX works.
When ASP.NET V1 was shipped, a Web service framework known as ASMX was introduced. It is tightly integrated with the ASP.NET HTTP pipeline. This pipeline provides the hosting environment to ASMX services and it is almost always hosted inside ASP.NET applications which are managed by IIS. In this way, ASMX services can leverage the advantages of ASP.NET applications such as process management, application recycling, configuration and deployment, and extensibility points provided by ASP.NET HTTP pipeline.
It is not required to have IIS to run ASMX services. For example, you can use the ASP.NET Cassini sample web server to host an ASP.NET application and thus ASMX services. You also build a web server into your own application to host the ASP.NET pipeline using the managed HTTP.sys utility System.Net.HttpListener(see Run ASMX without IIS).
However, ASMX services cannot run without the ASP.NET HTTP pipeline. Even though you can integrate the pipeline into your application as above, you still need to think of the ASMX services as being in a different world, that is, they have their own configuration and deployment which are quite web-flavored. In this sense, WCF services go one big step beyond to make service-oriented programming real.
The fact that ASMX services are tightly coupled with ASP.NET HTTP pipeline is due to the flat and passive HTTP request handling mechanism. HTTP requests received from IIS are passed on to ASP.NET pipeline and then are consumed by service methods.
WCF services, however, are based on a strictly layered model to break this paradigm. Roughly speaking, there are three different layers for WCF services:
This layered model is similar as the Open System Interconnection (OSI) model. The lowest Transport layer is responsible for listening and receiving requests and converting the received data into “Messages”. A Message is a cross layer data packet that travels all of the layers to the top. The Channel layer provides a Message processing framework for different service requirements. In the real implementation, it actually consists of one or more sub-channel layers such as Basic layer, Security layer, ReliableMessaging layer, Transaction layer, etc. The top ServiceModel layer is the application layer that manages service instances and invokes service operations. It provides Object Models (OM) for people to program with.
In this layered model of WCF services, the top SericeModel layer is also responsible for building the lower level layers in different hosting environments. It also makes the Transport layer to be freely chosen among different communication protocols. This is why it does not rely on the ASP.NET HTTP pipeline as ASMX services does.
As mentioned above, WCF services are hosted by a ServiceHost. Ideally, any application or environment can create ServiceHost to host WCF services. In reality, we classify the different environments into three categories:
The WAS hosting environment is a broad concept that extends the ASP.NET HTTP pipeline hosting concept for ASMX services. WAS is an NT service in Windows Vista. It is separated out from the legacy IIS as a standalone Windows component that provides protocol-agnostic activation mechanism for different protocols besides HTTP. The IIS, Cassini, and any custom Web Server flavored hosting environments also fall into this category since they share the same WCF service deployment and activation mechanism. I will talk about this more in later sections.
You can easily host a WCF service in an EXE application so that you can control the lifetime of the ServiceHost. Furthermore, the WCF service shares the same configuration file with the application. This hosting environment is mostly useful when you also build your client code into the application. A good example is that a sophisticated business application with 3-tier architecture can have WCF services to pass messages between different layers.
NT Services are special EXE applications which are long running and the lifetime is controlled by Service Control Manager (SCM). Because of the long running behavior, you need to be careful of all of different requirements for writing an NT Service: security, reliability, and performance. You can use Microsoft Visual Studio to create managed NT Services with “Windows Service” project type.
As mentioned above, a WCF service works similarly as an ASMX Service. For HTTP protocol, it relies on ASP.NET HTTP pipeline to transfer data. For non-HTTP protocols such as Net.Tcp, Net.Pipe, and Net.Msmq etc, it relies on the extensibility points, i.e., ProcessProtocolHandler (PPH) and AppDomainProtocolHandler (ADPH), of ASP.NET to transfer data. We will use the term “protocol handler” interchangeably to refer to either the ASP.NET HTTP pipeline or the ADPH. In the context of this writing, WCF services hosted in this environment are called WAS hosted services or simply called hosted services, and in contrast, services hosted in NT Services or EXE applications are called self-hosted services.
Let’s first take a look at a simple hosted service and see how it works.
A hosted service requires a physical service file with extension “.svc” to be associated with it. Here is the content of a simple service file HelloWorld.svc:
<%@Service Language="C#" Class="HelloWorld.HelloService" %>
using System;
using System.ServiceModel;
namespace HelloWorld
{
[ServiceContract]
public interface IHelloContract
{
[OperationContract]
string Hello(string greeting);
}
[ServiceBehavior]
class HelloService : IHelloContract
public string Hello(string greeting)
{
return "You said: " + greeting;
}
}
This file has a Service directive which is enclosed in the “<% %>” block and it also contains inline C# code. The Service directive tells the hosting environment which Service this file points to.
Just as ASMX services, the code can be compiled into a DLL that is deployed to the Global Assembly Cache (GAC), or to the application’s “\bin” directory, or it can be put in a C# file under the application’s “\App_Code” directory.
With this service file, we have defined a service contract IHelloContract and the service implementation. However, the service still does not have an endpoint defined yet. You can either define an endpoint declaratively through the configuration file “web.config” or imperatively through code. The latter will be covered separately in a different blog later.
The service configuration inside the web.config file is very similar as that of self-hosted services. Here is an example of web.config file for the above service:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.serviceModel>
<services>
<service type="HelloWorld.HelloService">
<endpoint binding="basicHttpBinding"
contract="HelloWorld.IHelloContract" />
</service>
</services>
</system.serviceModel>
</configuration>
I need to point out a few points for this config file:
1) Service Type Attribute: The service type “HelloWorld.HelloService” specified here plays as a lookup key for the corresponding HelloWorld.svc. It tells the hosting environment which service will take the configuration specified here.
2) Endpoint Address: I did not specify the “address” of the endpoint here. The endpoint address is the same as the base address in this case. I will expand this in the next section.
3) Nested web.config: The service configuration can be specified in nested web.config files. For ASP.NET applications, a web.config file can locate in any sub-directories or virtual web directories as well as the root of the virtual application. All of the settings in the nested web.config files are merged for the virtual ancestors of the directory where the .svc file locates.
The .svc file does not contain much useful information except for providing the service type which is also specified in the web.config file. Then why do we need .svc files after all? The main reason is that we need them to provide intuitive addressing model.
Suppose that we drop the above HelloWorld.svc file into a virtual application “/test”, we automatically have the following base address for the service:
You can enable different protocols for a single ASP.NET application. Each protocol needs to have a protocol binding for the whole web site. For IIS6 and below, the only protocol that is supported is HTTP (which implies HTTPS).
The WAS hosting environment looks up all enabled protocols for the ASP.NET application and generates the base addresses for the hosted service. Each base address has the following format:
<scheme>://<hostname>[:<port>]/<apppath>/<servicefilename>.svc
You can access the base addresses through the ServiceHostBase.BaseAddresses property. In WCF V1, only one base address is supported for each protocol. So if there are two or more bindings for HTTP is specified, you will get an ArgumentException on the service side with error message “Collection already contains an address with scheme http”.
Note: It is NOT recommended to specify an absolute address (with protocol scheme included) to the endpoint in web.config, otherwise, you will get AddressAccessDeniedException on the service side if the address does not match the service base address up to the application path (<apppath>) or EndpiontNotFoundException if you happen to match the application path but not the service path.
The WAS hosting environment is represented by the public type System.ServiceModel.ServiceHostingEnvironment. It is responsible for service activation, that is,
· It finds the service compilation information from System.Web.Compilation.BuildManager
· It creates the ServiceHost instance to host the service with compilation information.
· It then calls ServiceHost.Open to build the layers.
· It then caches the service and manages its lifetime inside the AppDomain.
This whole process is exposed through the following public method:
public static void EnsureServiceAvailable(string virtualPath)
This API is protocol agnostic. It is an extensible point for a custom protocol handler to activate the service.
The service activation process has the following characteristics:
1) Activation on demand: A WCF service is activated in the AppDomain only if EnsureServiceAvailable is called by one protocol handler for that service. Once it is activated, it will be active in the AppDomain until the AppDomain is unloaded.
2) Activation once for all: A WCF service can be activated from any protocol handler. Once it is activated, it is activated for all endpoints and thus all protocols. So when a second protocol handler calls EnsureServiceAvailable, it is a no-op as the service has been activated.
Hosted WCF services enjoy all of the features for ASP.NET applications. One of the major feature is application recycling including AppDomain recycling and process (or AppPool) recycling. There are different factors that can cause application recycling to happen. See “Recycling Application Pool Settings” for more information about process recycling. When the worker process is recycled, all of the AppDomains in that process are also recycled. The configuration setting HostingEnvironmentSection.IdleTimeout can control AppDomain recycling. Also an AppDomain can be recycled if critical files for the application are changed. These files include web.config, assemblies in the “\bin” directory, code files in the “\App_Code” directory, etc.
Whenever a .svc file is modified in application, the AppDomain is also recycled. This is to simplify the service recycling mechanism. When the AppDomain is recycled, the ServiceHostingEnvironment tries to close all of the cached WCF services in a timely manner. Services not closed timely are aborted at the end. The timeout is controlled by the HostingEnvironmentSection.ShutdownTimeout property.
The drawback of service recycling is that all of the sessionful data is lost. This means that Security and ReliableMessaging break when recycling happens. The workaround is to leverage the ASP.NET state service features by enabling AspNetCompatibility mode. I will expand on this in a later blog.
Trademarks |
Privacy Statement | http://blogs.msdn.com/wenlong/archive/2005/11/14/492383.aspx | crawl-002 | refinedweb | 2,346 | 50.23 |
Bjorn Sundberg wrote ..
> Thanks Graham for your quick response. Its 2 am and my head is abit slow.
> But is the idea to let apache do the digest authentication, that is apache
> takes care of matching username against the password supplied in the
> authenhandler()?
If you use AuthDigestFile to specify a user/password file that Apache can
itself use, the authenhandler() isn't even required. As you probably know,
you can find more details of how to set up Apache at:
Given that Apache will handle all aspects of authorisation, all that needs
to be done now is to work around the problem in mod_python.publisher
that prevents it being used in a directory authenticated using digest
authentication.
I was putting that workaround in authenhandler(), but probably shouldn't
have suggested it as it has probably confused the issue. What has to be
done though is to hook in a bit of code somehow before the handler
for mod_python.publisher. This could be done in an earlier processing
phase or as a content handler just prior to mod_python.publisher is
triggered. I would suggest the latter.
To do that, where you currently have:
PythonHandler mod_python.publisher
change it to:
PythonHandler my_digest_workaround::_delete_authorization_header
PythonHandler mod_python.publisher
When you specify two handlers like this, mod_python will execute each in
turn. Thus, by adding a _delete_authorization_header() method to a module
my_digest_workaround we can hook in some code to run before
mod_python.publisher. The content of my_digest_workaround would thus be:
from mod_python import apache
def _delete_authorization_header(req):
if req.headers_in.has_key("Authorization"):
del req.headers_in["Authorization"]
return apache.OK
The my_digest_workaround module could be put in the same directory as
.htaccess file, or if using global Apache configuration in root directory of
where your published files are kept. I explicitly called the handler
_delete_authorization_header(), with a leading underscore so that it
will not be found if some addressed a URL for publisher at it directly.
End result is that the workaround gets called first and it removes the
problem header and then publisher gets executed and your function
called.
Graham
> Björn S
>
> On 11/23/05, Graham Dumpleton <grahamd at dscpl.com.au> wrote:
> >
> > Graham Dumpleton wrote ..
> > > Bjorn Sundberg wrote ..
> > > > Is there a way do use http digest authentication?
> > >
> > > No. HTTP digest authentication and mod_python.publisher are currently
> > > incompatible. See:
> > >
> > >
> > >
> > > It is actually a simple fix, but wasn't done for mod_python 3.2.
> > >
> > > Even if fixed, the HTTP digest authentication has to be done by Apache,
> > > it cannot be done by mod_python.publisher when using __auth__ etc.
> > > The fix is merely to stop mod_python.publisher barfing when it is being
> > > done by Apache.
> >
> > Actually, as usual there is nearly always a way to fudge things. You
> could
> > still use Apache HTTP digest authentication (managed by Apache) and
> > still use mod_python.publisher by having an authenhandler() which
> > deleted the "Authorization" header so that mod_python.publisher didn't
> > find it and therefore didn't barf.
> >
> > def authenhandler(req):
> >
> > if req.headers_in.has_key("Authorization"):
> > del req.headers_in["Authorization"]
> >
> > ... etc.
> >
> > I haven't tried this, but it should work.
> >
> > Graham
> > | http://modpython.org/pipermail/mod_python/2005-November/019583.html | CC-MAIN-2017-51 | refinedweb | 513 | 51.24 |
/* Header for CCL (Code Conversion Language) interpreter.
National Institute of Advanced Industrial Science and Technology (AIST)
Registration Number H14PRO021. */
#ifndef EMACS_CCL_H
#define EMACS_CCL_H
/* Macros for exit status of CCL program. */
#define CCL_STAT_SUCCESS 0 /* Terminated successfully. */
#define CCL_STAT_SUSPEND_BY_SRC 1 /* Terminated by empty input. */
#define CCL_STAT_SUSPEND_BY_DST 2 /* Terminated by output buffer full. */
#define CCL_STAT_INVALID_CMD 3 /* Terminated because of invalid
command. */
#define CCL_STAT_QUIT 4 /* Terminated because of quit. */
/* Structure to hold information about running CCL code. Read
comments in the file ccl.c for the detail of each field. */
struct ccl_program {
int idx; /* Index number of the CCL program.
-1 means that the program was given
by a vector, not by a program
name. */
int size; /* Size of the compiled code. */
Lisp_Object *prog; /* Pointer into the compiled code. */
int ic; /* Instruction Counter (index for PROG). */
int eof_ic; /* Instruction Counter for end-of-file
processing code. */
int reg[8]; /* CCL registers, reg[7] is used for
condition flag of relational
operations. */
int private_state; /* CCL instruction may use this
for private use, mainly for saving
internal states on suspending.
This variable is set to 0 when ccl is
set up. */
int last_block; /* Set to 1 while processing the last
block. */
int status; /* Exit status of the CCL program. */
int buf_magnification; /* Output buffer magnification. How
many times bigger the output buffer
should be than the input buffer. */
int stack_idx; /* How deep the call of CCL_Call is nested. */
int eol_type; /* When the CCL program is used for
encoding by a coding system, set to
the eol_type of the coding system.
In other cases, always
CODING_EOL_LF. */
int multibyte; /* 1 if the source text is multibyte. */
int cr_consumed; /* Flag for encoding DOS-like EOL
format when the CCL program is used
for encoding by a coding
system. */
int suppress_error; /* If nonzero, don't insert error
message in the output. */
int eight_bit_control; /* If nonzero, ccl_driver counts all
eight-bit-control bytes written by
CCL_WRITE_CHAR. After execution,
if no such byte is written, set
this value to zero. */
};
/* This data type is used for the spec field of the structure
coding_system. */
struct ccl_spec {
struct ccl_program decoder;
struct ccl_program encoder;
unsigned char valid_codes[256];
int cr_carryover; /* CR carryover flag. */
unsigned char eight_bit_carryover[MAX_MULTIBYTE_LENGTH];
};
/* int ccl_driver P_ ((struct ccl_program *, unsigned char *,
unsigned char *, int, int, int *));
/*;
#endif /* EMACS_CCL_H */
/* arch-tag: 14681df7-876d-43de-bc71-6b78e23a4e3c
(do not change this comment) */ | https://emba.gnu.org/emacs/emacs/blame/328f7b35981238f4e528bfe2cb5b0e17f074d056/src/ccl.h | CC-MAIN-2020-40 | refinedweb | 387 | 60.72 |
The easiest way to get started with libLCS is to start building simple circuits using the off-the-shelf logic gates provided in libLCS. All circuit elements, which have an input and an output, will be called as modules when reffered to in the context of libLCS. Since logic gates have a well defined input and output, they are also called as modules in libLCS (unlike in Verilog where logic gates are reffered to as primitives). All logic gate modules (except the NOT gate module) in libLCS are provided as class templates requiring two template parameters. The template parameter first in the order of template arguments denotes the number of inputs to the gate, and the other template parameter denotes the input to output delay of the gate. Since a NOT gate can have only one input, it is provided as a class template taking only one template parameter which represents the input to output delay of the NOT gate.
In libLCS, the cable/wire connections between modules have to be done using busses. Busses are also provided as class templates requiring one template parameter. The template parameter indicates the width (or number of lines) of the bus.
Further in this section, I will go over building a trivial circuit as an illustrative example. More complicated examples can be found in the basic examples section.
aand
bbe inputs to our circuit. Let
sbe the output. Then, the boolean function for
sis:
s = ab' + a'b
Hence, to generate
s from
a and
b, we require two 2-input AND gates, one 2-input OR gate, and two NOT gates. The circuit diagram is as follows (the small circles/bubbles represent NOT gates):
Each node in the above circuit translates in to a bus in the case of libLCS. As marked in the circuit, seven single-line busses are required to build the circuit. The first step in our program is to declare these 7 single-line bus objects. The class template to generate bus classes is defined in the header file
lcs/bus.h. All classes in libLCS are defined in the namespace
lcs, and so is the bus class template
lcs::Bus. We declare the busses as follows.
lcs::Bus<1> a, b, a_, b_, p1, p2, s; // The bus names are same as // that in the diagram above.
Note the use of a template parameter of 1 in the above declaration to indicate the width of the busses being declared. After declaring the busses in the circuit, the next step is to initialise the logic gate modules in the circuit. We will first initialise the NOT gates in the circuit. The initialisation is done as follows. (The NOT gates are defined in the header file
lcs/not.h.)
lcs:. Constructors for all the off-the-shelf gates provided in libLCS require two arguments: The output bus as the first argument, and the input bus as the second argument.
Next we shall initialise the AND gate modules of our circuit. The AND gates are defined in the header file
lcs/and.h. A two input AND gate would.
lcs::And<2> ag1(p1, (a,b_)), ag2(p2, (a_,b)); // Notice the use of the template parameter of // 2 to denote a 2-input AND gate. The second //));
With the above OR gate initialisation, we have built our complete circuit. We now need a way to test it. For this, libLCS provides a class
lcs::Tester defined in the header file
lcs/tester.h. It is also a class template requiring one integral template parameter. A
lcs::Tester object will have to be initialised by passing one
lcs::Bus object to the constructor (This bus object should not have been connected previously to the output port of some module). The template parameter to initialise a
lcs::Tester object should be the same as the width of the bus passed as an argument to the constructor. At every clock state change, the
lcs::Tester object feeds a different value onto the
lcs::Bus object with which it was created. The values it feeds are in sequence from 0 to 2w - 1, where w is the width of the bus with which it was created. For our circuit, we will make use of the
lcs::Tester class to feed different values to the inputs
a and
b as follows.
lcs::Tester<2> tester((a,b)); // The template parameter 2 indicates the bus width of // the input bus to our circuit.
Testing our circuit would not only need feeding proper inputs, we should also monitor the output of our circuit to verify the correctness. libLCS provides a class
lcs::ChangeMonitor (defined in the header file
changeMonitor.h) for this. An object of this class should be instantiated by passing a bus object and an
std::string variable to the constructor. Then, it will monitor the bus line states and report whenever a change occurs to the line states using
std::string variable as a name for the bus. For our circuit, we will make use of two
lcs::ChangeMonitor objects: one to monitor the inputs, the other to monitor the output. This is done as follows.
lcs::ChangeMonitor<2> inputMonitor((a,b), "Input", lcs::DUMP_ON); // The template parameter 2 indicates the // bus width of the input bus to our circuit. lcs::ChangeMonitor<1> outputMonitor(s, "Output", lcs::DUMP_ON); // The template parameter 1 indicates the bus // width of the output bus to our circuit.
Note the additional parameter,
lcs:
lcs::DUMP_OFF instead of
lcs::DUMP_ON.
After all the circuit elements are setup, we need to start the simulation. Before we start, we also need to set the time at which the simulation should stop. This is done by a call to the static function
lcs::Simulation::setStopTime. After setting the stop time, we should start the simulation by a call to the static function
lcs::Simulation::start.
The entire/complete program which simulates our circuit is as follows. It is bundeled as an example along with the latest libLCS release file.
#include <lcs/bus.h> #include <lcs/not.h> #include <lcs/and.h> #include <lcs/or.h> #include <lcs/tester.h> #include <lcs/simul.h> #include <lcs/changeMonitor.h> int main() { lcs::Bus<1> a, b, a_, b_, p1, p2, s; lcs::Not<> ng1(a_, a), ng2(b_, b); lcs::And<2> ag1(p1, (a,b_)), ag2(p2, (a_,b)); lcs::Or<2> og(s, (p1,p2)); lcs::ChangeMonitor<2> inputMonitor((a,b), "Input", lcs::DUMP_ON); lcs::ChangeMonitor<1> outputMonitor(s, "Output", lcs::DUMP_ON); lcs::Tester<2> tester((a,b)); lcs::Simulation::setStopTime(1000); lcs::Simulation::start(); return 0; }
When the above program is compiled and run, the following output will be obtained. (See this page
tester feeds. However, since the value was 0 even before the first clock pulse, the
inputMonitor does not display the input states at the time of 100 units. The output corresponding to a 0 input is also 0. Hence, the
outputMonitor does not display anything at the time of 100 units as the output has been 0 even before the first clock pulse. accoridingly as the value has changed is wants a different name for the VCD file, they should set it using the function
lcs::Simulation::setDumpFileName. The dumped VCD file should be viewed using a VCD viewer. GTKWave is one such excellent tool which can plot the VCD wave forms. The screenshot of the GTKWave plot of the VCD file which was generated from the above simulation is as follows: | http://liblcs.sourceforge.net/getting_started.html | CC-MAIN-2017-22 | refinedweb | 1,254 | 63.8 |
On Wed, Oct 28, 2009 at 07:05:30PM -0500, Manoj Srivastava wrote: > On Wed, Oct 28 2009, Tobi wrote: > > > Man. > > I beg to differ. It is really trivial, and it does not make the > rules file less readable > > #!/usr/bin/make -f > ifeq (,$(srip $(ENV_VAR_WE_LOOK_FOR))) > include regular.mk > else > include special.mk > endif > ummm, I don't think so. Have you actually looked at the packages? I'd suggest trying to provide a patch for one of them, because looking at this now it seems very non-trivial to "fix"...and this is from an outsider just like you, I've never even heard of these packages (just did a quick apt-get source and looked around). I don't see what the problem is...this really feels like bikeshedding to me. why not just let them do it their way? it's still a Makefile from every point that matters (just not "head -1"). Honestly this doesn't affect me so I don't care whether or not you let them do this, but I just think you shouldn't call it "trivial", it (at least to me) clearly isn't, and your proposed solution doesn't provide the ellegance that their current one does. -- _________________________ Ryan Niebur ryanryan52@gmail.com
Attachment:
signature.asc
Description: Digital signature | https://lists.debian.org/debian-devel/2009/10/msg00744.html | CC-MAIN-2018-13 | refinedweb | 219 | 76.72 |
Agenda
See also: IRC log
<scribe> scribe: Krcsmith
Dave: Any objections?
[silence]
Dave: So approved for publication
RESOLUTION: Publish last week's minutes
Keith: There have been action
items, Rhys has gone through draft with respect to these
... should be able to access these directly through ref to action number?
Rhys: small bug, but generally,
yes.
... so we should carry on using this mechanism.
<Keith>
Rhys: 4 or 5 particular issues
that need discussion. Need further info before changes.
... [agrees that URI posted by Keith is correct]
... You can also access the issues from Trackbot directly
... [goes through issues at the URI]
... Zeroes and error codes, is that normal in DOM?
... and what should value of propertyfiltererror be?
Keith: should check DOM documentation?
Rhys: seemed unusual to have 0 as
error code (normally it means 'OK')
... what do you use for propertyfiltererror?
Keith: will check if we raise it
Rhys: will propertyfiltererror and accessviolationerror be defined?
Keith: they don't define 0 in the DOM
Rhys: I'll avoid 0
... Issue 6: DCIProp change event. No definition in current document. Think Keith said you just raise a value for it..
... No definition for it formally, any IDL or JavaScript definition?
Keith: We raise a DOM event using our namespace
Rhys: OK for DOM3 (namespace in event), how about DOM2?
Keith: not sure we have namespace
Rhys: if we allow additional DOM methods, there may be events with the same value (DOM v DCCI conflict)
Sailesh: Nodes with DCCI namespace, would that solve for DOM2?
Rhys: But is it possible a
listener could not tell between a DCCI prop change or DOM
event? Do we have a means of distinguishing?
... Is DCCI prop change identifier numeric or string?
Sailesh: I think it's string, can also listen to a group of events
Rhys: If the string that identifies it is characteristic to us, is that good enough?
Sailesh: Unlikely that other event would start with dcci
Keith: +1
Rhys: so no IDL/JavaScript definition, just needs to be documented
PROPOSED RESOLUTION: We will document a specific name to identify these events
<Rotan> From a formalist POV, a unique prefix in a string is not the same as a unique namespace, so we should document the reason for the name change in the document. Perhaps we should informatively note that we're assuming the prefix "DCCI" in a string is sufficient to ensure uniqueness.
Rhys: issue 7: DOM Mutation
events
... Do we need to write about other DOM events? Are mutation events mandatory to support?
Sailesh: Can you say what those events are?
Rhys: Those that indicate tree changes (child inserted, etc.)
Sailesh: We need to be able to convey structural changes to DCCI topology, so those events would be suitable.
Rhys: Mandatory support?
Sailesh: Yes, nodes changed, added removed. So Mutation event support should be mandatory. Keith, what events did we use in old spec?
Keith: We did mention them.
Sailesh: So they have to be mandatory [the three mentioned above]
Rhys: Any more?
<Rotan> Does mutation event identify the specific part of the tree that changes, or does it simply indicate that a change has occurred "somewhere"?
Keith: Just those.
RESOLUTION: Mandatory support for the three mutation events (node added, changed, removed)
<Zakim> Rotan, you wanted to ask the above
Rotan: Not clear on what part of tree has been changed- any clarification?
Keith: It references the parent node
Rotan: OK, so it's efficient, important if many changes, no confusion as to context.
Rhys: Issue 9 - report when
non-DCCI property node inserted
... currently says 'MAY' raise not supported error, shouldn't this be mandatory?
Keith: +1
Rhys: DCCI is a retrieval mechanism, cannot be used to insert. So a DOM implementation that allows 'insert' needs to raise error.
Sailesh: Consumer applications can add nodes, so should be up to the implementation to provide access
Rhys: But not possible using
DCCI?
... So they need to declare non-support.
PROPOSED RESOLUTION: Change 'MAY' to 'MUST' and add text around conditions this may occur
Sailesh: Isn't that a double-condition - if implementation can add a node, it must support raising the event?
Rhys: Yes
... Issue 13 - access to tree root in DOM 3. Keith does your mail cover this, can I put details into document?
Keith: Yes and no - maybe not general enough to be in the spec.
Rhys: Isn't there a mechanism in DOM3 spec for finding an implementation?
Keith: Might be , but we're not using it.
Rhys: Should not be prescriptive about the method. For DOM 2, could use a global variable. So could add a non-normative explanation.
<Rotan> Would we normatively define the global variable, or leave it up to implementations?
RESOLUTION: State that we should not be prescriptive about the method, add non-normative explanation.
Rotan: Would global variable be declared normatively?
Rhys: Worried about doing this in JavaScript, so informative suggestion.
Rotan: Analog with dcci string being used as a namespace, which it's not. So maybe explain that we are picking suggested prefixes.
Sailesh: +1
Rhys: +1
Rotan: Avoids developer confusion around 'reserved' names.
Rhys: Issue 14
... No mandatory namespace support in DOM 3. This allows partial implementations, which is bad (DOM 3 without events). This adds complications.
... Would like to mandate namespace support in DOM 3 (which is a driver to use DOM 3, so it's reasonable).
... Complexity of 3 implementations would cause a problem, so +1
Sailesh: +1
RESOLUTION: Issue 14, mandate support for namespaces for DOM 3 implementations
Dave: But issue around actually having a DOM 3 implementation
Keith: mine is not DOM 3. Only
partially.
... getFeature is used
Rhys: currently in publication moritorium. Hope to have changes by next week.
Dave: Working draft pre-F2F?
Rhys: I think so.
<Rotan> I have the keys, and will email them to group members. Just ask me.
Dave: Sounds right. Any XMLSpy licence we can use?
Sailesh: If we can publish in about 2 weeks, that would give another 2 weeks pre F2F. So could we send out spec for comments with a week's deadline?
Rhys: This will be a working draft, so can request comments immediately.
Dave: Principle of publishing one week before F2F to give time for review.
Dave: Haven't had time for review
of Widget spec.
... Invite for further discussions with XHTML 2 - DONE
... (d) pointers received from Keith, - DONE
... How to indicate actions 'done' through trackbot?
<steph> closing ACTION:
<steph> just go to
Rhys: Generally (from MWI) people claim completion and if WG agrees, then change manually using the Trackbot Web UI.
Dave: As chair I can look after that.
<steph> then select the right issue and click on the right on "close"
Dave: All except one could make an earlier call. Would make it easier for Far East members. One problem from Boston.
Keith: 8am early in Boston...
Dave: [asks Kanghan, is the 9am Boston time OK for the call]
<Kangchan> Yes.
Dave: Will follow up and propose
to change time.
... Next call on 17th? Many members are in Banff.
<steph> my regrets for next 4 weeks till the f2f
Keith: Rhys are you available:
Rhys: No, in Banff
Keith: Then no call.
Dave: Next call wil be on 17th, and we will have new time slot and send confirmation/agenda.
Dave: described on member page.
People need to book hotels. I will set up online form (inc.
agenda suggestions).
... like to look at device coordination, eventing. Please book hotel rooms!
<Rotan> I will be providing maps and other logistics info next week. Need help with picking hotels? Just email me.
<Kangchan> The image in the paper titled "Declarative Models for Ubiquitous Web Applications Morfeo-MyMobileWeb" was broken
<Kangchan> The link to Statement of Interest by Steven Pemberton was also broken.
Dave: list of papers circulated. Will send out list of acceptances next week. Still getting statements of interest.
Rhys: Ready to go - had 2 last
calls. Both documents are up to date. Two lists of last call
... Situation where People who have commented in first last call have not responded in second has been resolved.
... Need pubrules then look at scheduling CR
Dave: So what is next step?
Rhys: CR
Dave: So need to prepare a draft, + dispostion of comments.
Rhys: This is all linked from DI
pages. I'll also circulate an email.
... Normally our team contacts do pubrules
... If someone can prepare boilerplate I can drop in the text.
... But if it can be done in the XML, even better
Dave: Review period?
Rhys: No particular pressure.
Dave: But what about sufficient implementations?
Rhys: We have on partial one that we know of. Not sure if Max's is still accessible.
<scribe> ACTION: Dave to contact Max re DISelect implemntation [recorded in]
<trackbot-ng> Created ACTION-4 - Contact Max re DISelect implementation [on Dave Raggett - due 2007-05-10].
Dave: Suggest 6 months for comments/implementation?
<scribe> ACTION: Dave to organise transition call for DISelect [recorded in]
<trackbot-ng> Created ACTION-5 - Organise transition call for DISelect [on Dave Raggett - due 2007-05-10].
Rhys: Lots of discussion at DDWG
F2F. Got more clarity on how ontology works. Also fruitful
discussion over properties that can vary.
... DDR would store fixed properties, but non-fixed properties are of interest to other groups.
... e.g. Sony Ericsson 910 has flip out screen pad which when open reveals more of the screen.
... You can model that in a DDR, but not whether the screen is currently open or not.
... So we need to model the range of minimums/maximums, defaults etc.
... We can model current states in the ontology [but should not be in the DDR]
... Should be a new version of ontology doc next couple of weeks to reflect this
[Ends] | http://www.w3.org/2007/05/03-uwawg-minutes.html | CC-MAIN-2016-18 | refinedweb | 1,630 | 68.36 |
Module to generate PCAPs from any input file. This is a modified version of PGT tool which wasdeveloped earlier by, Andrewg Felinemenace.
Project description
Pcapgen PCAP Generation Suite
pgtlib
pgtlib is a wrapper built on top of Scapy to provide additional flexibility to create custom TCP client<->server packet captures. This module would also provide functionality to prefix 3-way TCP Handshake and close established connections gracefully.
pgtlib usage
Let's say over TCP/5555, you would like to send "----> hey from client\n" from client and server echoes back with a response message saying, "<---- ack data\n". Let's construct a packet based on this:
from pcapgen.pgtlib import * fHandle = PCAP('/tmp/tcp.pcap') # PCAP Output Filename conn = fHandle.tcp_conn_to_server(5555) # Assign dest port as TCP/5555 conn.to_server('----> hey from client\n') # Client message to server conn.to_client('<---- ack data\n') # Server message to client conn.finish() # Construct FIN fHandle.close() # Close file handle print('[*]Done.')
pft
PCAP Fix Tool (pft, in short) is a wrapper on top of scapy. This utility helps in resolving broken TCP communications, changing endpoint directions and ports etc. This tool takes the C Arrays input of any TCP stream, appends the missing TCP 3-Way handshakes along with adding the necessary FIN TCP flags to terminate the established TCP communication gracefully.
pft usage
- Open faulty pcap and navigate to the faulty TCP stream index that you want to correct.
- View data as 'C Arrays' and export the output to any flat file e.g. /tmp/raw
- $python pft.py -p 1337 -w /tmp/raw
- This would geneate raw.pcap (currently supports PCAP format only) which would have TCP/1337 as destination port along with the end-to-end PDU data intact.
pgt
PCAP Genation Tool (pgt) is wrapper built on top of scapy again which generates simulated HTTP,FTP and Email (SMTP/IMAP) protocols data along with several encoding types i.e. base64, deflate, gzip etc.
pgt usage
$python pgt.py ~/Desktop/sample.docx # Generates HTTP(GET/POST), FTP(active and passive), SMTP and IMAP PCAPs.
External dependencies
- scapy [pip install scapy]
- python-magic [pip install python-magic]
Credits
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/pcapgen/ | CC-MAIN-2020-05 | refinedweb | 384 | 58.58 |
Elements
Introduction
This section covers the elements types for our halfedge mesh, as well as the traversal and utility functions that they offer.
#include "geometrycentral/surface/halfedge_mesh.h"
Note
In the most proper sense, these element types are really “handles” to the underlying element. They refer to a particular element, but the
Vertex variable in memory is not really the mesh element itself, just a temporary reference to it.
For instance, it is possible (and common) to have multiple
Vertex variables which actually refer to the same vertex, and allowing a
Vertex variable to go out of scope certainly does not delete the vertex in the mesh.
However, the semantics are very natural, so for the sake of brevity we call the type simply
Vertex, rather than
VertexHandle (etc).
Additionally, see navigation for iterators to travese adjacent elements, like
for(Vertex v : face.adjacentVertices()).
Construction
Element types do not have constructors which should be called by the user. Instead, the element will always be created for you, via one of several methods, including:
- Iterating through the mesh
for(Vertex v : mesh.vertices())
- Traversing from a neighbor element
Face f = halfedge.face()
- Iterating around an element
for(Halfedge he : vertex.outgoingHalfedges())
Adding a new element to a mesh is covered in the mutation section.
Comparison & Hashing
All mesh elements support:
- equality checks (
==,
!=)
- comparions (
<,
>,
<=,
>=, according to the iteration order of the elements)
- hashing (so they can be used in a
std::unordered_map)
Vertex
A vertex is a 0-dimensional point which serves as a node in the mesh.
Traversal:
Halfedge Vertex::halfedge()
Returns one of the halfedges whose tail is incident on this vertex.
If the vertex is a boundary vertex, then it is guaranteed that the returned halfedge will be the unique interior halfedge along the boundary. That is the unique halfedge such that
vertex.halfedge().twin().isInterior() == false.
Corner Vertex::corner()
Returns one of the corners incident on the vertex.
Utility:
bool Vertex::isBoundary()
Returns true if the vertex is along the boundary of the mesh.
See boundaries for more information.
size_t Vertex::degree()
The degree of the vertex, i.e. the number of edges incident on the vertex.
size_t Vertex::faceDegree()
The face-degree of the vertex, i.e. the number of faces incident on the vertex. On the interior of a mesh, this will be equal to
Vertex::degree(), at the boundary it will be smaller by one.
Halfedge
A halfedge is a the basic building block of a halfedge mesh. As its name suggests, the halfedge is half of an edge, connecting two vertices and sitting on on side of an edge in some face. The halfedge is directed, from its tail, to its tip. Our halfedges have a counter-clockwise orientation: the halfedges with in a face will always point in the counter-clockwise direction, and a halfedge and its twin (the neighbor across an edge) will point in opposite directions.
Traversal:
Halfedge Halfedge::twin()
Returns the halfedge’s twin, its neighbor across an edge, which points in the opposite direction.
Calling twin twice will always return to the initial halfedge:
halfedge.twin().twin() == halfedge.
Halfedge Halfedge::next()
Returns the next halfedge in the same face as this halfedge, according to the counter-clockwise ordering.
Vertex Halfedge::vertex()
Returns the vertex at the tail of this halfedge.
Edge Halfedge::edge()
Returns the edge that this halfedge sits along.
Face Halfedge::face()
Returns the face that this halfedge sits inside.
Note that in the case of a mesh with boundary, if the halfedge is exterior the result of this function will really be a boundary loop. See boundaries for more information.
Corner Halfedge::corner()
Returns the corner at the tail of this halfedge.
Fancy Traversal:
Halfedge Halfedge::prevOrbitFace()
Returns the previous halfedge, that is the halfedge such that
he.next() == *this. This result is found by orbiting around the shared face.
Because our halfedge mesh is singly-connected, this is not a simple O(1) lookup, but must be computed by orbiting around the face. Be careful: calling
he.prevOrbitFace() on each exterior halfedge can easily lead to O(N^2) algorithm complexity, as each call walks all the way around a a boundary loop.
Generally this operation can (and should) be avoided with proper code structure.
Halfedge Halfedge::prevOrbitVertex()
Returns the previous halfedge, that is the halfedge such that
he.next() == *this. This result is found by orbiting around the shared vertex.
Because our halfedge mesh is singly-connected, this is not a simple O(1) lookup, but must be computed by orbiting around the vertex. Be careful: calling
he.prevOrbitVertex() in a loop around a very high-degree vertex can easily lead to O(N^2) algorithm complexity, as each call walks all the way around the vertex.
Generally this operation can (and should) be avoided with proper code structure.
Utility:
bool Halfedge::isInterior()
Returns true if the edge is interior, and false if it is exterior (i.e., incident on a boundary loop).
See boundaries for more information.
Edge
An edge is a 1-dimensional element that connects two vertices in the mesh.
Traversal:
Halfedge Edge::halfedge()
Returns one of the two halfedges incident on this edge. If the edge is a boundary edge, it is guaranteed that the returned edge will be the interior one.
Utility:
bool Edge::isBoundary()
Returns true if the edge is along the boundary of the mesh. Note that edges which merely touch the boundary at one endpoint are not considered to be boundary edges.
See boundaries for more information.
Face
A face is a 2-dimensional element formed by a loop of 3 or more edges. In general, our faces can be polygonal with d \ge 3 edges, though many of the routines in geometry central are only valid on triangular meshes.
Traversal:
Halfedge Face::halfedge()
Returns any one of the halfedges inside of this face.
BoundaryLoop Face::asBoundaryLoop()
Reinterprets this element as a boundary loop. Only valid if the face is, in fact, a boundary loop. See boundaries for more information.
Utility:
bool Face::isBoundaryLoop()
Returns true if the face is really a boundary loop. See boundaries for more information.
bool Face::isTriangle()
Returns true if the face has three sides.
size_t Face::degree()
Returns the number of sides in the face. Complexity O(d), where d is the resulting degree.
Boundary Loop
A boundary loop is a special face-like element used to represent holes in the mesh due to surface boundary. See boundaries for more information.
Traversal:
Halfedge BoundaryLoop::halfedge()
Returns any one of the halfedges inside of the boundary loop.
Utility:
size_t BoundaryLoop::degree()
Returns the number of sides in the boundary loop. Complexity O(d), where d is the resulting degree.
Corner
A corner is a convenience type referring to a corner inside of a face. Tracking corners as a separate type is useful, because one often logically represents data defined at corners.
Traversal:
Halfedge Corner::halfedge()
Returns the halfedge whose tail touches this corner. That is to say,
corner.halfedge().vertex() == corner.vertex().
Vertex Corner::vertex()
Returns the vertex which this corner is incident on.
Face Corner::face()
Returns the face that this corner sits inside of. | https://geometry-central.net/surface/halfedge_mesh/elements/ | CC-MAIN-2020-16 | refinedweb | 1,195 | 57.27 |
Angular: Set Base URL Dynamically
Recently one of my Angular projects had a requirement to have multiple instances of websites hosted on the same domain with different base URLs. For example, the application URL is and now you want to create multiple sites with different base URL:
and so on. With the change in base URL, the API path also changed from /api/GetCall to /client1/api/GetCall.
If we want to change the base URL, we have two problems to solve:
1. Handle Angular routing to accommodate base URL.
2. Handle Http service requests and append base URL to each request.
1. Fix Routing
You just need to put a <base> tag in the head of the index or Layout page and specify a base URL like this:
<base href="/client1/" />
So if you had an Angular route defined like this:
{ path: 'home', component: HomeComponent }
this route would become /client1/home if <base href="/client1/" /> is present in the head section of the page.
2. Append Base URL to HTTP requests
We have an API relative URL which starts at /api/products. In this section, we want to make sure that when we make a call to API, the base URL is appended to the API URL, so in this case, the API URL becomes /client1/api/products.
/api/products --> /client1/api/products
There are two popular ways of achieving this, one, using HttpInterceptors and, two, using dependency injection.
Using Dependency Injection:
Register a base URL provider in the module so it is available everywhere in the application:
providers: [ { provide: 'BASE_URL', useFactory: getBaseUrl } ]
Provide factory method which gets the base URL from <base> element:
export function getBaseUrl() { return document.getElementsByTagName('base')[0].href; }
Now you can get the base URL injected and add it to URL:
export class FetchProductsComponent { public forecasts: IProduct[]; constructor(http: Http, @Inject('BASE_URL') baseUrl: string) { http.get(baseUrl + 'api/products').subscribe(result => { this.products = result.json() as IProduct[]; }, error => console.error(error)); } }
Using HttpInterceptors:
Since HttpInterceptors were introduced in Angular 4.3, this will not work on earlier versions.
HttpInterceptor intercepts requests made using HttpClient, if you try to make requests with old Http class, interceptor won't hit.
To create an interceptor, create an Injectable class which implements HttpInterceptor.
import { Injectable } from '@angular/core'; import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; @Injectable() export class ApiInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const baseUrl = document.getElementsByTagName('base')[0].href; const apiReq = req.clone({ url: `${baseUrl}${req.url}` }); return next.handle(apiReq); } }
Register interceptor as a provider:
{ provide: HTTP_INTERCEPTORS, useClass: ApiInterceptor, multi: true }
Now whenever you make any Http request using HttpClient, ApiInterceptor will be invoked and base URL will be added to the API URL.
When you have two options to append base URL to Http requests, which one to choose? I liked the interceptor way as you do not need to inject it in all the places where you are making Http calls, just write one interceptor and done, it will intercept all the Http calls made using HttpClient.
Have any questions or suggestions? Please drop a message in the comments section below. | http://www.projectcodify.com/angular-set-base-url-dynamically | CC-MAIN-2021-49 | refinedweb | 531 | 52.49 |
GraphQL is a language and set of technologies that make querying data easier for modern frontend applications. Named the technology developers are most interested in learning in the “2019 State of JavaScript” report, GraphQL is recognized as a scalable and production-ready tool that is used by many industry giants such as Github, Netflix, and Shopify, to name a few.
While most features of GraphQL are well-understood (e.g., directives, input types, resolvers), enum types are often underrated and their usefulness largely unknown. In this tutorial, we’ll shed light on why enums are important and explore the essential role this simple type plays in building robust GraphQL APIs.
GraphQL schemas
GraphQL APIs rely on GraphQL schemas to expose data. GraphQL provides it owns scalar types (
Int,
Float,
String,
Boolean, and
ID) and lets you create your own data types using the following keywords.
typeto define complex object types used by queries (read data)
inputto define input types used as arguments by mutations (create, update, delete data)
We’ll base all our examples on the following schema describing a user management API.
# A User (profile) is linked to some Accounts that carries all authentication information type Account { id: ID! # "!" indicate a non-null (mandatory) field authType: String! # "google-auth", "github-auth", "outlook-auth"!]! } # we define an "input" type for our updateAccount mutation input UpdateAccountInput { id: ID! state: String! # "verified", "disabled", "archived" } type Mutation { updateAccount(input: UpdateAccountInput!): Account! }
Our GraphQL API allows us to list all users with some optional filters.
status, of
Stringtype, allows us to filter the multiple boolean fields of
Userusing a simple
Stringvalue:
“verified”, “disabled”, “archived”
authTypeis based on
Account.authType
The API uses the
Account.authType value (
“google-auth”, “github-auth”, “outlook-auth”) internally to leverage the proper provider to authenticate but also to get user profile information.
“google-auth” leads to the appropriate logic under the
GoogleProfileProvide namespace.
We can get the first 10 active users to use Google by doing the following.
user(first: 10, authType: "google-auth", status: "verified") { id # ... }
Our API also exposes an
updateAccount mutation, which allows us to update an account status during its lifecycle.
This schema is functional as-is. However, we can make it way more robust by leveraging GraphQL enums.
Why use enums?
Although when using
String,
Account.authType, and
UpdateAccountInput.state we can expect to receive specific values, this can introduce issues at multiple levels.
Strings are case-sensitive and break GraphQL validations
Below is an example of how you might use the
users query.
query { users(first: 10, status: "Verified") { id } }
GraphQL-wise, on the client side (e.g., Apollo), this query is entirely valid. However, can you spot the typo?
The
status value
“Verified”, should be written as
“verified”.
Having a free-form
String type here might trigger unexpected 500s, silent errors, or, worse, security vulnerabilities.
To prevent this, we’ll have to add some validation logic to our
users query resolver.
interface UsersArgs { first: number, from?: string, status?: String, authType?: string, } const STATUSES = ['', '', ] export const resolvers = { Query: { users: (_record: never, args: UsersArgs, _context: never) { if (args?.status && !STATUSES.includes(args.status)) { // throw error } // ... } } }
This is quite counterproductive since the principal value of GraphQL type-based schemas is to provide validation out of the box on operations and data. Using enums will limit the status value to a given set of defined values and avoid duplicate validations logic.
Exposing internal values
We saw that
Account.authType relys on a
String type, which leads to the following kind of
users query.
query { users(first: 10, authType: "google-auth") { id } }
Such a pattern is not optimal because exposing internal values goes against the principle that APIs should expose a simple, decoupled interface with data.
Again, we can improve our
users query resolver to allows public-friendly values for filtering.
interface UsersArgs { first: number, from?: string, status?: String, authType?: string, } const AUTH_TYPES_FILTER_MAP = { 'GOOGLE': 'google-auth', 'GITHUB': 'github-auth, 'OUTLOOK': 'outlook-auth', } export const resolvers = { Query: { users: (_record: never, args: UsersArgs, _context: never) { // does both mapping and validation (invalid value will be ignored) const authType = AUTH_TYPES_FILTER_MAP[args.authType] // ... } } }
This would allow the following query.
query { users(first: 10, authType: "GOOGLE") { id } }
However, here again, we have to build a feature already provided by GraphQL via enums.
In the next section, we’ll walk through how to map enums to internal values by migrating our schema to enums.
Discoverability issue (TypeScript, GraphiQL/Explorer)
The last downside of relying on the
String type for filter- or choice-based values is discoverability.
If you have an
UpdateAccountInput.status that relies on the
String type, GraphQL won’t be able to inspect the possible values of
UpdateAccountInput.status during the introspection query since only the resolvers know about them.
GraphQL introspection is one of the core features of GraphQL that allows clients to dynamically inspect the schema definition by doing a GraphQL query (inception).
Here’s an example listing all the queries defined on our schema:
query { __schema { queryType { fields { name args { name type { name description } } description deprecationReason } } } } { "data": { "__schema": { "queryType": { "fields": [ { "args": [ { "name": "authType", "type": { "name": "String", "description": null } }, { "name": "first", "type": { "name": null, "description": null } }, { "name": "from", "type": { "name": "ID", "description": null } }, { "name": "status", "type": { "name": "String", "description": null } } ], "deprecationReason": null, "name": "users", "description": "perform the action: \"users\"" } ] } } } }
Tools like GraphiQL use introspection to provide autocomplete functionality. GraphQL Code Generator also uses it to generate TypeScript types.
String types do not allow us to inspect the possible values.
GraphQL enums are introspectable, allowing the app to autocomplete possible values and generate corresponding TypeScript types.
Migrating to enums
Relying on
String may lead to security issues, unnecessary validation logic on the resolvers side, and a poor developer experience.
Let’s make our GraphQL Schema more robust by migrating to enums.
How to use enums
GraphQL enums can be defined using the
enum keyword.
enum AuthType { GOOGLE GITHUB OUTLOOK }
According to the official specification, you should name enums values using the all-caps convention. Enum values don’t need any common prefix since they are namespaced by the enum’s name.
Updating the schema
Let’s take a look at our new enums-based schema:
enum AuthType { GOOGLE GITHUB OUTLOOK } # A User (profile) is linked to some Accounts that carries all authentication information type Account { id: ID! # "!" indicate a non-null (mandatory) field authType: AuthType!!]! } enum AccountState { VERIFIED, DISABLED, ARCHIVED } # we define an "input" type for our updateAccount mutation input UpdateAccountInput { id: ID! state: AccountState! } type Mutation { updateAccount(input: UpdateAccountInput!): Account! }
Enum internal values
Enum value resolution (at resolver and client side) is an implementation detail, meaning that each library chooses how to resolve a given enum value to a language-specific value.
With Apollo Server, each enum value will resolve to its string equivalent.
AuthType.GOOGLEresolves to
“GOOGLE”
AuthType.GITHUBresolves to
“GITHUB”
AuthType.OUTLOOKresolves to
“OUTLOOK”
However, our API expected manipulated internal values (
“google-auth”, “github-auth”, “outlook-auth”) to operate appropriately.
Per the official documentation, Apollo Server enables you to provide enum resolvers, as shown below with our updated
users query resolver.
JavaScript version:
export const resolvers = { AuthType: { GOOGLE: 'google-auth', GITHUB: 'github-auth', OUTLOOK: 'outlook-auth', }, Query: { users: (_record, args, _context) { // args.authType will always be 'google-auth' or 'github-auth' or 'outlook-auth' // ... } } }
TypeScript version:
enum AuthType { GOOGLE = 'google-auth', GITHUB = 'github-auth', OUTLOOK = 'outlook-auth', } interface UsersArgs { first: number, from?: string, status?: String, authType?: AuthType, } export const resolvers = { AuthType, Query: { users: (_record: never, args: UsersArgs, _context: never) { // args.authType will always be 'google-auth' or 'github-auth' or 'outlook-auth' // ... } } }
Note that with TypeScript, an enum type can be directly passed as a resolver.
Apollo Server will resolve enum values to their proper internal values (
resolvers.AuthType) for both input and output data (
Mutation arguments and
Query returned data).
Now that our schema relies on enums, let’s see how it improves our queries and mutations usage.
Querying with enums
We can now query our users and filter using our
AuthType enum.
query { users (first: 10, authType: GOOGLE) { id } }
Our query is now safe, typoless, and fully discoverable.
But the enum value as
String is not valid. The field using an enum type requires an enum reference, so passing the enum value isn’t considered valid.
Bonus: TypeScript generation
GraphQL enums are introspectable, as shown below.
Introspectable enums mean that tools like GraphQL Code Generator will generate the corresponding TypeScript enum type for your frontend application.
With our schema, GraphQL code generator will be able to create the corresponding TypeScript enum:
export enum AuthType { GOOGLE = 'google-auth', GITHUB = 'github-auth', OUTLOOK = 'outlook-auth', }
This will come in handy for later use (
useQuery(),
useMutation()):
const ActiveUsersList = () => { const { loading, data } = useQuery( usersQueryDocument, { variables: { first: 10, authType: AuthType.GOOGLE, } }) // ... }
Relying on both GraphQL enums and TypeScript-generated enums makes for a robust and powerful developer experience.
Summary
Even on small GraphQL APIs, such as the User Management API, enums bring a lot of consistency and make your schema more robust.
In this tutorial, we explored how GraphQL enums can help:
- Provide a more robust and discoverable API — Every list-based or filtering field of your schema should leverage enums to avoid security, typo-related, and discoverability issues. Using enums a great example of embracing the main power of GraphQL: semantic operations and on-flight data validation
- Expose a simple interface — The main goal of an API is to provide a simplified interface over data or complex systems. This is even more true with GraphQL, which brought natural, JSON-like APIs to the frontend world. GraphQL enums are an excellent approach to abstracting internal values to simple choices when it comes to filtering
- Maintain slim resolvers — When building a GraphQL API, it’s essential not to reimplement the features provided by GraphQL. If the main features of GraphQL are operation validation (e.g., operation asked, the structure of arguments) and data validation (for both input and output), the resolvers should be slim by only focusing on the business logic (e.g., data manipulation, extra complex validation)_6<<
>>IMAGE “What you need to know about GraphQL enums”
Great write-up, thank you!
I have a question though: It isn’t clear to me how the client side can know the internal values for the enum. Since Apollo has devs define those internal values in a resolver, they don’t show up in the server schema itself, and therefore when you tell codegen to run for the client, it can’t know about the internal values. Am I missing some helpful setting or something? Do you have a complete version of your example in a repo? | http://blog.logrocket.com/what-you-need-to-know-about-graphql-enums/ | CC-MAIN-2020-40 | refinedweb | 1,764 | 54.73 |
In this section we will learn about the Java OutputStreamWriter.
java.io.OutputStreamWriter is a character written output stream which encodes the characters into bytes, for encoding this class uses a specific charset. OutputStreamWriter is acted as a bridge into encoding of character streams to byte streams. write() method in OutputStreamWriter facilitate to write characters to the stream. Wrapping within BufferedWriter of this class makes it more efficient.
Constructor Detail
Method Detail
Example
Here an example is being given which will demonstrate about how to use the OutputStreamWriter. A Java class that I have created for demonstrating how to use the OutputStreamWriter. In this class I have used various classes of java.io package for completing this example. As it is discussed that OutputStreamWriter class should be wrapped within BufferedWriter so I have used this class in my example except this the FileOutputStream class is used. Using this example I have tried to write the data to a file. So, when you will executed this example successfully you will see that a file is created with the name (if not existed) and in the directory specified by you.
Source Code
JavaOutputStreamWriterExample.java
import java.io.BufferedWriter; import java.io.OutputStreamWriter; import java.io.OutputStream; import java.io.FileOutputStream; import java.io.IOException; public class JavaOutputStreamWriterExample { public static void main(String args[]) { OutputStream os = null; OutputStreamWriter osw = null; BufferedWriter bw = null; try { /*os = new FileOutputStream("test.txt"); osw = new OutputStreamWriter(os); osw.write("Java IO OutputStreamWriter Example"); */ os = new FileOutputStream("test.txt"); osw = new OutputStreamWriter(os); bw = new BufferedWriter(osw); bw.write("Hello"); bw.newLine(); bw.write("Java IO OutputStreamWriter Example"); System.out.println("Contents written to the file successfully."); } catch(IOException ioe) { System.out.println(ioe); } finally { if(os != null) { try { bw.flush(); bw.close(); os.flush(); os.close(); osw.close(); } catch(Exception e) { System.out.println(e); } } }// finally close }// main close }// class close
Output
When you will compile and execute this example you will get the output as follows :
And to see where the contents has been written go to your directory what you have specified at the programming time and open your file.
Advertisements
Posted on: December IO OutputStreamWriter
Post your Comment | http://www.roseindia.net/java/example/java/io/outputstreamwriter.shtml | CC-MAIN-2016-30 | refinedweb | 364 | 52.26 |
19 November 2010 10:58 [Source: ICIS news]
LONDON (ICIS)--Polyethylene (PE) buyers in ?xml:namespace>
“If I can get €30/tonne ($41/tonne) [less] in December I will consider that a real achievement,” said one buyer of high density polyethylene (HDPE). “We’re not even buying that much, but [producers] won’t budge.”
PE buyers had faced price increases of around €30/tonne in November, an amount that would cover the €28/tonne increase in the monthly ethylene contract price, which now stood at €978/tonne FD (free delivered) NWE (northwest Europe).
Buyers of low density polyethylene (LDPE) were under even more pressure, as producers aim to raise prices next month.
On 18 November, Dow Chemical announced a €70/tonne increase for December PE. The US-based chemical major was making it clear that it was looking to cover what it saw as its increased costs in PE.
Dow Chemical’s move was met with hilarity by some and anger by others. A couple of sources noted that Dow’s price increase has changed the debate over the direction of PE pricing in December.
“If Dow announces plus €70/tonne, that means others will roll over,” said one buyer, “but it also means that we might not be able to get lower prices.”
Producers of LDPE and linear low density polyethylene (LLDPE) reported strong demand this month, and Dow said that it had already closed its order books for November.
Several sources questioned the premise that demand was good, instead putting higher prices down to restricted availability rather than particularly healthy demand.
Several permanent capacity closures in the LDPE market, coupled with the less-than-stellar performance of new plants in Europe and the Middle East and the strikes last month in
“I see LDPE as structurally tight now,” said another producer, “and I can’t see it getting any better in the future.”
Another producer said that LDPE should no longer be considered a commodity; it should command a premium over its traditional blending partner, linear low density PE (LLDPE).
The price gap between the two grades had soared to as much as €200/tonne in some cases, although this was not typical of contracts between producers and their buyers. The traditional €50/tonne delta was no longer valid, however.
LDPE net prices were moving as high as €1,300/tonne FD NWE at some accounts. LLDPE C4 was trading around €1,100/tonne FD NWE. Monthly contractual business did not show such extremes.
With rises in crude oil and naphtha prices, PE producers aimed to grab back the margins they had lost. A recent dip in crude oil prices from the recent $90/bbl high had led some buyers to expect some relief in December.
“I was predicting a rollover in December after recent falls in the oil price,” said another buyer.
Crude oil was trading at $85.96/bbl on Friday morning.
Countering reports that demand was shoddy, one major LLDPE producer reported November as its best sales month ever.
Whether or not higher prices are implemented in December, PE prices are unlikely to move down to any great extent next month.
Inventories were low, even if demand tailed off significantly. Producers and traders were under no pressure to sell and they saw no reason to offer discounts.
“Ethylene is getting tighter and we could see a big jump in the December contract,” said the LLDPE producer. “We won’t give away any more margin.”
Buyers said they had been disappointed with the amount of material coming out of the
For 2011, buyers were more cautious in their outlooks.
“We are discussing volumes for 2011 now,” said the producer. “Buyers don’t trust the
“The situation is dynamic, driven by the Middle East, but the
($1 = €0.73)
For more on polyethylene visit ICIS chemical intelligence
For more on Dow Chemical | http://www.icis.com/Articles/2010/11/19/9412006/europe-pe-buyers-unable-to-obtain-lower-prices-in-november.html | CC-MAIN-2014-52 | refinedweb | 645 | 61.56 |
Provides a simple set of guards that you can use in your tests to skip execution if it is not applicable. These methods are mixed into Test as both instance and class methods so you can use them inside or outside of the test methods.
def test_something_for_mri skip "bug 1234" if jruby? # ... end if windows? then # ... lots of test methods ... end
Is this running on jruby?
# File lib/minitest.rb, line 770 def jruby? platform = RUBY_PLATFORM "java" == platform end
Is this running on maglev?
# File lib/minitest.rb, line 777 def maglev? platform = defined?(RUBY_ENGINE) && RUBY_ENGINE "maglev" == platform end
Is this running on mri?
# File lib/minitest.rb, line 784 def mri? platform = RUBY_DESCRIPTION /^ruby/ =~ platform end
Is this running on rubinius?
# File lib/minitest.rb, line 791 def rubinius? platform = defined?(RUBY_ENGINE) && RUBY_ENGINE "rbx" == platform end
Is this running on windows?
# File lib/minitest.rb, line 798 def windows? platform = RUBY_PLATFORM /mswin|mingw/ =~ platform end
© Ryan Davis, seattle.rb
Licensed under the MIT License. | http://docs.w3cub.com/minitest/minitest/guard/ | CC-MAIN-2017-43 | refinedweb | 165 | 70.9 |
I want to create an interface that implements some of its own methods in Java (but the language won't allow this, as shown below):
//Java-style pseudo-code
public interface Square {
//Implement a method in the interface itself
public int getSize(){//this can't be done in Java; can it be done in C++?
//inherited by every class that implements getWidth()
//and getHeight()
return getWidth()*getHeight();
}
public int getHeight();
public int getWidth();
}
//again, this is Java-style psuedocode
public class Square1 implements Square{
//getSize should return this.getWidth()*this.getHeight(), as implemented below
public int getHeight(){
//method body goes here
}
public int getWidth{
//method body goes here
}
}
Is it possible to create the equivalent of an interface in C++ that can implement some of its own methods?
To answer your other question, yes it can be done in C++ through the use of the
virtual keyword. To my knowledge, it is the primary method of polymorphism in C++.
This set of tutorials is great; I would recommend a solid read-through if you want to learn more about C/C++.
Use an
abstract class:
public abstract class Square { public abstract int getHeight(); public abstract int getWidth(); public int getSize() { return getWidth() * getHeight(); } }
Does it have to be interface? Maybe abstract class will be better.
public abstract class Square { public int getSize() { return getWidth() * getHeight(); } //no body in abstract methods public abstract int getHeight(); public abstract int getWidth(); } public class Square1 extends Square { public int getHeight() { return 1; } public int getWidth() { return 1; } }
I think you're mixing up interfaces with abstract classes:
An interface describes the contract that all implementing classes must obey. It is basically a list of methods (and, importantly, documentation of what they should return, how they should behave etc.
Notice that NONE of the methods have a body. Interfaces do not do that. You can, however, define static final constants in an interface.
public interface Shape { /** * returns the area of the shape * throws NullPointerException if either the height or width of the shape is null */ int getSize(); /** * returns the height of the shape */ int getHeight(); /** * returns the width of the shape */ int getWidth(); }
An abstract class implements some of the methods, but not all. (Technically the abstract class could implement all methods, but that wouldn't make for a good example). The intention is that extending classes will implement the abstracted methods.
/* * A quadrilateral is a 4 sided object. * This object has 4 sides with 90' angles i.e. a Square or a Rectangle */ public abstract class Quadrilateral90 implements Shape { public int getSize() { return getHeight() * getWidth(); } public abstract int getHeight(); // this line can be omitted public abstract int getWidth(); // this line can be omitted }
Finally, the extending object implements all the remaining methods both in the abstract parent class and in the interface. Notice that getSize() is not implemented here (though you could override it if you wanted to).
/* * The "implements Shape" part may be redundant here as it is declared in the parent, * but it aids in readability, especially if you later have to do some refactoring. */ public class Square extends Quadrilateral90 implements Shape { public int getHeight() { // method body goes here } public int getWidth() { // method body goes here } } | http://m.dlxedu.com/m/askdetail/3/dbb49733dc7d72a79158b3c5597c3d20.html | CC-MAIN-2018-30 | refinedweb | 534 | 55.98 |
01 March 2012 11:38 [Source: ICIS news]
SINGAPORE (ICIS)--India’s Reliance Industries Ltd (RIL) has raised its list prices for all grades of polyethylene (PE) and polypropylene (PP) by rupees (Rs) 1.00-3.00/kg (Rs1,000-3,000/tonne, $20-61/tonne), on persistently short supply and high raw materials costs, a source close to the company said on Thursday.
RIL raised linear low density (LLDPE) film list prices by Rs3.00/kg late on 29 February, while high density PE (HDPE) and PP grades were increased by Rs2.00/kg. LDPE film list prices were up by Rs1.00/kg.
The new PE list prices now stand at Rs92.50-93.00/kg ?xml:namespace>
The revised PP list prices are at Rs91.00-93.00/kg DEL India for raffia and Rs97.00-98.00/kg
The tight domestic market is a result of the forthcoming shutdowns at the HDPE facilities of Indian Oil and Gail India, the source said.
Imports, originating from the
Soaring high naphtha prices at close to $1,100/tonne CFR (cost and freight)
“Propane prices are very high now, we have no choice but to raise our prices to maintain decent margins,” he added.
The increase in list prices by RIL is the second adjustment since February for LDPE, HDPE and PP, while LLDPE film is the third adjustment (please see graph below), he said.
“There may be another upward adjustment in the [PE] list prices in the middle of March because the market is still looking tight. We will adjust our list prices according to the market price,” the source said.
Spot prices in the domestic open market this week were discussed Rs1.00-2.00/kg higher at Rs89.00-90.00/kg
($1 = Rs49 | http://www.icis.com/Articles/2012/03/01/9537165/indias-reliance-hikes-pe-pp-prices-on-tight-supply-high.html | CC-MAIN-2014-41 | refinedweb | 298 | 80.62 |
Working with refs in React
.
When to use Refs:
Here are a few good use cases for refs:
- Managing focus, text selection, or media playback.
- Triggering imperative animations.
- Integrating with third-party DOM libraries.
We can use ref in functional and class components both by using React.useRef and React.createRef respectively.
React.createRef and React.useRef
Both React APIs are used to create a mutable object. The mutable object’s properties can be changed without affecting the Component’s state i.e
refs are used when there is no need to re-render the component.
The object has a
current property, this property is where the value is stored and referenced.
These APIs create these mutable objects which can be called
refs. They hold a reference to any value we want
React.createRef are used in class components to create refs.
React.useRef are used in functional components to create refs.
Let’s create a functional component and use React.useRef.
Increament the count by using ref:
import React, {useRef, useEffect } from "react";const CheckRef = () => {
const renderCount = useRef(0);
return (
<>
<div>
<button onClick={() => handleCount()}>Increase Render Count</button>
<div>Render Item {renderCount.current} times.</div>
<div>
)
}
In the above example, we created a refs named as renderCount with an initial value 0 and used {renderCount.current} to show count value.
and click event on the button named as handleCount.
Let’s create a state with the help of this state that will change the value of count on click event.
const [countVal, setCountVal] = useState(false);
const handleCount = () => {
setCountVal(countVal ? false : true);
};
useEffect(() => {
renderCount.current = renderCount.current + 1;
});
Here on click event countVal will be changed from true to false and vice versa, As we know by using useEffect hook, you tell React that your component needs to do something after render. React will remember the function you passed (we’ll refer to it as our “effect”), and call it later after performing the DOM updates.
So this will increase the count by one every time the user clicks on the button.
Focus on Input by using ref
import React, {useRef} from "react";const CheckRef = () => {
const inputRef = useRef(""); return (
<>
<div>
<input ref={inputRef}></input>
<button onClick={() => inputFocus()}>
Input Focus</button>
</div>
)
}
In the above example, we created refs named as inputRef with an initial value blank and click event on the button named as inputFocus.
const inputFocus = () => {
inputRef.current.focus();
};
By clicking on the Input Focus button, inputRef.current.focus() will move focus on Input.
We can do the same thing with the class component, Let’s create a class component and use React.CreateRef.
Focus on Input by using React.CreateRef
class CheckRefConstructor extends React.Component {
constructor(props) {
super(props);
this.inputRef= React.createRef();
}
render() {
return (
<div>
<input type="text" ref={this.inputRef} />
<button onClick={this.focusInput}>Focus input</button>
</div>
);
}
}
In the above example, we created refs named as inputRef by using React.createRef() and click event on the button named as this.focusInput.
this.focusInput = () => {
this.inputRef.current.focus();
};
By clicking on Focus input button, inputRef.current.focus() will move focus on Input.
Thanks for Reading!!!!!!!! | https://vibhas1892.medium.com/working-with-refs-in-react-c21f6fb15a25?source=---------2---------------------------- | CC-MAIN-2021-31 | refinedweb | 519 | 51.65 |
Handling Errors in React Components with Error Boundaries
|
A.
Along with React 16 came a feature that is a really good friend - Error Boundaries. Here's what the official document says about it..
So let's understand that in parts. Error Boundaries are React Components and they catch error anywhere in their child component tree. This means that they do not catch errors that occur within themselves and need to have children components to make any sense. The errors are logged, hence it is possible to get info about the error and exactly where this error occurred. The fun part is that you can display a fallback UI, so you can choose to display whatever you want instead of the component that crashed.
A component becomes an error boundary if it defines the
componentDidCatch(error, info) method. This lifecycle method was introduced in React 16 too.
If you this doesn't really make sense to you yet, I think a practical example will help. So let us create an error boundary component class.
How to create an Error Boundary
import React, {Component} from 'react'; import ReactDOM from 'react-dom'; class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = {hasError: false }; } componentDidCatch(error, info) { this.setState({hasError: true }); } render() { if (this.state.hasError) { return <h1>Oops!!! Something went wrong</h1>; } else { return this.props.children; } } }
From the code above, notice that an error boundary is defined like a regular React component with the difference being the
componentDidCatch method. So what's going on in the component?
hasError is set to an initial state of
false. If ever there is an error during rendering, in lifecycle methods, and in constructors in any of its children components or any subcomponent below it, the state of
hasErroris changed to
true. This state determines what will be rendered as seen in the render function. If there's an error, an error message is rendered instead.
Let's put this error boundary to use.
Using An Error Boundary
We are going to use part of a to-do app to explain this. Here's the full app on CodePen.
class ToDoApp extends React.Component { ... render() { return ( <div> <h2>ToDo</h2> <div> <Input /> //Error Boundary used here <ErrorBoundary> <ToDoList /> </ErrorBoundary> </div> </div> ); } }
In the code above, you can see that the error boundary is used like a normal component and is wrapped around the
TodoList component. If there's ever an error in this component or its children components, the error boundary component displays a fallback UI. Below is an image of the to-do app with no error.
Here's what happens when there is an error in the
<ToDoList /> component.
Note that the place where you place the error boundary in your code determines where the fallback UI will appear. Let us place the error boundary opening tag before the
<Input /> component.
class ToDoApp extends React.Component { ... render() { return ( <div> <h2>ToDo</h2> <div> //Error Boundary used here <ErrorBoundary> <Input /> <ToDoList /> </ErrorBoundary> </div> </div> ); } }
If there's an error, here's the display you get. Notice that unlike the previous image, the
input does not appear. Kindly ignore the uneven spacing. :)
Ideally, an error boundary component is declared once and then used throughout an application.
More On componentDidCatch()
Now, let's get back to the
componentDidCatch method. It works like the Javascript
catch{} block, but for components. You'll notice that
componentDidCatch has two parameters,
error and
info. What are they?
The first parameter is the actual error thrown. The second parameter is an object with a
componentStack property containing the component stack trace information. This is the path through your component tree from your application root all the way to the offending component. Let's modify our error boundary to make use of this parameters.
import React, {Component} from 'react'; import ReactDOM from 'react-dom'; class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = this.state = { hasError : false, error : null, info : null }; } componentDidCatch(error, info) { componentDidCatch(error, info) { this.setState({ hasError : true, error : error, info : info }); } } render() { if (this.state.hasError) { return ( <div> <h1>Oops!!! Something went wrong</h1> <p>The error: {this.state.error.toString()}</p> <p>Where it occured: {this.state.info.componentStack}</p> </div> ); } else { return this.props.children; } } }
What we did is modify our state to capture the error and info. Then display this error message and info in the fallback UI. When there's an error, here's what we get.
You can also log the error gotten to an error reporting service.
import React, {Component} from 'react'; import ReactDOM from 'react-dom'; class ErrorBoundary extends React.Component { ... componentDidCatch(error, info) { this.setState({hasError: true }); logErrorToService(error, info); } ... }
Conclusion
Now that you have understood what an error boundary is and how it can be used, I bet you think it's super cool. However, do not let the excitement make you want to wrap each component in an error boundary. This tweet says it all.
Error boundary work many levels deep, so there’s no need to “wrap at every level”. Just put your <ErrorBoundary> in a few strategic places.— Dan Abramov (@dan_abramov) July 27, 2017
Got any question or addition? Leave a comment.
Thank you for reading. :) | https://sarahchima.com/blog/error-boundaries-in-react/ | CC-MAIN-2019-13 | refinedweb | 873 | 59.9 |
error while running the applet - Java Beginners
);
++num;
}
}
}
}
i have problem while running the code , error...error while running the applet import java.applet.Applet;
import... is correct but u have problem in running the program. You follow the following steps
Problem in running first hibernate program.... - Hibernate
Problem in running first hibernate program.... Hi...I am using... the error " java.lang.NoClassDefFoundError: roseindia/tutorial/hibernate/FirstExample
Exception in thread "main" "
exception in thread main while running servlet
exception in thread main while running servlet I got exception in thread main no such method error while running servlet. I have added... lib also. Restart your server then run your code
Hibernate error in eclipse
Hibernate error in eclipse Hi...
while running my application i got... are trying to submit the null value. So, review your code again or send your full code........
I will try to short out your problem
Im getting this error while running JPA project
Im getting this error while running JPA project Exception in thread "main" javax.persistence.PersistenceException: [PersistenceUnit: examplePersistenceUnit] Unable to configure EntityManagerFactory code - Hibernate
hibernate code while generating the hibernate code i got the error like org.hibernate.MappingException
Hibernate error in eclipse
Hibernate error in eclipse Hi...
while running my application i got these type errors...can youme please?
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.StoreData.main(StoreData.java:11)
Caused
getting classnotfound exception while running login application
getting classnotfound exception while running login application hi,
I am getting
Error creating bean with name 'urlMapping' defined... to bean 'loginController' while setting
bean property 'urlMap' with while inserting millions of records - EJB
error while inserting millions of records Hello, I am using ejb cmp... out occurs same problem is occur when i am using hibernate but when i am using... problem
my code is
public void insertData(){
Context context
Hibernate delete a row error - Hibernate
Hibernate delete a row error Hello,
I been try with the hibernate delete example (... - Hibernate 3.0rc1
10:46:41,397 INFO Environment:469 - hibernate.properties
Downloading and Viewing html source of a page i.e. running on the server
illustrates you the procedure of viewing
complete html code of a page i.e. running... of the program which views the html source
code of your given page running on server...
Downloading and Viewing html source of a page i.e. running on the
server
Records are not inserting in to main table while running the mysql stored procedure.
Records are not inserting in to main table while running the mysql stored procedure. Hi,
Im migrating procedures from oracle to MySql.In... me with this issue.
My Code:
BEGIN
select concat('Inserting into SD
Java Compilation error. Hibernate code problem. Struts first example - Hibernate
Java Compilation error. Hibernate code problem. Struts first example Java Compilation error. Hibernate code problem. Struts first example
connection proxy error in hibernate
connection proxy error in hibernate while we get connection through hibernate we arise an error connection proxy error while we are using multiple connection's
Code error
)
read.close();
}
}
}
While using this it shows error as:
run...Code error package trail;
import... seconds)
Hw can i correct this code????????
Basically, the Exception code problem - Hibernate
: "
+ insurance. getInsuranceName());
}
in the above code,the hibernate...hibernate code problem String SQL_QUERY =" from Insurance...
thanks
shakti Hi friend,
Your code is :
String SQL_QUERY =" from
getting error while inserting values in database
getting error while inserting values in database AddUser.java...) {
out.println("An Error Had occurred while accessing the database...");
if (envContext == null)throw new Exception("Error: No
java runtime error: JDBC code - Java Beginners
and also set in the class path. the code is compilled and giving runtime error...java runtime error: JDBC code Hi i want to insert data into mysql... during handshake. Is there a server running on localhost:3306?
Please give running webservice
Error running webservice Hi,
I am getting following error:
05/10 12:45:46 ERROR org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error
Running problem with NoughtsAndCrossesGame in blank
Running problem with NoughtsAndCrossesGame in blank Hi i was having... main(String[] args) {
// TODO code application logic here... in the above loop but is shown separately here to make
connection proxy error in hibernate
connection proxy error in hibernate while we get connection through hibernate we arise an error connection proxy error while we are using multiple
error message is like below statements
SEVERE: Servlet.service() for servlet
Upload Code error on deploying
Upload Code error on deploying on deploying the above code as it is said it is giving error that " No getter method for property thefile of bean org.apache.struts.taglib.html.BEAN
"
Error 500--Internal Server Error
java compilation error - Hibernate
java compilation error hi
i am getting org.hibernate.exception.GenericJDBCException: Cannot open connection exception when runnig the code why this exception is coming
hibernate...............
hibernate...............
Hibernate is free open source software it can... Hibernate 3.0. You can download the Hibernate and install it yourself. But I have
Java error reached end of file while parsing
Java error reached end of file while parsing... to describe you a code that help you in
understanding java error reached end of file while parsing ,In this code
we want to display Time in hour, minute
Running First Hibernate 3.0 Example
Running First Hibernate 3.0 Example
Hibernate is free open source software it can... of database.
After running the code example you may check your MySQL database
Snippet Code Error
Snippet Code Error The following is a snippet of code from a Java application which uses Connector/J to query a MySQL database. Identify possible...= 0");
rs= s.getResultSet();
while (rs.next())
{
Reservation v
hibernate - Hibernate
hibernate Hai,This is jagadhish
I have a problem while developing insert application of Hibernate.The application is compiled,while running....
For read more information: and running error - RMI
Java Compilation and running error The following set of programs...);
}
catch(Exception e)
{
System.out.println("Error: " + e...");
}
catch(Exception e)
{
System.out.println("Error:" + e);
}
try
Getting an error :(
Getting an error :( I implemented the same code as above..
But getting this error in console...
Console
Oct 5, 2012 10:18:14 AM... start
INFO: Jk running ID=0 time=0/15 config=null
Oct 5, 2012 10:18:16 AM
J2EE Tutorial - Running RMI Example
above.
We used the -iiop flag while invoking rmic ...
J2EE Tutorial - Running RMI Example
...?
1) We require jndi package for running this
program.
JFREE error again
. but then also its giving me error
i am able to compile the code but now when i am running the code i am getting expection that:
Exception in thread "main...JFREE error again hi.........
As i had asked u the jfree error i
Hibernate - Hibernate
Hibernate Hai this is jagadhish, while executing a program in Hibernate in Tomcat i got an error like this
HTTP Status 500... Exception report
description The server encountered an internal
java runtime error - JDBC
java runtime error when i am running my jdbc program using thin driver this error is coming at runtime:
Exception in thread "main..., give me the suggesion yo solve this problem This kind of error due
Trouble in running Dos Command from Java Servlet
Trouble in running Dos Command from Java Servlet Hello All,
I have...:\FileListing";
Runtime.getRuntime().exec("cmd /c dir");
I gets error as:
java.io.IOException: Cannot run program "C:\Program": CreateProcess error=2, The system cannnot.... working with the Hibernate 4.3.1 and it is giving following error message:
Access
MAin error
MAin error Error while running hello program in another dir rather in bin.
path is already set.
java -version jdk1.6.0_24
no error while compilation but @ d tym of runnin error in main class is generated
Exception in thread
Script error - JSP-Servlet
of 5 seconds. For this i implement a javascript function named change. While running this it shows an error as "STACK OVERFLOW".
Correct the code . The code... then send me jsp code.
Thanks
Dll issue while launching the application
Dll issue while launching the application I am using one dll in my... message(e.g msi has not installed , code for this i have implemented in the main... is if the user has not installed the msi , then while launching the application Mapping
Running & Testing on WAMP server
;
In the above code <?= ?> is an alternate of echo language construct, to enable...Running & Testing on WAMP server
In this section we will learn how... red, it means no service is currently running, click on it and a popup menu
Hibernate code
Hibernate code programm 4 hibernate Hi,
Read hibernate tutorial at
Thanks
please read at the the link
java code using while loop
java code using while loop
Hibernate Code - Hibernate
Hibernate Code
How to Invoke Stored Procedure in Hibernate????????
Plz provide details code
Hibernate code problem - Hibernate
Hibernate code problem how to write hibernate Left outer join program
please fix the error
='"+pid+"'");
15: int count=0;
16: while(rs.next())
17: {
///////////@@@@the above mentioneed is error and code is as follows... to compile class for JSP:
An error occurred at line: 14 in the jsp file
error
error while iam compiling iam getting expected error
PHP Do While Loop
the code within. We generally use Do-While loop when the iteration must run at least once despite of the validity of the variable. In Do-While loop we need...Do-While Loop Function PHP:
PHP Do-While loop method is another type of loop
Session #1 - Hibernate introduction and creating CRUD application
application.
Example code of insert, update, search and delete data using Hibernate... is the video tutorial of Hibernate:
Above video tutorial teaches you Hibernate ORM...:
Here is the SQL code for creating table for running this application:
DROP TABLE
Applet Error - Applet
in the above code...as it is a very large code which isn't necessary for finding...,
Please post your code.
Thanks [code]
public class circuit extends...) {
....Some Painting Lines Code Here....
if (rect1Clicked
Applet to database error - Applet
which i didn't included in the above code...as it is a very large code which isn't... is a part of that...
The code works fine in the local system..
but when its...);
repaint();
}
public void paint(Graphics g) {
....Some Painting Lines Code Here
hibernate code - Hibernate
hibernate code How to store a image in mysql or oracle db using struts &hibernate
While and do-while
While and do-while
... classes can lead to more readable and maintainable code.
More readable, maintainable code-Nesting small classes within
top-level classes places the code
; Tutorial Section
Introduction
to Hibernate 3.0 |
Hibernate Architecture |
First
Hibernate Application |
Running
the Example in Eclipse |
Understanding Hibernate O/R Mapping |
Understanding Hibernate <generator> element
HIBERNATE CODE - Hibernate
HIBERNATE CODE Dear sir,
I am working with MyEclipse IDE.I want to connect with MYSQL using Hibernate.
What is the Driver Template and URL of MYSQL toconnect using Hibernate
error
error I am running a program insert into statement in sql using.../ServletUserEnquiryForm.shtml
getting an error given below
SQLException caught: [Microsoft][ODBC SQL Server Driver]COUNT field incorrect or syntax error
please suggest
Hibernate code - Hibernate
Hibernate code can you show the insert example of Hibernate other than session.save(obj); Hi
I am sending a link where u can find lots of example related to hibernate...
java error - Java Beginners
,but there are some errors while running the code are
1.class SortFileData is public... be dereferenced
If Programme saved in SortFileData also shows some error Please rectify... Friend,
Save java file with 'SortFileData.java' and try the following code
Hibernate code - Hibernate
Hibernate code how to write hql query for retriveing data from multiple tables
The while and do
While and do-while
Lets try to find out what a while statement
does. In a simpler language, the while statement continually executes a block of statements while
Error in simple session bean ..................
getting these errors while i am runnign above client...Error in simple session bean .................. Hi friends,
i am... one plz help me to solve this issue.
here is the client code which i have
Advertisements
If you enjoyed this post then why not add us on Google+? Add us to your Circles | http://www.roseindia.net/tutorialhelp/comment/32610 | CC-MAIN-2015-22 | refinedweb | 2,061 | 57.87 |
IntroductionI.Language is realignFor some developers the programming language that they are using is like realign for them. If you talk anything bad about the language then you can get in to good hot heated argument with the developer. You can even see this in your day-to-day life at work, user groups and bulletin boards, some times articles on this topic. Before .NET framework was introduced, every language was using its compiler to produce native code (processor specific). Some of the compilers where optimized for a specific operating system of processor. In this scenario each language capabilities and compiler capabilities where really mattered. For example, when we develop a COM component in VB 6, it had the Apartment Model Threading (STA) and STA had its won drawbacks. When you want a lighting fast COM component then, people where relaying on ATL and VC++ to do it. And more over, when we develop COM components in VC++ we had more control over the component and we can remove the unwanted COM glue methods from our COM components. But this is not in the case of VB 6. VB 6 helped us to create COM components at the speed of light and it took care of all the COM glue methods for us.The .NET and JIT CompilersWell, it is an old story after .NET Framework has been introduced. In .NET framework when we compile a Portable executable (PE) or a component, the code is compiled in to Managed Code/Intermediate Language (MSIL or IL). This MSIL uses CPU-independent set of instructions. The .NET Runtime ships Just-In-Time (JIT or JITter) compiler, which will convert the MSIL code in to the native code (CPU Specific code). So whatever code we write will be complied in to MSIL format and after that our code is history. The .NET runtime/Common Language Runtime (CLR) ships three different classes of JITters. The Main JIT compiler converts the MSIL code it to native code with out any optimizations. The JIT compiler takes the MSIL code and optimizes it. So this compiler requires lot of resources like, time to compile, larger memory footprint, etc. The PreJIT is based on the Main JIT and it works like the traditional compilers rather than Just-In-Time compilers. This compiler is used at the time of installation.A Simple Test Well we know what will happen to our code, when it is passed on to VB.NET compiler or C# compiler. So all it matters is MSIL format that what weve to worry about. Because once our code has been converted in to MSIL format, from MSIL format all the code that we write will be converted to native code in the same way never the less if it is a VB.NET source or C# source. Microsoft climes that if we choose VB.NET or C# the code should be same. To test it Im going to write two .NET components (DLLs) in VB.NET and C# which does the same things. Here how the code looks. VB.NET codeImports System Namespace Hello Public Class World Public Function SayHelloWorld() As String Return "Hello, World! From VB.NET Component!" End Function End Class End NamespaceC# Codeusing System;namespace Hello{public class World{public string SayHelloWorld(){return "Hello, World! From C# Component!";}}} In both VB.NET and C# code, weve a namespace called Hello and it includes a public class called World. The World class exposes a public method called SayHelloWorld. Simple is in it? Lets compile the above code.VBC /t:library /out:VBComp.dll /r:System.dll VBComp.Vb CSC /t:library /out:CSharpComp.dll /r:System.dll CSharpComp.cs Weve asked the VB.NET and C# compilers to produce a DLL file (library) by including the System.DLL file for the reference.IL DisassemblerThe .NET framework ships a tool called IL Disassembler, which can open a managed component or a PE (Portable Executable) and show the MSIL Code and Meta data associated with it. Lets fire the IL Disassembler (Go to Start > Programs > Microsoft .NET Framework SDK > Tools > IL Disassembler) and open the both VB.NET and C# version of the DLL. The following figures show the IL code generated by the VB.NET and C# compilers. VB.NET IL Code C# IL Code If you can look at the code closely both look the same way for the method SayHelloWorld. But VB code one more overhead called _VBProject. I was thinking of doing a performance test against the both components. But ASP.NET and .NET Framework is still and its first beta and this version is kind of proof of concept and just for learning. So, it didnt make any sense for me doing that. More over Beta 1 license agreement prevents doing such tests.SummaryAs for as Im concern the language of choice is up to you. If youve a VB background and you feel pretty good about VB then dive in to VB.NET. If you come from a C or C++ or Java or JavaScript background and you feel pretty good about C like syntax then dive in to C#. All it maters is the language that you are familiar with and how productive you are in that language. Until next time, Happy Programming!
C# or VB.NET - World War III
IL "The Language of CLR" - A Platform for Cross-Language | http://www.c-sharpcorner.com/UploadFile/ssivkumar/CSharporVB.NET-WorldWarIII12222005073658AM/CSharporVB.NET-WorldWarIII.aspx | crawl-003 | refinedweb | 901 | 75.3 |
TheBH1750FVI device is a digital light intensity..
Configure I2C Interface
In order to use this module you must enable the I2C interface on the Raspberry Pi as it is not enabled by default. This is a fairly easy process and is described in my Enabling The I2C Interface On The Raspberry Pi tutorial.
Connecting Hardware Code
Here is a simple Python script to read the light level from the module :
#!/usr/bin/python import smbus import time # Define some constants from the datasheet DEVICE = 0x23 # Default device I2C address POWER_DOWN = 0x00 # No active state POWER_ON = 0x01 # Power on RESET = 0x07 # Reset data register value # Start measurement at 4lx resolution. Time typically 16ms. CONTINUOUS_LOW_RES_MODE = 0x13 # Start measurement at 1lx resolution. Time typically 120ms CONTINUOUS_HIGH_RES_MODE_1 = 0x10 # Start measurement at 0.5lx resolution. Time typically 120ms CONTINUOUS_HIGH_RES_MODE_2 = 0x11 # Start measurement at 1lx resolution. Time typically 120ms # Device is automatically set to Power Down after measurement. ONE_TIME_HIGH_RES_MODE_1 = 0x20 # Start measurement at 0.5lx resolution. Time typically 120ms # Device is automatically set to Power Down after measurement. ONE_TIME_HIGH_RES_MODE_2 = 0x21 # Start measurement at 1lx resolution. Time typically 120ms # Device is automatically set to Power Down after measurement. ONE_TIME_LOW_RES_MODE = 0x23 #bus = smbus.SMBus(0) # Rev 1 Pi uses 0 bus = smbus.SMBus(1) # Rev 2 Pi uses 1 def convertToNumber(data): # Simple function to convert 2 bytes of data # into a decimal number return ((data[1] + (256 * data[0])) / 1.2) def readLight(addr=DEVICE): data = bus.read_i2c_block_data(addr,ONE_TIME_HIGH_RES_MODE_1) return convertToNumber(data) def main(): while True: print "Light Level : " + str(readLight()) + " lx" time.sleep(0.5) if __name__=="__main__": main()
If you want download this script directly to your Pi you can use the following command :
wget
or use this link in a browser.
In order to run it you can use :
sudo python bh1750.py
The output should look something like :
The while loop keeps taking readings every 200ms until you press CTRL-C.. If the ADDR pin is tied to 3.3V the address is 0x5.
The module is available from eBay, Amazon and many other online electronics shops.. | http://www.raspberrypi-spy.co.uk/2015/03/bh1750fvi-i2c-digital-light-intensity-sensor/ | CC-MAIN-2017-34 | refinedweb | 345 | 50.02 |
Rev 47 |
Details |
Compare with Previous |
Last modification |
View Log
| RSS feed
/* Copyright (C) 1991, 1992, 1996, 1997, 1999 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Written by Douglas C. Schmidt (schmidt@ics.uci you consider tuning this algorithm, you should consult first:
Engineering a sort function; Jon Bentley and M. Douglas McIlroy;
Software - Practice and Experience; Vol. 23 (11), 1249-1265, 1993. */
//#include <alloca.h> //SHARK
#include <limits.h>
#include <stdlib.h>
#include <string.h>
/* Byte-wise swap two items of size SIZE. */
#define SWAP(a, b, size) \
do \
{ \
register size_t __size = (size); \
register char *__a = (a), *__b = (b); \
do \
{ \
char __tmp = *__a; \
*__a++ = *__b; \
*__b++ = __tmp; \
} while (--__size > 0); \
} while (0)
/* Discontinue quicksort algorithm when partition gets below this size.
This particular magic number was chosen to work best on a Sun 4/260. */
#define MAX_THRESH 4
/* Stack node declarations used to store unfulfilled partition obligations. */
typedef struct
{)
/* Order size using quicksort. This implementation incorporates
four optimizations discussed in Sedgewick:
1. Non-recursive, using an explicit stack of pointer that store the
next array partition to sort. To save time, this maximum amount
of space required to store an array of SIZE_MAX is allocated on the
stack. Assuming a 32-bit (64 bit) integer for size_t, this needs
only 32 * sizeof(stack_node) == 256 bytes (for 64 bit: 1024 bytes).
Pretty cheap, actually.
2. Chose the pivot element using a median-of-three decision tree.
This reduces the probability of selecting a bad pivot value and
eliminates certain extraneous comparisons.
3. Only quicksorts TOTAL_ELEMS / MAX_THRESH partitions, leaving
insertion sort to order the MAX_THRESH items within each partition.
This is a big win, since insertion sort is faster for small, mostly
sorted array segments.
4. The larger of the two sub-partitions is always pushed onto the
stack first, with the algorithm then concentrating on the
smaller partition. This *guarantees* no more than log (total_elems)
stack size is needed (actually O(1) in this case)! */
void
.1 ✓ XHTML & CSS | http://shark.sssup.it/svn/blame.php?repname=shark&path=%2Fshark%2Ftrunk%2Flibc%2Fstdlib%2Fqsort.c&rev=379&peg=1613 | CC-MAIN-2022-05 | refinedweb | 335 | 59.09 |
I.
This seems like a very noob question but I can't find an answer anywhere!
I'm very new to developing packages for Homebrew but when I edit my formula and come to update my package I get the following error
Error: SHA256 mismatch
My question is, how do I generate the expected SHA256 value?
In AIX 7.1 I'm generating SSH keypairs in the mkuser.sys.custom file when users are created. I want to use SHA1 to verify that the private key is valid after it's uploaded to a staging server for delivery to the user's PC. The problem I'm having is that the signature generated by mkuser.sys.custom is not the same as the signature generated by an either an external script running the same command, or by the Powershell script on the Windows end that's trying to validate it.Here is a snippet from mkuser.sys.custom:
#mkuser (home_directory, userid)#generate the ssh keysssh-keygen -f $1/.ssh_$2/id_rsa -t rsa -N '' &> /dev/null...#rename the private key so it can be identified by the Powershell scriptmv $1/.ssh_$2/id_rsa $1/.ssh_$2/$2_rsa...#generate the SHA1 and store it for uploadingshasum $1/.ssh_$2/$2_rsa > $1/.ssh_$2/$2_sha
Sample output looks like "17dfe8f6ed59a191f552ecca1a3232cb9436fe23".
If I copy the shasum line to a script, and run it with the same home_directory and userid input I would get the following signature: "C0A35786719399CF707E8AC9611A10B6C5474E31". This is the same result that I get in Powershell.
I've tried the same thing with the built-in csum -h SHA1, and get identical results.
Why are my signatures coming out different?
I am working on following the SHA-2 cryptographically functions as stated in.
I am examining the lines that say:
I do not understand the last two lines. If my string is short can its length after adding K '0' bits be 512. How should I implement this in Java code?
Why in this soulution which I found there is no Loop to use buffor few times?
using System.IO;using System.Security.Cryptography;private static string GetChecksum(string file){ using (FileStream stream = File.OpenRead(file)) { SHA256Managed sha = new SHA256Managed(); byte[] checksum = sha.ComputeHash(stream); return BitConverter.ToString(checksum).Replace("-", String.Empty); }}
I'm trying to generate SHA checksum for +2GB file. How it should be?. | http://convertstring.com/no/Hash/SHA384 | CC-MAIN-2017-47 | refinedweb | 394 | 67.55 |
[Please note that comments and discussion for published tutorials are at ]
In the previous tutorial we looked at binding data to fields on a Windows Phone 7 page. In this tutorial we take the next step and create a list on a first page and then display the details on a second page. This turns out to be shockingly easy to do, but along the way we’ll uncover some other useful controls and a few subtle features.
To get started open Visual Studio 2010 and click on New Project. In the New Project dialog, click on the Silverlight for Windows Phone template and then on Windows Phone List Application. I called my example i2WPCustomerList
Before you do anything else, run the application. You’ll find that a list appears. You can move the list up and down with the mouse (try “flicking” up and down as well!). When you click on an entry you are taken to a details page for that entry.
Before we modify this application to use our customers, let’s take a look at how it is accomplishing all of this.
Dissecting The List Application
Stop debugging (don’t shut the emulator) and open MainPage.xaml. Let’s dissect this line by line, area by area.
The PhoneApplicationPage Element
At the top, within the opening PhoneApplicationPage element, are a number of name space declarations
xmlns="" xmlns:x="" xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" xmlns:d="" xmlns:mc=""
The effect of each of these is to name an alias to a namespace. That is, for example, the second line creates the alias “x” for the namespace found in. Having declared this, you can then use that alias to find the element Name defined in that name space by writing
x:Name
which tells the compiler where Name is defined.
Immediately after the name space declarations, the design time DataContext is defined, pointing to the SampleData folder in which resides the file MainViewModelSampleData.xaml. You can see that file in the Solution Explorer window under the folder Sample Data, and you can see it on your disk as well by navigating to the directory (folder) that holds the new application, then to the Sample Data directory, in which is that very file.
The DataContext assignment is followed by three resource assignments. We’ll take a long look at Static Resources in an upcoming tutorial, but the upshot of these three lines is to define the FontFamily, FontSize and Foreground color by using three predefined values. (This makes it very easy for your application to look and feel like a Windows Phone 7 application.)
The next statement tells the application which orientations (vertical, horizontal or both) you intend to support in this application.
The final two lines of this opening element set the width and height of the design surface and indicate that this application will be visible in the System Tray.
The Outer and Inner Grids
Within the PhoneApplicationPage is a grid, LayoutRoot which has two rows. The first row holds a StackPanel with the ApplicationTitle and ListTitle TextBlocks.
The second row of the grid holds an innerGrid named ContentPanel, which in turn holds a ListBox.
The ListBox
The Listbox has two interesting features. First, its ItemSource is bound to a property named Items. The ItemsSource is an ObservableCollection that is used to populate the ListBox. An ObservableCollection is a list that implements INotifyCollectionChanged, and so, as items are added or removed or modified, the UI is notified through that interface.
<ListBox x:
At the very end of the ListBox element is the assignment of a method name to the SelectionChanged event. There are two ways to hook up events for elements defined in the Xaml. One is to define the event handler in the Xaml itself (as shown here) and the other is to define the event handler in the code-behind file (as shown previously).
The ItemTemplate
The second interesting aspect of the ListBox is that how it displays its data is defined in the ListBox.ItemTemplate, which in turn holds a DataTemplate, which, in its turn, holds the elements that will be repeated for each item in the list,
<ListBox.ItemTemplate> <DataTemplate> </DataTemplate> </ListBox.ItemTemplate>
In this case the DataTemplate holds a StackPanel whose orientation is Horizontal. The first item in the StackPanel is an image, the second item in the StackPanel is an inner StackPanel, which in turn holds two TextBlocks. Since the orientation for the inner StackPanel is not specified, the default (vertical) is used. You can see the effect in the running application (the image is the arrow head in a circle), where this specification repeats for each item (I’ve added a line between the first two items).
When The Program Starts
Out of the box, when the program starts up, the code in App.xaml.cs will run. We won’t delve deep into this file for now, but the net effect is that the code in the constructor of MainView.xaml.cs will be invoked, which will initialize the visible components and when the page is displayed the method OnNavigatedTo will be invoked,
protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); if (DataContext == null) DataContext = App.ViewModel; }
Note that the DataContext is set to the ViewModel static value in the App class, which itself is initialized to MainView. This delays the creation of the view until it is needed. The MainView itself is composed of the databound list we looked at above, and so the sample data is displayed.
Handling the SelectionChangedEvent
When the user clicks on an element in the list, the SelectionChanged Event is fired, and the SelectionChangedEvent handler method in MainPage.xaml.cs is called,
private void MainListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (MainListBox.SelectedIndex == -1) return; NavigationService.Navigate(new Uri("/DetailsPage.xaml?selectedItem=" + MainListBox.SelectedIndex, UriKind.Relative)); MainListBox.SelectedIndex = -1; }
The first line checks for an invalid index, and the third line resets the index (using –1 and not 0 as 0 is the offset to the first item in the list). The middle line is where the action is; here we call the NavigationService, which is the approach of choice for navigating from one page to another. The static Navigate method takes a URI which we create on the fly based on the user’s choice.
Control of the application then switches to the DetailsPage and the constructor and OnNavigatedTo methods are invoked there,
public DetailsPage() { InitializeComponent(); } / When page is navigated to, set data context to selected item in list protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); string selectedIndex; if (NavigationContext.QueryString.TryGetValue( "selectedItem", out selectedIndex)) { int index = int.Parse(selectedIndex); DataContext = App.ViewModel.Items[index]; } }
Taking this apart, the Navigation system provides a NavigationContext, which provides a query string. We call TryGetValue, passing which value we want (selectedItem) and a string for the value. We then turn that string into an integer, and ask the ViewModel Items property for the object at that index, and assign that as the DataContext.
Modifying the Application For Customers
With the out of the box list application reasonably understood, you can see that adding our Customer data will not be terribly difficult. Start by adding a folder named Model and into that folder place the customer.cs file from the previous tutorial (reproduced here in full for your convenience),
public class CustomerCollection { private readonly List<Customer> _customers = new List<Customer>(); public List<Customer> Customers { get { return _customers; } } public CustomerCollection() { GenerateCustomers(500); } (var i = 0; i < howMany; i++) { var first = firsts[random.Next(0, firsts.Count)]; var last = lasts[random.Next(0, lasts.Count)]; var streetNumberInt = random.Next(101, 999); var streetNumber = streetNumberInt.ToString(); var zipCode = random.Next(10000, 99999).ToString(); var homePhone = random.Next(200, 999) + "-555-" + random.Next(2000, 9099); var workPhone = random.Next(200, 999) + "-555-" + random.Next(2000, 9099); var fax = random.Next(200, 999) + "-555-" + random.Next(2000, 9099); var homeEmail = first + "@" + isp[random.Next(0, isp.Count)] + ".com"; var workEmail = last + "@" + isp[random.Next(0, isp.Count)] + ".com"; var isMale = (random.Next(1,3)) % 2 == 0 ? true : false; var creditRating = (short)random.Next(100, 800); var firstContact = new DateTime(2010, 1, 1); var; } }
Setting the Bindings
With the customer class in place, we’re in a position to decide which fields to bind to in the list. The first line will display the full name, and so will need a pair of TextBlocks in a StackPanel and careful handling of the margins to manage the space between them,
<ListBox x: <ListBox.ItemTemplate> <DataTemplate> <StackPanel x: <Image x: <StackPanel> > <TextBlock x: </StackPanel> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
The missing piece is to set the DataContext which we do in MainViewModel.cs. We can simplify that file tremendously,
using System; using System.ComponentModel; using System.Collections.ObjectModel; namespace WindowsPhoneListApplication1.ViewModels { public class MainViewModel : INotifyPropertyChanged { public MainViewModel() { var custColl = new Model.CustomerCollection(); Items = custColl.Customers; } public ObservableCollection<Model.Customer> Items { get; private set; } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (null != handler) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } }
Notice the automatic property Items. Automatic properties must have both a getter and a setter. In this case, since we want to use an automatic property, but we want Items to be read
only, we make the setter private.
For this to compile, you’ll need to comment out, or remove, the files under the folder SampleData (or the entire folder!)
Set the TitlePanel TextBlock values in MainPage.xaml,
<StackPanel x: <TextBlock x: <TextBlock x: </StackPanel>
and run the application.
Notice that the fields from the Customer class are appropriately displayed, and that you can flick the list up and down as you could with the sample data. This time, however, the data is drawn from the observable collection of Customers, which we could, of course, have obtained from a Web Service, a Database or any other data source.
When the user clicks on a customer, we want to show the detail. At this point that is as simple as setting the right bindings in Details.xaml.
Notice, first, that on this page you bind the ListTitle to the customer name. This take a small adjustment in the title block,
<StackPanel x: <TextBlock x: > </StackPanel>
The details can be as much of the customer record as you choose to display. We have a precedent for what to display in a previous tutorial, so let’s use that. Here is the complete ContentPanel,
<Grid x: <Grid x: }" /> </Grid> </Grid>
What Have You Learned Dorothy?
…if I ever go looking for my heart’s desire again, I won’t look any further than my own backyard; because if it isn’t there, I never really lost it to begin with…if I ever go looking for my heart’s desire again, I won’t look any further than my own backyard; because if it isn’t there, I never really lost it to begin with
By using the Windows Phone List Application, we can significantly cut down on the work while increasing the visual compatibility of List/Detail projects.
Now, that said, if your heart’s desire is in your own backyard then you haven’t lost it to begin with either, no?
MindMap
Here is a mind-map of some of the concpets covered in this tutorial (click inside to move around in the map or click here for the full map
—-
Post Script: True story, a number of years ago I received an email with this quote: “I am sir your translator for book to Korean. I have question, what means sir, “I’ve a feeling we’re not in Kansas anymore.”
Previous Tutorial | Next Tutorial
Pingback: iPhone Developer? How to move to Windows Phone 7! | I Love Windows Phone!
Pingback: DotNetShoutout
I’d suggest adding to the the “The ItemTemplate” section, just to point out to (completely new SL devs) that you can really template the entire row however you like. On the iPhone you are, in practice, limited to the ContentView and a set of built in constraints:
@Michael L Perry
Yes, thanks, you are absolutely correct
ObservableCollection implements INotifyCollectionChanged, not INotifyPropertyChanged. | http://jesseliberty.com/2010/09/13/iphone-to-windows-phone-7-lists-and-details/ | CC-MAIN-2021-10 | refinedweb | 2,040 | 54.42 |
Iterables, functions, and generators in Python
To learn about the
yield keyword, there are a variety of other terms and concepts that you must be comfortable with first. Before we dive into all of that, let’s keep the end in mind and talk through why
yield is beneficial.
Using
yield will improve the memory efficiency — and subsequently, the speed/performance — when looping over a large iterable. These benefits will be less pronounced for small data sets; however, as data grows so too does the benefit of using
yield.
Now, onto the explanation. In short,
yield is a replacement for the return keyword that produces a generator from a function, which is used as a one-time iterable. If you’re like me when I first learned this, you got lost along the way. So, to unpack this concept, let’s start from the ground and work our way up.
What Is an Iterable?
A bit tongue-in-cheek, but an iterable is a data type that can be iterated over. To clarify, it’s a data type where the individual elements are intelligible data — individual characters of a string, terms in a dictionary, items in a list or tuple, etc. Functionally, data is an iterable if it works in the following code snippet:
for x in my_iterable: pass
What’s important to note is that while individual elements are accessed one at a time, the entire iterable is still stored in memory. That means that if you’re iterating over a range from 0 to 5,000,000,000, then each of those values is taking up resources. Even though as the programmer you efficiently write a set of repeated commands inside the loop, the application still needs to store that which is being iterated over.
What Is a Function?
A function is a set of commands that form a definition that’s not executed except when invoked or called. What this means is that even if your function’s processes were to take up large amounts of memory and resources, that will only happen when the function is called. The definition of the function does nothing on its own.
It’s helpful to think of a function as a black-box that takes inputs (arguments) and produces an expected output (return value). Thus, a function very much takes on the shape of a formula or an equation, except that it goes beyond arithmetic.
I described a function as a black-box because what happens inside the function really shouldn’t matter to the user—you only need to know what’s necessary to supply to the function, and what to expect as an output. With the exception of the arguments, nothing else is accessible by the function. Similarly, with the exception of the return value, nothing inside the function is accessible outside of it.
What Is a Generator?
A generator is a type of iterable that’s meant for one-time use. The design intention is that an element within the iterable is no longer needed once it has been consumed. Therefore, rather than creating and storing the entirety of an iterable, a generator produces each element one at a time. This saves resources and improves performance. To see this in action, let’s compare a list to a generator:
my_list = [n for n in range(10)] print(my_list) # [0,1,2,3,4,5,6,7,8,9]my_generator = (n for n in range(10)) print(my_generator) # <generator object <genexpr> at 0x10daaa480>
First, the syntactic difference is that the list comprehension is done with square brackets
[] while the generator comprehension is performed with parenthesis
(). Notice the list is all stored and readily printable while a generator points to a generator object.
They seem different, but they behave similarly when working within a loop.
for element in my_list: print(element) """ 0 1 2 3 ... etc. """for element in my_generator: print(element) """ 0 1 2 3 ... etc. """
What Does the “Yield” Keyword Do?
Finally, the explanation for our initial question. The
yield keyword is going to replace
return in a function definition to create a generator. This can then be used as a normal iterable, reaping the benefits of both generators and functions.
def createGenerator(): for i in range(100): yield imy_generator = createGenerator() print(my_generator) # <generator object createGenerator at 0x102dd2480>for i in my_generator: print(i) # prints 0-99
So, how does this work? When the returned generator is first used—not in the assignment but the
for loop—the function definition will execute until it reaches the
yield statement. There, it will pause (see why it’s called yield) until used again. Then, it will pick up where it left off. Upon the final iteration of the generator, any code after the
yield command will execute.
Let’s add some print code to see the sequence of events:
def createGenerator(): print("Beginning of generator") for i in range(3): yield i print("After yield")print("Before assignment") my_generator = createGenerator() print("After assignment")for i in my_generator: print(i) # prints 0-99""" Before assignment After assignment Beginning of generator 0 1 2 After yield """
In summary, the
yield keyword modifies a function’s behavior to produce a generator that’s paused at each
yield command during iteration. The function isn’t executed except upon iteration, which leads to improved resource management, and subsequently, a better overall performance. Use generators (and yielded functions) for creating large data sets meant for single-use iteration. | https://learningactors.com/what-does-the-yield-keyword-do/ | CC-MAIN-2020-10 | refinedweb | 913 | 52.29 |
Many times we want to implement pre-processing logic before a request hits the IIS resources. For instance you would like to apply security mechanism, URL rewriting, filter something in the request, etc. ASP.NET has provided two types of interception HttpModule and HttpHandler. This article walks through it.
HttpModule
HttpHandler
For the last few days, I have been writing and recording videos in design patterns, UML, FPA, Enterprise blocks and lot more. You can watch the videos here.
You can download my 400 .NET FAQ EBook from here.
Many times we need to inject some kind of logic before the page is requested. Some of the commonly used pre-processing logics are stat counters, URL rewriting, authentication / authorization and many more. We can do this in the code behind but then that can lead to lot of complication and tangled code. The code behind will not solve the purpose because in some implementations like authorization, we want the logic to execute before it reaches the resource. ASP.NET provides two ways of injecting logic in the request pipeline HttpHandlers and HttpModules.
HttpHandlers
HttpModules
HttpHandler help us to inject pre-processing logic based on the extension of the file name requested. So when a page is requested, HttpHandler executes on the base of extension file names and on the base of verbs. For instance, you can visualize from the figure below how we have different handlers mapped to file extension. We can also map one handler to multiple file extensions. For instance, when any client requests for file with extension
“Modules are called before and after the handler executes. Modules enable developers to intercept, participate in, or modify each individual request. Handlers are used to process individual endpoint requests. Handlers enable the ASP.NET Framework to process individual HTTP URLs or groups of URL extensions within an application. Unlike modules, only one handler is used to process a request”.
using System;
using System.Web;
using System.IO;
namespace MyPipeLine
{
public class clsMyHandler : IHttpHandler
{
public void ProcessRequest(System.Web.HttpContext context)
{
context.Response.Write("The page request is " + context.Request.RawUrl.ToString());
StreamWriter sw = new StreamWriter(@"C:\requestLog.txt",true);
sw.WriteLine("Page requested at " + DateTime.Now.ToString() +
context.Request.RawUrl); sw.Close();
}
public bool IsReusable
{
get
{
return true;
}
}
}
In step 2, we need to make an entry of HttpHandlers tag. In the tag, we need to specify which kind of extension requested will invoke our class.
<system.web>
<httpHandlers>
<add verb="*" path="*.Shiv,*.Koirala" type="MyPipeLine.clsMyHandler, MyPipeLine"/>
</httpHandlers>
</system.web>
Once done, request for page name with extension
public class clsMyModule : IHttpModule
{
public clsMyModule()
{}
public void Init(HttpApplication objApplication)
{
// Register event handler of the pipe line
objApplication.BeginRequest += new EventHandler(this.context_BeginRequest);
objApplication.EndRequest += new EventHandler(this.context_EndRequest);
}
public void Dispose()
{
}
public void context_EndRequest(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(@"C:\requestLog.txt",true);
sw.WriteLine("End Request called at " + DateTime.Now.ToString()); sw.Close();
}
public void context_BeginRequest(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(@"C:\requestLog.txt",true);
sw.WriteLine("Begin request called at " + DateTime.Now.ToString()); sw.Close();
}
}. | https://www.codeproject.com/Articles/30907/The-Two-Interceptors-HttpModule-and-HttpHandlers?fid=1530508&df=90&mpp=10&sort=Position&spc=None&select=4364148&tid=4364148 | CC-MAIN-2017-26 | refinedweb | 514 | 51.85 |
I'm not sure if I entirely understand, but doesn't my current method already do that in a different way?
I'm not sure if I entirely understand, but doesn't my current method already do that in a different way?
1. Menu choice is from the user input at this line:
menuChoice = Integer.parseInt(input.readLine());
2. I am absolutely certain that there are no spaces between the operator and the operand in...
I'd been trying to keep it to what I thought was relevant, but I'll just post it in its entirety if you feel it will help.
import java.io.*;
import java.util.*;
class GuildDKP {
final...
I haven't noted any exceptions as having been thrown at any point during the program's running. I'm completely lost on what the problem is here.
[SOLVED]
Program description: This part of the program is supposed to go through all the files in the directory, add all values in the file from the second line onwards, then recreate the text...
I'm working on a program that will do a number of things, the exact function being performed is selected by the user in a menu. (They type in the number corresponding to their choice, a switch... | http://www.javaprogrammingforums.com/search.php?s=23dd6102fc3fdca83799411cca4f7937&searchid=1583524 | CC-MAIN-2015-22 | refinedweb | 211 | 70.33 |
Why would someone want to write yet another programming language? And why do it in C#?
It‘s often taken for granted that you need an advanced degree in Computer Science—or a lot of stubbornness—to write a compiler. In either case, you’d have quite a few sleepless nights and broken relationships as a result. This article shows you how to avoid all that.
Here are a few advantages of writing your own language::
- Unlike most other languages, it’s very easy to modify functionality because everything is in an easy-to-follow standard C# code with a clear interface for functions to be added. Any additional functions can be added to this language with just a few lines of code
- All of the keywords of this language (if, else, while, function, and so on) can be easily replaced by any non-English keywords (and they don’t have to be ASCII, contrary to the most other languages). Only configuration changes are needed for replacing the keywords
- This language can be used as both as a scripting language and as a shell program, like Bash on Unix or PowerShell on Windows (but you will make it more user-friendly than PowerShell).
- Even Python doesn’t have the prefix and postfix operators ++ and -- with the killer argument, "you don’t need them." With your own language, you can decide for yourself what you need. And I’ll show you how.
- Any custom parsing can be implemented on the fly. Having full control over parsing means less time searching for how to use an external package or a regex library.
- You won’t be using any regular expressions at all! I believe that this is the main showstopper for a few people who desperately need to parse an expression but are averse to the pain and humiliation induced by the regex rules.
This article is based on two articles that I published in MSDN Magazine (see references in the sidebar). In the first article, I described the Split-and-Merge algorithm to parse a mathematical expression, and in the second one, I described how you can write a scripting language based on that algorithm. I called that language CSCS (Customized Scripting in C#). For consistency, I’ll call the language that I’ll describe in this article CSCS as well.
The CSCS language, as described in my second MSDN article, was not yet very mature. In particular, there’s a section toward the end of the article mentioning some of the important features usually present in a scripting language that CSCS was still missing. In this CODE Magazine article, I’ll generalize the CSCS language and show how to implement most of these missing features and a few others as well.
The Split-and-Merge Algorithm to Parse a Language Statement
Here, I’ll generalize the Split-and-Merge algorithm to parse not only a mathematical expression but also any CSCS language statement. A separation character must separate all CSCS statements. I define it in the Constants.cs file as Constants.END_STATEMENT = ';' constant.
The Split-and-Merge algorithm consists of two steps. First, you split the string into the list of tokens. Each token consists of a number or a string and an action that can be applied to it.
For strings, the actions can only be a plus sign + (string concatenation) or Boolean comparisons, such as ==, <, >=, etc., giving a Boolean as a result. For numbers, there are a few other possible actions, such as -, *, /, ^, and %. The prefix and postfix operators ++ and -- and the assignment operators +=, -=,*=, etc., are treated as special actions for numbers. For strings, I implemented the += assignment operator only, because I couldn’t find a reason for other assignment operators for strings.
The separation criteria for tokens are an action, an expression in parentheses, or any special function, previously registered with the Parser. In case of an expression in parentheses or a function, you recursively apply the whole algorithm to the expression in parentheses or to the function with its arguments. At the end of the first step, you’ll have a list of cells, each consisting of an action and either a number or a string. This action is applied to the next cell. The last cell always has a null action. The null action has the lowest priority.
The second step consists of merging the elements of the list created in the first step. The merging of two cells consists of applying the action of the cell on the left to the numbers, or strings of the left and of the right cell. The merging of two cells can only be done if the priority of the action of the left cell is greater than or equal to the priority of the action of the cell on its right. Otherwise, you merge first the cell on the right with the cell on its right, and so on, recursively, until you reach the end of the list.
The priorities of the actions are shown in Listing 1.If they don’t make sense for your usage, you can easily change them.
Example of the Split-and-Merge Algorithm
Let’s see how to evaluate the following expression: x == "a" || x == "b".
First of all, x must be registered as a function with the Parser (all CSCS variables are registered and treated as functions). Therefore, when the Parser extracts the token x, it recognizes that it’s a function and replaces it with the actual x value, say, c.
After the first step, you’ll have the following cells consisting of strings and actions: ("c", ==), ("a", ||), ("c", ==), ("b", ")"). The symbol ")" denotes a null action. The last cell always has a null action.
The second step consists in merging all the cells one by one from left to right. Because the priority of == is higher than the priority of ||, the first two cells can be merged. The action of the left cell, ==, must be applied, yielding to:
Merge(("c", ==), ("a", ||)) = ("c" == "a", ||) = (0, "||").
You can’t merge the cell (0, ||) with the next one, ("c", ==), because the priority of the || action is lower than the priority of "==" according to the Listing 1. So we must first merge ("c", ==) with the next cell, ("b", )). This merge is possible and is analogous to the previous one: Merge(("c", ==), ("b", ")") ) = (0, ")").
Finally you must merge two resulting cells:
Merge ((0, ||), (0, ")")) = (0 || 0, )) = (0, ")")
The result of the expression is 0 (when x = "c").
See the full implementation of the Split-and-Merge algorithm in the accompanying source code download (on the CODE Magazine website), in the Parser.cs file. Check out the UML diagram containing all of the classes used in parsing the CSCS language in Figure 1.
Using the algorithm above with recursion, it’s possible to parse any compound expression. Here’s an example of the CSCS code:
x = sin(pi*2); if (x < 0 && log(x + 3*10^2) < 6*exp(x) || x < 1 - pi) { print("in if, x=", x); } else { print("in else, x=", x); }
The CSCS code snippet above uses several functions: sin, exp, log, and print. How does the Parser map them to the functions?
Writing Custom Functions in C# to be Used in the CSCS Code
Let’s see an example of implementing the Round() function. First of all, you define its name in the Constants.cs file as follows:
public const string ROUND = "round";
Next, you register the function implementation with the Parser:
ParserFunction.AddGlobal(Constants.ROUND, new RoundFunction());
In order to use all of the translations available in the configuration file, you must also register the function name in the Interpreter, so that it knows it needs to register all possible translations with the Parser:
AddTranslation(languageSection, Constants.ROUND);
Basically that’s it; the Parser will do the rest. As soon as the Parser gets the Constants.ROUND token (or any of its translations from the configuration file) it calls the implementation of the Round() function. All function implementations must derive from the ParserFunction class:
class RoundFunction : ParserFunction { protected override Variable Evaluate( string data, ref int from) { Variable arg = Parser.LoadAndCalculate( data, ref from, Constants.END_ARG_ARRAY); arg.Value = Math.Round(arg.Value); return arg; } }
Parser.LoadAndCalculate() is the main entry point of the Parser, which does all the work in parsing and calculating the expression and returning the result. Implementation of the rest of the functions looks very similar to the implementation of the Round() function.
Example: Client and Server Functions
Using functions, you can implement anything to be used in the CSCS language—as long as it can be implemented in C#, that is. Let’s see an example of inter-process communication: an echo server in CSCS, implemented via sockets.
Define the CSCS function names of the server and the client in the Constants.cs:
public const string CONNECTSRV = "connectsrv"; public const string STARTSRV = "startsrv";
Then you register these functions with the Parser:
ParserFunction.AddGlobal(Constants.CONNECTSRV, new ClientSocket(this)); ParserFunction.AddGlobal(Constants.STARTSRV, new ServerSocket(this));
Check out the implementation of the ServerSocket in Listing 2. The implementation of the ClientSocket is analogous. Figure 2 shows an example run of a client and a server on a Mac.
Any function that you want to use in CSCS can be implemented in C#. But can you implement a function in the scripting language, in CSCS itself?
Writing Custom Functions in CSCS
You define custom functions with the custom function definition in the Constants.cs file:
public const string FUNCTION = "function";
To tell the Parser to execute special code as soon as it sees the function keyword, you need to register the function handler with the handler. The Interpreter class does that:
ParserFunction.AddGlobal(Constants.FUNCTION, new FunctionCreator(this));
You can provide a translation to any language in the configuration file and the same applies to all other functions. See the project configuration file in the accompanying source code download (on the CODE Magazine website). You’ll find the Spanish keyword función there. In order to use all of the available translations, you must also register them in the Interpreter:
AddTranslation(languageSection, Constants.FUNCTION);
Check out the implementation of the Function Creator in Listing 3. It creates another function and registers it with the Parser:
CustomFunction customFunc = new CustomFunction( funcName, body, args); ParserFunction.AddGlobal(funcName, customFunc);
The name of the custom function to be registered is funcName. The Parser expects that the token with the function name will be the next one after the function token. Commas separate the tokens.
All of the functions that you implement in the CSCS code correspond to the different instances of the C# CustomFunction class.
During parsing, as soon as the Parser encounters the funcName token, it calls its handler, the CustomFunction, where all the action takes place. You can see the CustomFunction implementation in Listing 4.
Custom function does two things. First, it extracts the function arguments and adds them as local variables to the Parser (they’ll be removed from the Parser as soon as the function execution is finished or an exception is thrown).
Second, the body of the function is evaluated, using the main Parser entry point, the LoadAndCalculate() method If the body contains calls to other functions, or to itself, the calls to the CustomFunction can be recursive. Let’s see this with the factorial example.
Example: Factorial
The factorial notation is n! and it’s defined as follows: 0! = 1, n! = 1 * 2 * 3 * … * n.
In the notation, n must be a non-negative integer. Therefore it can be defined recursively as: n! = 1 * 2 * 3 * … * (n – 1) * n = (n – 1)! * n.
In CSCS, the code is the following:
function factorial(n) { if (!isInteger(n)) { exc = "Factorial is for integers only (n="+ n +")"; throw (exc); } if (n < 0) { exc = "Negative number (n="+n+") for factorial"; throw (exc); } if (n <= 1) { return 1; } return n * factorial(n - 1); }
The factorial function above uses an auxiliary isInteger() function:
function isInteger(candidate) { return candidate == round(candidate); }
The isInteger() function calls yet another round() function. The implementation of the round() function isn’t in CSCS but is already in C# code that you saw in the previous section.
Executing the factorial function with different arguments provides the following output:
.../Documents/cscs/cscs/bin/Debug>> a = factorial(-1) Negative number (n=-1) for factorial .../Documents/cscs/cscs/bin/Debug>> a = factorial(1.5) Factorial is for integers only (n=1.5) .../Documents/cscs/cscs/bin/Debug>> a = factorial(6) 720
The factorial code contains some throw() statements. This suggests that there should be something able to catch them.
Throw, Try, and Catch Control Flow Statements
The try() and throw() control flow statements can be implemented as functions in the same way that you saw the implementation of the Round() function above.
Both functions must be registered with the Parser first as well:
public const string TRY = "try"; public const string THROW = "throw";
The implementation of the throw() function follows:
class ThrowFunction : ParserFunction { protected override Variable Evaluate( string data, ref int from) { // 1. Extract what to throw. Variable arg = Utils.GetItem(data, ref from); // 2. Convert it to a string. string result = arg.AsString(); // 3. Throw it! throw new ArgumentException(result); } }
The try function requires a bit more work, so it’s easier to delegate all the work to the Interpreter, which can tell the Parser what to do:
class TryBlock : ParserFunction { internal TryBlock(Interpreter interpreter) { m_interpreter = interpreter; } protected override Variable Evaluate( string data, ref int from) { return m_interpreter.ProcessTry(data, ref from); } private Interpreter m_interpreter; }
In the Interpreter.ProcessTry() implementation, first you should note where you started the processing (so later on you can return back to skip the whole try-catch block). Then you process the try block, and if the exception is thrown, you catch it. In the Parser code, you throw only ArgumentException exceptions.
int startTryCondition = from - 1; int currentStackLevel = ParserFunction.GetCurrentStackLevel(); Exception exception = null; Variable result = null; try { result = ProcessBlock(data, ref from); } catch(ArgumentException exc) { exception = exc; }
If there’s an exception, or a catch or a break statement, you need to skip the whole catch block. For that, go back to the beginning of the try block and then skip it:
if (exception != null || result.Type == Variable.VarType.BREAK || result.Type == Variable.VarType.CONTINUE) { from = startTryCondition; SkipBlock(data, ref from); }
After the try block, you expect a catch token and the name of the exception to be caught, regardless of whether the exception was thrown or not:
string catchToken = Utils.GetNextToken(data, ref from); from++; // skip opening parenthesis // The next token after the try must be a catch. if (!Constants.CATCH_LIST.Contains(catchToken)) { throw new ArgumentException( "Expecting a 'catch()' but got [" + catchToken + "]"); } string exceptionName = Utils.GetNextToken(data, ref from); from++; // skip closing parenthesis
Why do you use a CATCH_LIST to see if the catch keyword is there and not just Constants.CATCH = "catch"? Because the CATCH_LIST contains all possible translations of the catch keyword in different languages. You provide them in the configuration file. For example, you can use atrapar in Spanish, or fangen in German..
In case of an exception, you must process the catch block. You first create an exception stack (what was called from what) and then add this information to the exception variable that can be used in the CSCS code that caught the expression:
if (exception != null) { string excStack = CreateExceptionStack( currentStackLevel); ParserFunction.InvalidateStacksAfterLevel( currentStackLevel); GetVarFunction excFunc = new GetVarFunction( new Variable(Double.NaN, exception.Message + excStack)); ParserFunction.AddGlobalOrLocalVariable( exceptionName, excFunc); result = ProcessBlock(data, ref from); ParserFunction.PopLocalVariable( exceptionName); }
In case there’s no exception, skip the catch block:
else { SkipBlock(data, ref from) }
Let’s try throwing and catching exceptions in action with the factorial function that you saw above. You use the following CSCS code that has some artificially created execution stacks for throwing an exception:
function trySuite(n) { print("Trying to calculate the", "negative factorial…"); result = tryNegative(n); return result; } function tryNegative(n) { return factorial(-1 * n); } try { f = tryNegative(5); print("factorial(", n, ")=", f); } catch(exc) { print ("Caught Exception: ", exc); }
After running it, you get the following exception message:
Trying to calculate negative factorial... Caught Exception: Negative number (n=-5) for factorial at factorial() tryNegative() trySuite()
Of course, this is a bare bones exception handling so you might want to add some fancier stuff, like at what line of the function the exception was thrown, function parameters, and so on.
How do you keep track of the execution stack? That is, of the functions being called? In ParserFunctions, you define the following static variable:
public class StackLevel { public StackLevel(string name = null) { Name = name; Variables = new Dictionary<string, ParserFunction> (); } public string Name { get; set; } public Dictionary<string, ParserFunction> Variables { get; set; } } private static Stack<StackLevel> s_locals = new Stack<StackLevel>();
Each StackLevel consists of all of the local variables of the function being executed (including the passed-in parameters) and the function name. This is the name you see in the exception stack.
Each time you start execution of a new function (regardless of whether it’s defined in the C# code or in the CSCS code), a new StackLevel is added to the s_locals stack. You pop up one StackLevel from the s_locals data structure each time you finish the execution of a function.
In the examples, you saw a few functions implemented in CSCS. Do all of the scripts have to be in the same file? Can you include other files containing the CSCS code?
Including Other Files Containing the CSCS Code
To include another module containing CSCS scripts, you use the same function approach as with all other functions, like you used with Round() or try/throw control statements. The include keyword is also defined in Constants.cs:
public const string INCLUDE = "include";
The function implementation is in the IncludeFile class deriving from the ParserFunction class:
ParserFunction.AddGlobal(Constants.INCLUDE, new IncludeFile());
In the CSCS code, including another file looks like this:
include("filename.cscs");
As soon as the Parser gets the INCLUDE token (or one of its translations), the execution of IncludeFile.Evaluate() is triggered. This function must first extract the actual script from the file to be included:
class IncludeFile : ParserFunction { protected override Variable Evaluate( string data, ref int from) { string filename = Utils.ResultToString( Utils.GetItem(data, ref from)); string[] lines = Utils.GetFileLines(filename); string includeFile = string.Join( Environment.NewLine, lines); string includeScript = Utils.ConvertToScript(includeFile);
Then you process the whole script using the Parser main method, LoadAndCalculate(). Note that at the end, you return an empty result because there’s nothing to return upon completion.
int filePtr = 0; while (filePtr < includeScript.Length) { Parser.LoadAndCalculate(includeScript, ref filePtr, Constants.END_LINE_ARRAY); Utils.GoToNextStatement(includeScript, ref filePtr); } return Variable.EmptyInstance; } }
All of the global functions added from the included file stay with the Parser after completion of the Include statement.
You can implement if, when, for, and other control flow statements in the same way you implemented the including of a file. I haven’t implemented the for loop because its functionality can be easily achieved with a while loop. Here’s an example of such a substitution of the for loop in the CSCS code:
i = 0;while (i++ < 10) { if (i % 2 == 0) { print (i, " is even."); } else { print (i, " is odd."); } }
Try to guess: In the CSCS code above, how many of the tokens are implemented as functions (that is, classes deriving from the ParserFunction class)? There are four: while(), if (), print(), and ++. Else isn’t a function by itself, it’s processed together with if (similarly, catch is not a separate function but is processed together with try).
What about the i++ token inside of the while() statement? How is it implemented?
Implementing ++ and -- Prefix and Postfix and Compound Assignment Operators
You can use the same approach for assignment as you did for including a file by implementing it as a function set(), for example. This is how I implemented the assignment in the first version of the language described in MSDN Magazine (See the sidebar for a link).
The assignment a = 5 is equivalent to set(a, 5), the prefix operator ++i is equivalent to set(i, i + 1). The postfix operator i++ is a bit longer: i++ is equivalent to set(i, i + 1) – 1 in CSCS.
A language with such awkward assignment operators can’t, obviously, be part of the Premier League of programming languages. You need a different approach to have proper assignment operations.
I decided to take the following approach: Declare action functions, all deriving from the abstract ActionFunction class (that derives from the ParserFunction class). An action function is triggered as soon as the Parser gets any of the following action tokens: ++, --, +=, -=, *=, etc. In case of ++ and --, you need first to find whether it’s a prefix or a postfix operator—the Parser will know that: In case of a prefix, it will have an unprocessed token before the action.
All of the actions must be registered with the Parser first:
ParserFunction.AddAction(Constants.ASSIGNMENT, new AssignFunction()); ParserFunction.AddAction(Constants.INCREMENT, new IncrementDecrementFunction()); ParserFunction.AddAction(Constants.DECREMENT, new IncrementDecrementFunction());
Check out the implementation of the IncrementDecrementFunction() in Listing 5. The implementation of other action functions is analogous. As you can see, the Parser knows from the context whether it works with a prefix or a postfix operator and if it was triggered because of a -- or a ++ action. Note that at the end, the function returns either the current variable value (in case of the prefix) or the previous value in case of the postfix.
With this approach, you can play around with the assignments in CSCS as follows:
a = 1; b = a++ - a--; // b = -1, a = 1 c = a = (b += 1); // a = b = c = 0 a -= ++c; // c = 1, a = -1 c = --a - ++a; // a = -1, c = -1
The Listing 5 has a section about arrays. I haven’t talked about them yet. How do the assignments work with arrays?
Arrays
The declaration of an array is different from the declaration of a variable in CSCS. To declare an array and initialize it with data, you use the same statement. As an example, here‘s the CSCS code:
a = 20; arr = {++a-a--, ++a*exp(0)/a--, -2*(--a - ++a), ++a};i = 0; while(i < size(arr)) { print("a[", i, "]=", arr[i], ", expecting ", i); i++; }
The number of elements in the array isn’t explicitly declared because it can be deduced from the assignment.
The function size() is implemented as a typical CSCS function returning the number of elements in an array. But if the passed argument isn’t an array, it returns the number of characters in it.
Internally, an array is implemented as a C# list so you can add elements to it on the fly.
You access elements of an array, or modify them, by using the squared brackets. If you access an element of an array and that element has not been initialized yet, an exception will be thrown by the Parser. However, it’s possible to assign a value to just one element of an array, even if the index used is greater than the number of elements in the array. In this case, non-existing elements of the array are initialized with empty values. This happens even if it’s the first assignment for this array. For this special shortcut array assignment, the CSCS function set() is used:
i = 10;while(--i > 0) { newarray[i] = 2*i; } print("newarray[9]=", newarray[9]); // 18 print("size(newarray)=", size(newarray)); // 10
Check out the array implementation in the accompanying source code download (available through the CODE Magazine website).
Compiling on Various Operating Systems
It’s a common misunderstanding that C# is for Windows only. People may have heard of a few attempts to port it to other operating systems, but most think that those attempts are still in some kind of a work in progress.
After using Xamarin Studio for Mac for some time, I found that it’s not quite a work in progress but rather a very powerful tool to build and run C# apps on a Mac. And it’s free! The underlying free and open source Mono project currently supports .NET 4.5 with C# 5.0. Recently, Microsoft announced that it’s planning to acquire Xamarin, so the support should continue and hopefully Xamarin Studio for Mac will be kept free (you can also use C# with Xamarin for iOS and Android programming, but this is already not free).
Xamarin doesn’t support any Windows Forms, but what concerns the core C# language is that I didn’t have to change a single line of code when porting my Visual Studio project from Windows. What I did have to change is the configuration file. For Windows the configuration looks like this:
<configuration> <configSections> <section name="Languages" type= "System.Configuration.NameValueSectionHandler"/> <section name="Synonyms" type= "System.Configuration.NameValueSectionHandler"/> …
Unfortunately, this wouldn’t work with Xamarin. There you must add ,System to the type:
<configuration> <configSections> <section name="Languages" type= "System.Configuration. NameValueSectionHandler,System"/> <section name="Synonyms" type= "System.Configuration. NameValueSectionHandler,System"/> …
That configuration won’t work with Visual Studio, so you must use different configuration files with Visual Studio than with Xamarin.
There’s also a way to use C# macros if you want to have different code when you use your language on Windows and on Mac OS. This especially makes sense if you work with the file system.
Implementing a Directory Listing on Windows and on Mac OS
The Xamarin Studio uses the Mono Framework and the macro to use if you want to know if you’re using Mono is #ifdef __MonoCS__. You can see it at work here:
public static string GetPathDetails(FileSystemInfo fs, string name) { string pathname = fs.FullName; bool isDir = (fs.Attributes & FileAttributes.Directory) != 0; #if __MonoCS__ Mono.Unix.UnixFileSystemInfo info; if (isDir) { info = new Mono.Unix.UnixDirectoryInfo(pathname); } else { info = new Mono.Unix.UnixFileInfo(pathname); }
In the code snippet above, you see Unix-specific code to get the directory or file data structure. Using this structure, it’s easy to find typical Unix permissions for user/group/others, which don’t make sense on Windows:
char ur = (info.FileAccessPermissions & Mono.Unix. FileAccessPermissions.UserRead) != 0 ? 'r' : '-'; char uw = (info.FileAccessPermissions & Mono.Unix. FileAccessPermissions.UserWrite) != 0 ? 'w' : '-'; char ux = (info.FileAccessPermissions & Mono.Unix. FileAccessPermissions.UserExecute) != 0 ? 'x' : '-'; char gr = (info.FileAccessPermissions & Mono.Unix. FileAccessPermissions.GroupRead) != 0 ? 'r' : '-'; ... string permissions = string.Format( " {0} { 1}{2} { 3}{4} { 5}{6} { 7} { 8} ", ur, uw, ux, gr, gw, gx, or, ow, ox);
Take a look at Listing 6 for the complete implementation of the GetPathDetails() function.
Figure 3 shows running the ls command on a Mac and Figure 4 shows running a dir command on a PC.
The question that might strike you now is: "How do I configure using the ls commandon a Mac and the dir command on a PC for the same CSCS function?"
Keywords in Different Languages
If you want a keyword to be used in any other language, you must add a code so that you can read possible translations from the configuration file. For example, I defined the keyword for a function to show the contents of a directory as follows:
public const string DIR = "dir";
Now, if I want possible translations of this keyword I add in the Interpreter initialization code:
AddTranslation(languageSection, Constants.DIR);
Because ls isn’t really a translation from dir to a foreign language, I added the Synonyms configuration section to smooth the differences between Windows and Mac concepts, so that they don’t look so foreign to each other:
<Languages> <add key="languages" value= "Synonyms,Spanish,German,Russian" /> </Languages> <Synonyms> <add key="del" value ="rm" /> <add key="move" value ="mv" /> <add key="copy" value ="cp" /> <add key="dir" value ="ls" /> <add key="read" value ="scan" /> <add key="writenl" value ="print" /> </Synonyms>
Using the same configuration file, you can add translations for the CSCS keywords in any language. Here’s a valid CSCS code to check whether a number is odd or even using the German keywords:
ich = 0; solange (ich++ < 10) { falls (ich % 2 == 0) { drucken (ich, " Gerade Zahl"); } sonst { drucken (ich, " Ungerade Zahl"); } }
Wrapping Up
Using the techniques presented in this article and consulting the accompanying source code download, you can develop your own fully customized language using your own keywords and functions. The resulting language will be interpreted at runtime directly, statement by statement.
The straightforward way of adding new functionality to the language is the following:
Think of an English keyword (primary name) of the function to be implemented in English:
public const string ROUND = "round";
Map this keyword to a C# class and register them both with the Parser:
ParserFunction.AddGlobal(Constants.ROUND, new RoundFunction());
Make it possible to read translations of this keyword from any language from the configuration file:
AddTranslation(languageSection, Constants.ROUND);
Implement the class registered above with the Parser. The class must derive from the ParserFunction class and you must override the Evaluate() method.
That’s it: using the technique above, you can implement not only the typical functions like round(), sin(), abs(), sqrt(), and so on, but most of the control flow statements, like if(), while(), break, return, continue, throw(), include(), etc. All variables declared in the CSCS code are implemented the same way: you register them as functions with the Parser.
You can use this language as a shell language to perform different file or operating system commands (find files, list directories or running processes, kill or start a new process from the command line, and so on). Or you can use it as a scripting language, writing any tasks and adding them to the scripts for execution. Basically, any task can be achieved in CSCS as long as it’s possible to implement it in C#.
There are a few things that are still far from perfect and could be added to the CSCS language. For instance, the debugging possibilities are next to nil. The exception handling is quite basic, so adding the possibility for the exception stack to show the line of code where it occurred would be interesting. Also, currently, only the list data structure is supported in CSCS (I call it tuple). Adding the possibility to use other data structures, like dictionaries, for instance, would be also an interesting exercise: let me know what you come up with! | https://www.codemag.com/Article/1607081 | CC-MAIN-2019-47 | refinedweb | 5,077 | 53.51 |
P/Invoke functions and attributes are found in the System.Runtime.InteropServices namespace. The .NET Compact Framework supports a useful subset of P/Invoke functions from the full .NET Framework. Most simple unmanaged code functions can be called without difficulty from managed code. Unmanaged code functions with more complex parameter passing requirements will need some additional support in the managed code caller.
To call a function in unmanaged code using P/Invoke, that function must be exported from a DLL. An exported function is one that can be called across an EXE/DLL or DLL/DLL boundary.
From the .NET point of view, unmanaged code functions are static. They do not operate on instances of ...
No credit card required | https://www.safaribooksonline.com/library/view/microsoft-net-compact/0735617252/ch22s03.html | CC-MAIN-2018-34 | refinedweb | 119 | 58.89 |
OK. But then how does the message protocol handler know when a message is
done? How do you know you've actually received all the data for a discreet
If the answer is this is not handled by default then how is this typically
done in MINA... how do you hold onto inbound client data until a full
message is ready? For example:
public class ReverseProtocolHandler extends ProtocolHandlerAdapter
{
...
public void messageReceived( ProtocolSession session,
Object message )
{
// Reverse reveiced string
String str = message.toString();
StringBuffer buf = new StringBuffer( str.length() );
for( int i = str.length() - 1; i >= 0; i-- )
{
buf.append( str.charAt( i ) );
}
// and write it back.
session.write( buf.toString() );
}
}
I can test in here whether all the data is available, but if I don't have
the entire message do I have to then implement my own per-client message
buffering?
_____
From: Trustin Lee [mailto:trustin@gmail.com]
Sent: Monday, 23 May 2005 5:56 PM
To: Apache Directory Developers List
Subject: Re: [mina] c# client
Hi Martin,
2005/5/23, Martin J. Wells <marty@dot.net.au>:?
MINA itself doesn't implement any protocols. It simply helps you to
implement your or any others' protocols. If any protocol specification is
not defined, you'll have to define some first, and then implement the server
to conform to that specifiation, and MINA will help you implementing it.
So.. if you're implementing C# client for a server which is made on top of
MINA, actually it dosn't matter whether the server is implemented using MINA
or any other frameworks.
Thanks,
Trustin
--
what we call human nature is actually human habit
-- | http://mail-archives.apache.org/mod_mbox/directory-dev/200505.mbox/%3CE1Da7so-0000pB-00@ps10.kent.dot.net.au%3E | CC-MAIN-2016-18 | refinedweb | 273 | 56.55 |
If you construct a long program today and try to recall it after a few days, there is every possibility that you would have forgotten quite a few things and even what the program does or what a particular name stands for. Comments if included in a program help in recollection of different names, data values and other parameters.
Generally, a comment is enclosed between the symbols /* at the start and *I at the end. A comment may be of any length. It may be spread over several lines, generally referred to as block comment, or it may be included in a code line or written separately. Following are some examples of comments:
/* This is my first comment.*/
A= S/* Sale amount*// N;
"Delhi/**/London"
The second line in the above example is equivalent to the code A = S/N; and Sale amount is a comment enclosed between I * and * I. In the third line, I * *I is not a comment in the program, instead it is part of a character string that is enclosed between the double quotes (" ") . Including comments between the symbols/* and */ is useful for part-of-line comment as well as for block comment. Remember that there is no space between the two characters in/* or */.
The C++ style of the comment is also now part of C language. In this style, a comment may be put after double slash (//) up to the end of line. If it is to be used within a code line, then it should start after the code because any code written after double slash will become part of comment. If the comment is long and goes to next line, then another double slash is needed at the beginning of next line. An example of this is given in below
Illustrates inclusion of comments. The code lines are shown in bold.
#include <stdio.h>
// This is /*my*/ comments program.
void main() //The program illustrates comments.
{
/* This is my //first//program with comments*/
printf (/*A comment*/"Welcome to //programming /* See This Comment */ in C.\n");
/*This is a block comment within a code line which end with
* semicolon.
* Some prefer to put asterisk before every line.
* This is another comment.
*/;
}
The expected output of the above program is as follows:
In the above output, the comment included in the output string [i.e., the statement between double quotes and argument of printf()] has not been neglected and has become part of the output, whereas all other comments have been neglected. Also, note that you cannot have any code between/* and*/, because it would become part of comment. Remember that the comment symbols/* and*/ cannot be | https://ecomputernotes.com/what-is-c/basic-of-c-programming/comments-in-c | CC-MAIN-2019-30 | refinedweb | 443 | 71.44 |
Timer Class - ActionScript 3.0
The Timer class is a new addition to AS 3.0. The Timer class is similar to the setInterval function in AS 2.0 but has some more features added to it. One of such feature is the ability to start and stop the timer when needed.
Timer in AS 3.0 behaves a little different than the setInterval call in AS 2.0. A timer fires a timer event at regular intervals (the interval which is defined when defining the timer). As with the case of setInterval one can specify the time interval in which the event has to be fired.
The Timer class is part of the flash.utils package and has to be imported before one can use it. The declaration goes like this:
import flash.utils.Timer;
As mentioned earlier a Timer has a event associcated with it which is called a TimerEvent. The TimerEvent class is present in the flash.events package and if thie TimerEvent is used, one has to import the event before using it.
import flash.events.TimerEvent;
Now for the syntax of declaring a Timer it goes like this:
var myTimer:Timer = new Timer(delay, iterations);
One primary difference between the setInterval call and using a Timer is that, the Timer has a extra parameter which says how many times the timer has to fire (iterations). If you want the timer to iterate forever then the iteration can be declared as 0. This would keep firing the Timer forever.
To listen to the timer you need to add a listener which listens to the TimerEvent.
myTimer.addEventListener(TimerEvent.TIMER, drawRectangle);
and then start the timer.
myTimer.start();
At this point its also important to note that the getTimer function in AS 2.0 still exists and is in the package flash.utils and can be used as:
flash.utils.getTimer();
Sample code:
package {
import flash.utils.Timer;
import flash.utils.getTimer;
import flash.events.TimerEvent;
import flash.display.Sprite;
public class TimerExample extends Sprite
{
public function TimerExample()
{
var myTimer:Timer = new Timer(100, 10);
myTimer.addEventListener(TimerEvent.TIMER, drawRectangle);
myTimer.start();
}
private function drawRectangle(evt:TimerEvent):void
{
trace(flash.utils.getTimer()+ " : " + evt);
}
}
}
The other useful properties that are present in the Timer class are:
currentCount - Returns the total number of times the timer has fired since it started at zero.
repeatCount - Returns the total number of times the timer is set to run.
running - Returns true if the timer is running else false.
delay - Returns the delay in milliseconds and can also be set while the timer is running.
The other two methods of the Timer class which the example above doesn't cover are:
stop() - Stops the current running timer.
reset() - Resets the currently running timer and sets the current count to 0.
Another event which is associated with the TimerEvent is:
TimerEvent.TIMER_COMPLETE - This event is fired when the timer is completed and can used as:
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, drawRectangle); | http://tutorials.lastashero.com/2007/01/timer_class_actionscript_30.html | crawl-002 | refinedweb | 497 | 67.86 |
Postcards From Linux Part 3:
Mouse vs. Keyboard
My adventure into the world of Linux-using continues. With regard to the holy war of GUI interfaces vs. the POWER OF THE COMMAND LINE, I have to say that I see this as a false dichotomy. A menu lets you know what can be done, where stuff is, and what the options are. Once you know these things, a command line is [sometimes] the fastest way to do them. In the terminal I feel blind. In a windowed situation I feel like it’s too many steps to reach certain options.
You know what interface paradigm I always loved? Games made with id Tech 4 and Source engines. (Doom 3 and Half-Life 2, respectively.) You’ve got your menus and sliders and checkboxes and whatnots, but if you need to get into the crazy stuff you tap tilde and you’ve got sleek command line interface with text coloring, command history, script execution, and autocomplete. Yes, I know operating systems are more complex than videogames, but there’s a lot of value in this hybrid approach.
An interesting problem I like to think about: How can you use the GUI to teach the user to use the command line? I know this is heresy to the purists, but I see a lot of value in it. However it worked, it would have to be like keyboard shortcuts: When you look at a menu it usually lists the keyboard shortcuts for the stuff you’re doing. You can use the menu or the shortcut, and it’s up to the user when they want to make the mental investment of learning to do things the optimal way. If you select the same thing again and again, you’ll get irritated enough to memorize the shortcut. However, you never have to memorize anything and are free to do almost everything with the mouse. Repetition will create a desire for optimization which will create willingness to learn.
For me, a great example of this is MySQL. I use it once every six months or so. These intervals are so far apart that I don’t remember the commands. I have to look up every command, every time. One example of a dozen:
select database_foo
Hey, why didn’t that work?
select database_foo;
Nope. Damnit. uhhh…
SELECT database_foo
No. Fine. Google search. Oh right!
use database_foo
Okay, got it. I’m sure I’ll remember that next time. Now lets see…
delete table foo;
What? Why didn’t that work?
You get the idea. I can’t learn this stuff because I use it so rarely. This is a situation where you’d want to use a menu. Yes, it’s way slower to click-click-click your way through a GUI, but it’s faster and less frustrating than doing a search for every command.
When it comes to a GUI / terminal hybrid interface, I’m not sure how you could present this information. I’m not even sure it’s possible. But it’s still an interesting problem I like to think about.
Anyway, the stuff I’ve been working on…
IDE
You might remember from last time that I was completely baffled at trying to get a simple thing working. I got this sorted out with some help from a Linux-savvy friend. Here was his advice, which worked for me:
- As I’d already discovered: Don’t download libraries and source from the web unless you’re doing something really unusual or exotic, which should not be your first steps in programming on Linux. Also don’t use the Software Manager. While better, it still won’t give you all the parts you need. Instead…
- Use the Synaptic Package Manager. This should be your go-to place for getting libraries.
- When you’re looking for foo, it will probably be listed in the manager as libfoo. That’s the binaries so that you can use foo. However, if you want to write code with foo then you need libfoo-dev. These rules are not written in stone and there are exceptions, but this should help you narrow that initial search.
- Those long dependency chains we see in Windows? You know, where you need to install library B, which depends on C, which depends on D. The synaptic package manager mostly untangles this for you. However, it might be good to go up the chain a bit. Instead of installing B, maybe look and see if there is library A and install that instead. You’ll get B as part of the deal, and a whole lot of inter-dependence and path-sorting should get sorted out in the process. For example, I wanted the GTK library. By downloading the gnome-common package I got GTK, all the stuff that GTK needs, and all of the stuff to use GTK in various IDEs.
Disclaimer: The above is very rudimentary and probably factually correct in places. I said I got advice. I didn’t magically learn the entire system in a couple of days.
At any rate, I can code now. I’m not doing anything serious. I’m just making bits of things compile and getting a sense of how it all works. My sense at this point is that using libraries in Windows is always a pain in the ass. By contrast, on Linux it’s either trivial or impossible. So that’s kind of interesting.
Keyboard Shortcuts
On Windows, if you have NumLock off (so the keypad is in navigation mode) then pressing shift doesn’t alter the behavior of the keys. If you’re on a line of text, then pressing shift+num7 home (num 7) should select everything from the current cursor position to the beginning of the line.
On Linux, this will just type a seven.
This has been driving me crazy. It’s a small thing, but it’s deeply ingrained into my typing habits. I can see the merits of both systems and I don’t think either one is “wrong”. But I’ve got a quarter century of muscle memory behind using shift-num7 to select to the beginning of a line, and it’s proving difficult to overcome. The worst part is, I’m most likely to make this mistake when I’m already agitated and fighting with some other problem. As I hammer away, looking for a solution to an unrelated problem I end up typing more and more random numbers or accidentally clearing things I’ve typed. Ease-of-use issues like this form little negative feedback loops for me where frustrations compound and proliferate mistakes, leading to more frustrations.
I figured this was just the cost of making the switch. I mean, this is a pretty rare typing habit and it’s not like Linux coders are falling over themselves to accommodate every tiny little whim of Windows refugees.
But as it turns out, there is a solution. It’s easy. (Just slightly hard to find.) Under System Tools»System Settings»Keyboard Layout»Layouts tab, there’s an options button at the bottom of the dialog that takes you to a massive list that must encompass every conceivable keyboard configuration option, no matter how trivial, obscure, esoteric, novel, or odd. In that list is an option to make the shift-numpad relationship work like in Windows.
Wine
Paint Shop Pro is an off-brand image editing software. It doesn’t just stand in the shadow of Adobe Photoshop, it is eclipsed by it. Version 8 came out in 2003, and was one of the last entries into the now-extinct mid-market image editing software. Since then, the market has fragmented into two distinct camps:
- Simple software for touching up photographs: Brightness, contrast, color, cropping, borders. This stuff is either cheap or free, and is designed to be used by the proverbial grandpa trying to digitize his yellowing photo albums before he drops dead.
- Professional image manipulation software which can do anything and everything. You can photoshop things, paint digital pictures, create logos, restore old photographs, or whatever other kind of pixel-pushing you need to do. These things typically cost hundreds of dollars.
The extinct(?) mid-market stuff had 90% of the features of the top-tier stuff for 25% of the price. I bought Paint Shop Pro 8 sometime around 2004 or so. I think I paid $40, marked down from $70. This was a sweet spot for me with regards to price and features. A few years later Corel bought the developer and I can’t really tell what they’re doing with it these days. The feature list makes it sound like they gutted it, but maybe they’re just playing up with “simple tool for home photos” angle because that’s a bigger market than “bloggers who need to fiddle with things a bit”.
In any case, I’ve been using PSP8 for the better part of a decade now. That’s a long time to stick with a single version of something, and even now I’m not feeling any urge to upgrade. The software does everything I need it to do, I know how to use it, it’s stable, and it’s paid for. It is not possible to improve on this situation.
I was really worried about this when moving to Linux. The open source alternative on Linux is called GIMP, which is notorious for its interface. I’ve used it in the past and thought it felt like someone had taken all the tools in the toolbox and tied them together like Christmas lights. This might seem like a good idea until you actually try to use them this way.
I tried Wine, the program that lets old Windows programs run on Linux. It worked flawlessly here. PSP8 might be a little slower now, but it’s otherwise the same tool I’ve been using for years.
How can you use the GUI to teach the user to use the command line?
I think an example might be phpMyAdmin. After every operation (click) on the interface it displays the command line that was executed. So incidentally you can learn MySQL.
SMIT (the AIX admin GUI thing, may no longer be around) used to do that from the early 90s up uptil at least the early 00s. Mostly famous for having a running man icon and if whatever yo utried doing failed, the running man would fall over.
Didn’t help that AIX admin commands were like those on no other unixoid OS around, but if you wanted to see what your form-filling-out would do, you simply pressed (IIRC) F6.
STATA does something similar. Which is a good thing, because the documentation for that program is horrendous.
With Server 2012, Microsoft is now embracing the same philosophy. Every operating system command is a powershell script, essentially. The powershell is color coded, autocompleting and has a nice help system built into it.
They don’t teach you the powershell commands every time you click a button, but I would bet there’s going to be third party software that can capture those commands as you’re navigating and display them.
One of the ideas I have been toying with is a graphical command pipeline editor, where you can construct your impressive (or not) command line by dragging progams onto a canvas and hooking their input/outputs together using, heh, pipes.
But that always flouders on “but why not be able to do shell loops, and conditionals, and…” and at that point my brain goes “GUIs are hard, let’s keep typing”.
Do it the same way graphical editors (I think Shamus blogged about one (Sketch I think?) here) work for loops and such (or Word works math equations, for that matter): You drag-drop the construct, which has gaps into which you can drag-drop commands/more constructs. So you drag-drop a While (Condition) (Command) and then Condition has some simple stuff (or typeable, or whatever) and Command is the same as the cmd line itself.
I think you’re basically talking about Apples Automator.
I believe Blender literally lists the Python command corresponding to each menu item as a tooltip.
Mid-market image editing software isn’t extinct: Paint.NET!
I use it for everything from photo post-processing to icons to web images to random graphical needs. It’s got a great interface, and there are tons of plugins for all sorts of needs if the base software doesn’t cover it.
Totally free, and only a 3.5MB download. Far better than PSP8, in my opinion (I used PSP for years, Paint.NET replaced it).
But it doesn’t run on Linux, not even under Wine. There’s a less-fully-featured Linux clone:
Agreed, Paint.NET is good for virtually any small image editing job. Comes recommended from me as well. I like the workflow and interface of Photoshop more but it’s hard to deny how easy and fast Paint.NET is.
Of course, standard MS Paint is actually very good for basic tasks now as well, so it’s questionable whether anyone even needs a mid-tier image editor.
Paint.net (Windows) is a great little editor for most of what you need at the great price of free with donations taken for those who feel guilty getting so much without paying. I have to say on Linux that I normally work on the GIMP modified to look close to Photoshop (once upon a time I used PS for work so I know that interface and stock GIMP looks like a UI designed by someone who believes in the command line rather than reading a book on HCI before they started building the GUI).
The GUI stuff (WIMP is a discoverable interface, the command line is traditionally not and being able to manual search for commands is all well and good but you need to know what the command is to find it in some cases and a GUI showing you all the options and restraining your input to valid options is a lot easier than reading through the command line options help) is something that gets solved with exposing a macro mode in the GUI. Command macros (rather than recorded macros that track your click/typing chain and don’t expose the underlying commands as a string) are basically why all programs that want to automate some things need a command line interface, because you build your macro language from the exact same stuff as the command line. Linking a recording macro to the command macro is the answer. Press red record button, do activity in GUI, get back command macro which is written in CLI language that does what you just did. n future you can know what the CLI way of doing something you did in the GUI was by reading the recorded macro files. Anyone who says only CLI or only GUI is the true answer needs to just think about this unification of both and realise they need to stop fighting for one camp when having both is clearly the right answer. I will spend a lot of my time in a GUI (for a start because when I was first using a WIMP driven system in the mid 80s I couldn’t read/write that well due to my age, it was the first way I interacted with a PC and always feels natural on these computers with mice and displays that are not limited to ASCII output) thanks to the discoverability but the CLI is also invaluable and basic things like piping make it very powerful for chaining programs together in ways you can’t do with GUI only apps.
Paint.NET and Gimp both have one major deal killer for me: they do not support tablet pressure sensitivity. Paint.NET even did at one point and then removed the feature. This defeats the entire reason why I have a tablet!
I actually have a copy of PSP X2($25, on sale from around $60) which comes out any time I need to do something that can’t be done in XNView(free image viewing and adjustment suite). As far as I can tell, nothing has actually been *removed* from the earlier versions(I used PSP7 for a while), so I suspect they’ve just changed their marketing angle.
Holy… really? Now Gimp starts sounding even more useless, compared to Photoshop.
I used Corel Painter for a while. I find it more intuitive for drawing than Photoshop, it’s made to act like you’re actually drawing something, it has a lot of brushes with predictable behaviours, it even simulates watercolour mixing. Then I had to draw vector images, so I switched to Illustrator. It’s great for that purpose. Between these two programs I have everything I need for drawing. I only use Photoshop for image correction of photographs.
Well, it would be proper to say I USED these programs, because my career took a different turn. Now my expensive PC is only taxed when gaming.
Of course GIMP supports pressure sensitivity.
You just have to check the correspondent box in the tool box. It’s right under “Brush Dynamics”.
There you will find many more advanced options, too.
Heads up, the new version of GIMP (2.8), broke tablets. You need to use 2.6 to really have tablets work properly.
2.8 makes me angry for that and making me use export now.
Haven’t tried tablets with 2.8 (maybe it’s a personal problem of yours), but export is a reasonable change in the long run.
The export thing is REALLY nice for working with stuff like GUI composition where you might want to do several iterations, but ultimately want the result in a flat format for fast and easy loading. Previously you had to use “save as” manually to export to whatever your target format was (I usually use PNG), since in practice you still want the full composition structure (as XCF) for future editing.
The export makes this total non-issue: it remembers what the export file was, so saving as target format is a single keyboard shortcut, while saving the “working process” is another keyboard shortcut. Makes the common process of “saving and exporting” much easier.
Sure it’s a tiny additional pain if you only ever want to edit something once, but anything more complex it’s a HUGE time saver. Combined with the hierarchical layers support (finally) these two features have certainly boosted my GUI graphics productivity in GIMP by an order of magnitude.
As for 2.8 and tablets.. technically it works on Windows at least. Usability-wise I agree it was kinda easier previously, though I find that GIMP’s tablet support was always a bit weird. Feature-wise it can still do more than previously; hopefully next version they replace the UI with something that’s a bit faster to work with.
GIMP 2.8 does support tablets and pressure sensitivity (I know this because I use GIMP 2.8 these days), but it’s not turned on by default.
Also, I recommend that you turn off color management, as it appears to cause crashes to the desktop – obviously a horrible experience for a program used to create content.
Last time I tried GIMP(because tablet drivers were acting up, admittedly around 3 years ago), that box was grayed out and there was a note on both the GIMP and Paint.NET websites saying that pressure support had been removed.
Lucky for me, rolling back my tablet drivers to an earlier version fixed the problem.
Oh, and for TSE: Paintshop Pro supports vectors as well. Probably not quite as in-depth as in Illustrator. I used PSP7 to vectorize an Elijah Wood autograph I got from one friend to use in a birthday present for another.
Strange. Considering that Paint.NET is supposed to be a .NET app, I find it strange that it wouldn’t work under Linux with Mono installed. With some library wrangling of course.
Doesn’t Paint.NET need Mona? Mona is a linux/osx port of MS .net framework.
Doesn’t Paint.NET need Mono? Mono is a linux/osx port of MS .net framework.
I second the recommendation for Paint.NET. I actually do use Photoshop for doing real digital manipulation, restoring old photos, etc. but for the more common tasks, it’s great to not have to wait for the beast to load. Also the Paint.NET UI is outrageously intuitive.
For stuff like crop/resize/rotate/add text however it’s already overkill, nowadays a good image viewer will do that. I use and love IrfanView, you just press F12 and get a basic palette of tools that’s roughly comparable to Windows 7 Paint.
I’ll have to try it again. THe last time I used it I was constantly frustrated by slow response times, laggy display and browser crashes. And this was on a very nice computer. It’s been a year or two since I played with it.
To be fair, GIMP’s multi-window interface is very nice if you happen to have two monitors. And there is a new optional single-window mode for some months now.
Note: I do not want to start one of the many fruitless GIMP vs. PS and vice versa discussions. Oh, please, no …
I use GIMP every day. It is very powerful after you’ve figured out how it works, and where all the filters are. Recently I had to make a custom brush for doing pixel work, since the stock brush cannot do a 2×2 or 4×4 pixel square.
The multiwindow mode has one amazingly bad flaw that I can’t believe nobody has ever corrected. You have to click to change window-focus every single time. That means if you use the toolbar to select a brush or fill tool, you have to click once to focus the toolbar window, then another time to select the tool, then again to reselect the image window, and again to actually use the tool. 4 clicks for what should be a 2 click operation.
Single window mode finally made gimp usable. I love it now.
That might be a unixism of GIMP. Old-school Unix windowing systems tended (I think) to have focus-follows-mouse, so that you didn’t actually have to click to change the focus. It still sucks in a world where almost noone uses focus-follows-mouse, of course.
Tried just now to see, and for me, on Windows, clicking a button in a window other than the active one both switches focus and activates the button.
I wouldn’t know if this is GIMP’s fault, doesn’t happen to me … but I have my window manager set to “sloppy mouse focus”, which means that windows get focus immediately when I move mouse cursor over them (don’t have to click when I want to type into another window, don’t have to *raise* the window to type into it). I am not sure what would happen if I set it to “click to focus”.
The “GUI which also teaches commandline” idea is an interesting one. The thing with a lot of commandline programs, though, is that you spend most of the time specifying some action up-front before invoking it; the corresponding GUI would be some big dialog where you configure a page of checkboxes and comboboxes etc. before hitting a shiny red “Go!” button.
My gut feeling is that a hybrid file manager / terminal would be the way to go. Many commands that are “interesting” do some operation on a number of files, then get out of your life. The file manager could be used to select a bunch of input files (and output dirs?) interactively, then toolbar buttons and/or context menus could select what to do with those files. At the bottom it’d show you what commandline you were building up, along with a “Go” or “Cancel” button.
The kind of data that the bash-completion package has accumulated might be useful to have for this project.
“GUI which also teaches commandline” I guess is kinda what the start search bar in windows is in a basic form.
Then there is the free PowerShell thingy for windows, by microsoft as well, never tried that one.
“The open source alternative on Linux is called GIMP”
No. GIMP is merely ONE alternative. Try Krita.
> merely ONE alternative
…Welcome to Linux! :-)
Not that I mind of course, or I wouldn’t keep using it. But yeah, there are almost always ten other ways to do whatever you’re looking at. They may or may not work for you of course.
Krita is an excellent program, albeit more focused on drawing and painting. It’s less of an alternative for extensive photo manipulations.
Woah, never knew about this one, thanks!
“My sense at this point is that using libraries in Windows is always a pain in the ass. By contrast, on Linux it’s either trivial or impossible.”
I think you could replace the word “libraries” with damn near anything in this statement and it would remain true.
Interesting, a lot of times I feel the same, but in reverse. At heart I’m a networking guy, and the iproute2 and iptables tools are sublimely powerful. They are not, however, generally intuitive to… well, most of the people that I’ve talked to about them. So I can make Linux do amazing feats of network acrobatics, while in windows there’s a nice gui for setting an IP address and if I want to do something fiendishly convoluted, I often come to the conclusion that the only way I could do it is to install VMware and build a linux VM to do the routing for me in front of the windows box.
Windows also seems insistent on making the command line more difficult to use than it needs to be. Way back when I admin’d windows networks, being a command line sort of person, I’d use it for a lot of things. There are a few useful things in there, but one thing that always made me tear my hair out was that the cmd processor has a fully functional for loop that, while not being able to take input on stdin, can iterate through lines generated by a command, but the command line for showing users “net user” would output the list of users in 3 columns, and there was no way to change that.
So Shamus, your idea for the gui that teaches the command line seems like a really good idea to me, though it seems like it’s mostly useful for single commands or systems or what-have-you, and easiest to do when the GUI is just a front-end to running a command (which often is the case). The thing is, to me the real power is not so much a single command that could either have a gui or I could read the hopefully informative man page on, but the synergy of lots of little tools. ‘ls img*[0-9].{jpg,jpeg,gif} | xargs mogrify….’ I’ve not seen a gui that could do something like that, but if there was one… I’m not entirely sure it’d be any easier to use than the command line.
I’m not a programmer, but I do use a lot of different software. The most basic one is AutoCAD. It uses a command line with configurable commands and icons for every single possible action. The command line is always visible, unless turned off. It gives status updates and directions as well as a history of user actions. Using an icon just inputs and executes a command in the command line. Even shortcuts like ctrl-s get transformed into commands. It’s an archaic way to do things, newer software uses shortcuts with modifiers from the ctrl, alt and shift keys, but seeing what command your action invokes is very helpful when learning to use the software.
And I was about to mention AutoCAD.
Glad to know you didn’t give up in a fit of rage. I’d have understood if you did – most people do, as evidenced by the comments on your last postcard.
The command line thing – I think you’re right about people’s usage of it. For tasks you don’t do often, it’s easier to navigate an interface with tool tips and help and so on.
Replacing the command line entirely just leads to horrendously complicated GUIs though, that become bloated and unweildly, and difficult to navigate. This is often the case in Windows Server.
As for learning the terminal via a gui, I don’t think there are many people actively trying to do that. Someone above mentioned PHPMyAdmin, but I don’t know if that gives you a clear idea of how to do the same thing via the SQL cli.
Paint Shop Pro working fine in GIMP is great, but I doubt it would run the latest version of Photoshop flawlessly. Anyone tried?
Shamus, if you see this: what video card do you have, and which drivers are you using in Mint? Have you tried any 3D games at all, like TF2?
I’m not sure about CS6, but CS5 works pretty good.
I use the corel branded (now) “paintshop pro photo X2” for pretty much everything. It’s a couple versions behind (I think they’re up to X4 or X6 now or something) but it does everything I want it to do, with the exception of behaving strangely with Nvidia’s normal map filter plugin, for which I have to boot up GIMP.
I -hate- GIMP. The interface was clearly designed by somebody who has never had to do anything quickly.
Anyway, I just wanted to chime in here and say that I think PSP was better off when it was still Jasc, but the corel versions aren’t bad. And they typically cost <$50 which is far superior to whatever ridiculous bullshit adobe is charging for photoshop.
Adobe does have Photoshop Elements for something like $70.
I have no idea if it’s any good, but that and not Photoshop is clearly their offer to compete with programs like PSP.
Interesting note:
If you were using unity, and tapped alt, you get what they call a ‘hud’ which is like a console for currently running apps.
From what I can tell it searches the gui menu structure and presents you with those options via autocomplete! :)
Mostly useful when unity craps out and loses the gui menu, but still, I think it’s a step in the right direction
PS: gimp2.8 is pretty nice, it even has the option to turn off the multiple window gui that people have been whining about for years
also: much faster startup, and uses your gpu for graphics processing! what’s not to like?
I was not aware of this. Very neat. Thank you.
“How can you use the GUI to teach the user to use the command line?”
This is an interesting idea, but I see a major problem with it: command-lines and GUIs are completely different, and, more importantly, require a different method of thinking. Trying to design a GUI around the command-line (or vice-versa) would necessarily hamstring the GUI, preventing it from playing to its strengths.
As an example, let’s look at a pretty basic use case, exploring a filesystem. In a GUI file explorer, to change directories, you simply click on a directory. How could you use this to teach the cd command? You could change it so that changing directories required going to File->Change Directory. I think we can all agree that would be awful. Ok, that’s right out, how about if we had some kind of tooltip? So when you moused over a directory foo it gave you a tooltip that said “cd foo”. That could work, although I’m not sure how it would induce the user to want to use the command-line over just double-clicking the thing that’s already right in front of their face. The big problem with this is that it hides the true power of the cd command. If I want to go from my home directory ~ to some deeply nested directory, say ~/foo/bar/baz, in the GUI I have to double-click foo, then double-click bar, then double-click baz. In the command line I can type cd foo/bar/baz/–how do you represent this in the file explorer sitting in ~? What about tab-completion, how does that even make sense in a graphical context?
This sort of thing is called impedance mismatch. It’s impossible to bring the two together without severely affecting one or the other (or both), which is why I don’t think this is a good idea for an end-user environment to pursue. I would rather developers continue the excellent work they’ve done in recent years (thanks largely to Canonical) in bringing the standard of Linux’s GUI interfaces up to par. An end-user should never have to touch the command-line unless they want to, and these days, 99% of the time they don’t. On the other hand, if you’re a developer, I think it’s perfectly reasonable to expect people to learn how to use their tools–especially in the era of the internet, where finding a decent intro to the command-line requires five minutes on Google.
I do think, however, your idea would make a very neat tool specifically to teach the command-line! Imagine a terminal window that also had a menu bar on top with common commands, like cd, ls, etc. Then if you wanted to change directory, you could go to File->Change Directory, browse for the directory you want in a standard graphical file window, hit OK and then the command-line would fill in cd foo/bar/baz and automatically hit enter so you could see what the command-line is. It would give a newbie the power of the command-line with the added feature of discoverability, and the ability to dig something up in the GUI when they’ve blanked on the exact command. There are still weaknesses to this approach–you can’t add *every* command, since the number of possible commands is infinite (write a script, drop it anywhere in $PATH and set the +x bit and voila! New command) but it would be a very good tool to add discoverability to the command-line for those who are interested in going down that path.
> (thanks largely to Canonical)
Die in a fire, unity. If I wanted to use a Mac, I know how to find one.
(Yes, only half joking. It’s *really*, *really* not an interface I want to keep using, but hey whatever.)
It doesn’t have to be a program able to do everything a graphical program and a command line program, just one that, every time you do something notes “Hey, next time if you don’t want to bother with all this, just type this command instead!”
This might sound strange. I could have sworn that you once made a night before Christmas spoof but now I cant find it. does it exist or am i confusing you with someone else?
I just wanted to say I’m really, really enjoying more text (as opposed to video) content on this blog. I almost stopped checking when all the posts were nothing but Spoiler Warning (not that I dislike Spoiler Warning, but I rarely both am in an environment where I can watch a video AND have the time to watch it).
Yes!!! Yay text! Shamus, we’re in it for the writing!
Agreed in full.
The text accompanying (sp?) the Spoiler Warnings is usually funny enough for me to bother to come and read :p
COMPLETELY OFF TOPIC, BUT I’M DESPERATE…
Does anyone know how I can reach Josh or Randy of Twenty Sided’s official Guild Wars 2 guild – the Eikosi League?
This guild is currently stuck in limbo because none of its leaders have logged into the game in weeks.
I would like to add new members and make the guild active again, but nothing can be done until leadership is transferred to someone who is currently playing the game.
Thanks!
On that note, how are people doing in GW2? Is the overall userbase still populated, or are things more calm and level now? (Also, how’s the guild?)
Sorry for not getting baack to you. This is something I keep meaning to talk to Josh about.
I can’t log in to GW2 right now because of this Linux business. Josh is travelling. I’ll see if we can sort this out and get you running again.
Thank you Shamus!
The player population in the game has dropped significantly. Or, at least, it has on the server where the D20 guild is located.
Thankfully, the game adjusts according to the number of players in any given map area, so you can still complete objectives, even if you’re the only person doing them at the time.
Jarenth has been around, and he’s got those permissions; could you work through him?
I attempted to post a comment regarding needing to locate Josh or Randy of D20’s Eikosi League.
When I clicked on the “Post Comment” button, my browser hung.
My comment appears to have been lost in the internet ether and did not get posted.
Now I can’t make another attempt to post the comment because I get an error message stating that I’m making a duplicate post.
It seems it was actually posted. Maybe it arived after you refreshed the page?!?!
Shamus, I’m not sure if you’ve realized this due to Linux GUI conventions being different from on Windows, but you can move those Codeblocks toolbars around so they’re not taking up so much vertical space. You can even hide some of them entirely from the View -> Toolbars menu.
I moved from using PS:CS2 in high school to GIMP. At one time it was just as fast for me to do things in GIMP, or I could do them faster. I remember the first time opening GIMP and ragequitting it a minute and a half later due to not being able to find how to do the simplest of things. Switching just takes a little bit of time, and lots of patience.
I’m not familiar with PSP in the least, but GIMP just has things in different places than photoshop, and 95% of the features that most people use. The selection tools aren’t as good, but with layer masks they’ve become obsolete in my experience.
GIMP 2.8 annoys me to no end, however. Changing how files are saved(Oh ho, lets make them EXPORT instead of SAVE now to do the exact same thing. It’s a pure limiting distinction, doesn’t help anything), as well as it broke all tablet support. So, I have 2.6, which is still a great version, and what I recommend.
Ugh…
“You can use this dialog to save to the GIMP XCF format. Use File→Export to export to other file formats.”
If you know what exactly I did wrong and what exactly I should have done instead why don’t you just stop wasting my time and do it?
The distinction serves a purpose. XCF is the format which keeps information about layers, paths, etc., and in versions prior to 2.8 these were lost after saving in a different format and then closing the program.
Ctrl+E is not that much of a change, and you could always switch the keyboard shortcut to Ctrl+S.
I find it amusing that people prefer an out-dated version only to avoid a simple interface change, which can easily be reverted.
Paint.net allows you to save in its proprietary format, that keeps all the layers etc. (.pdn), and in any other format you want, through the normal ‘save as…’ option. Quicksave (‘save’, ctrl+s) saves the file *in the format it is currently open as*.
I don’t see how that is any less logical, or indeed less convenient that setting all save options only as proprietaries and stuff like png, jpeg, bmp and so on as ‘export’.
You only have a shortcut to the latest saved format instead of both an image format and the editors format at the same time.
I still have the belief that Linux is best suited for running servers, very specific applications (you can do some cool stuff on embedded systems these days), or tinkering. Windows, unfortunately, for me is still the best “I need to do a bit of everything on my desktop” OS. Of course MS is continuing to sweep power-user features under the carpet, so maybe that will change in a few years.
While you’re going through this, I decided that my birthday gift to myself would be to spend the time to learn how to be proficient with Vim. I struggled with whether or not it’d be worth it. But I decided that I could make Vim be the text editor I use nearly always, so I’m forging ahead. (As opposed to your MySQL example, where you just won’t be using it enough to remember the commands.) As you’d probably expect, it’s really difficult unless you make the effort to get to know it. Once you do, it actually is very rewarding.
I’m glad to see WINE worked out for you. I don’t think I’ve ever had it work for me, for even the simplest applications. That’s one of the reasons I keep Windows on my laptop and only use Linux in a virtual machine.
Merry Christmas!
Merry Christmas!
Merry Christmas! Честита Коледа!
If you ever decide that PSP is insufficient to your needs, I’ll recommend Photoshop Elements. Priced for the (higher) mid-market, it has most of the tools that you need unless image manipulation is your job.
Frankly, even a professional photographer can usually get away with Elements and Lightroom, never using full Photoshop at all.
Ah, Paint Shop Pro. I used PSP7 for years. Until I got an art tablet, which is easier to use with my Photoshop. I still whip it out now and again for certain small things I can do faster or easier with it.
The mid-tier art programs market has really died while I wasn’t paying attention? Damn. *Is sad* I’d better keep a strong and careful hold on my PSP7 disc.
Shamus, I can highly recommend Guake, a terminal emulator for Linux that is accessed by hitting F12 at any time. The terminal drops down from the top of the screen, id Tech/Source style.
Other people have said all this but I will say it as well:
1) On windows atleast, Paint.net is da bomb for mid-range image editing/manipuation. Use when infanview wont cut it and you CBA open photoshop.
2) There are many programs to give your linux desktop a quake style terminal.
3) For mysql, use phpmyadmin. You had apache and php installed anyway right?
4) Wish I got to spend Christmas day coding.. 8-p
Indeed I take Guake for granted until I go to use it on a computer that doesn’t have it!
Shamus this is “a bit late in the game” but did you look at possibly using as the GUI with (a lightweight 2D rendering engine for when you don’t need 3D rendering) example:
I did. I looked at several. Of course, I can’t remember the details of each or what I did/didn’t like about each of them now.
*nod* Myself I’m leaning towards writing my own Windows / Linux GUI lib (none of the current GUI’s seem to be close to what I need.)
Try “Gimpshop”. It’s GIMP with some UI tweaks to make it less shit. It even has a plugin called “deweirdifier” that consolidates the millions of separate windows into just 3.
GIMP already has a single-window mode. And the “millions of separate windows” in multi-window mode have always been three by default. I don’t see the benefit of Gimpshop in this day and age.
GIMP’s interface reminds of when I downloaded Blender to see if it would satisfy my video needs.
If you know what you are doing, it’s a very powerful tool. If you are a noob, it’s a nightmare of menus and buttons. And the tutorials are like you described in a an earlier post, devoted to one specific task, good luck figuring out a “not quite the same” scenario.
Hi Shamus, long time reader, first time poster.
The compiling thing is annoying indeed, especially when trying to satisfy the dev dependencies for a package, but apt has your back!
sudo apt-get build-deps packagename
will install all the development libs you need for compiling (there may not be a hyphen in build-deps, check the manpage with “man apt-get”)
Stick with Linux, Ubuntu and its derivatives especially have a really helpful community! =) I picked up Ubuntu 3 years ago and haven’t looked back, apart from gaming. Linux is like heaven for programmers! =)
All the best,
Christy
In the IDE section: “The above is very rudimentary and probably factually correct in places.” Should be “The above is very rudimentary and probably factually incorrect in places.”
“An interesting problem I like to think about: How can you use the GUI to teach the user to use the command line?”
Maya (a 3D modeling package) actually does this for scripting. Maya uses a proprietary language called Mel Script (though they actually have hook ins so you can code directly in Python as well now) which can allow you to do all the basic manipulations of objects as well as more complicated tasks like creating interfaces, loops, etc.
In their console editor, they echo all commands executed by the user in Mel Script. So as a budding scripter, if you wanted to figure out how to set translation values on an object through script, you could simply set those values using the GUI editor and it would print out the script line for manipulating that object to whatever values you set. From there its pretty easy to reverse engineer the script and create code to, say, run the same translation offset on an array of selected objects.
“How can you use the GUI to teach the user to use the command line?”
This, exactly.
A good user interface will educate the user and let them do the things in whichever way they feel is appropriate.
Doing this with a command line interface is not all easy, though.
Some good python IDEs have a “namespace browser” that will give you all existing names (including names of commands) in a tree complete with explanation — but i know no incarnation of this for the Linux console.
What I have found to be helpful are these things: “man [somecommand]” will give you the manual page for some command in the terminal. But entering “man:[somecommand]” in the adress line of the file manager will give you that man page in a graphical window where you can search for strings, click on stuff, have some yntax highlighting, and it can sit next to the terminal window where you are still trying to work out all the necessary arguments. At least with KDE, alt+F2 will open a single command line where you can put any command, web or local file adress or again said man:[something] and get the same result.
That and the mouse buffer (select with the mouse, insert with middle click make living with the console much easier
For selecting to the beginning (or end) of a line, I just use shift+home (shift+end), and to the beginning of the whole text shift+ctrl+home (shift+ctrl+end).
holding ctrl will enable you to move (and with shift select) the cursor word by word.
… I know, though, how difficult changing habits can be. Whenever I’m on windows I try and paste URLs or filenames with just a middle click and then realize I forgot to do the crtl+c/ctrl+v dance. | http://www.shamusyoung.com/twentysidedtale/?p=18111 | CC-MAIN-2017-39 | refinedweb | 8,161 | 71.04 |
Creating a JAMstack Site with Open Authoring Using Netlify CMS
Community is powerful. The internet has often succeeded by channeling that power into "crowdsourcing" for things like raising funds or even managing content. The most obvious example of crowdsourced content would be Wikipedia, but sites like Medium or DEV also harness community-driven content contributions. Many projects and companies also rely on their communities to improve their documentation.
When it comes to JAMstack sites, this community-driven content is often powered by straight GitHub forks and pull requests. This works well but requires a certain degree of technical knowledge as well as a bit of manual work (pulling the code, making the change, committing it, submitting the pull request and so on). This can be a real hindrance - especially if your goal is to get contributions from folks without a high degree of technical expertise.
However, a new feature of Netlify CMS called open authoring makes this process as easy as editing content directly in the CMS - the forking and pull requests are all handled behind the scenes. In this post, I'm going to walk through the steps to set up open authoring using Netlify CMS on a site built originally with Stackbit.
What is Netlify CMS and Open Authoring?
Netlify CMS is an open source project maintained by Netlify. It is what's often called a git-based CMS. As a git-based CMS, Netlify CMS provides the UI and tools to maintain the content, but the content itself is stored as files within a git repository and versioning is handled by the repository. Under a typical deployment, user access might be managed by Netlify Identity (or a third-party integration) and you'd invite contributors who are granted access to your CMS admin to edit content. You might have a workflow in place, but editing content is still limited to a small group with specially granted access.
With a site designed to have "crowdsourced" content, you'd need access to be public so that anyone could submit content, but you'd also need to ensure that changes are reviewed and approved before going live. To address this, Netlify CMS released open authoring, which is currently a beta feature only. I first learned of the feature when CSS Tricks adopted it for editing some of their community-driven pages.
Here's a quick overview of how it works. Open authoring uses GitHub authentication, meaning essentially that anyone with a GitHub account can add or modify content on your site. Content edits are work by creating a fork of your project and, when they submit their change for review, submitting as a pull request. However, while the whole fork and pull request process underpins the feature, it is (mostly) transparent to the user who simply makes changes to the content in the CMS. This means that, other than requiring a GitHub account, contributing content should be easily accessible to anyone, regardless of their level of technical knowledge.
The Example Site
The example we'll review for this tutorial is a site I just launched called RageQuit.tips that is designed to be community resource on the topic of burnout. Burnout is defined as "exhaustion of physical or emotional strength or motivation usually as a result of prolonged stress or frustration." It is generally associated with job stress and is something that many of us have faced, regardless what industry we work in. The idea for the site is to allow the community to share experiences and resources related to dealing with burnout.
If you are interested in the topic of burnout, please check it out. And if you have experiences or resources you'd like to share, I invite you to contribute.
The site was built using the following technologies:
- Stackbit
- Stackbit allowed the site and CMS to be easily generated using a theme, which was later customized to meet the site's specific needs.
- Jekyll
- The underlying static site generator is Jekyll . This was chosen to make source contributions easier as it is one of the oldest and most widely known static site generators.
- Netlify CMS
- As mentioned earlier, this is an open source, git-based CMS.
- Netlify
- Netlify is used to deploy and host the site, but also maintains the hooks needed to authenticate into the CMS via GitHub.
- GitHub
- GitHub manages the repository but also handles the authentication.
Using this site's code as an example, let's explore the steps to enable open authoring on a Netlify CMS site.
Getting Started
Stackbit provides a great tool that makes it easy to get started with a CMS-driven JAMstack site, including Netlify CMS. The best part, for the design-impaired like me, is that it comes with selection of attractive templates. I won't run through the process too deeply here, but basically you choose a theme, then a static site generator and finally a CMS. You can try it out for yourself here.
I picked Jekyll as the static site generator and, obviously, Netlify CMS. I chose Libris as the theme. Libris is designed as a documentation site template that also has a blog. This worked well for the resources section and blog I was planning.
Out of the box, Stackbit deploys a fairly standard Netlify CMS configuration. So, once the deployment has finished, you will get the invitation email to collaborate on the content via Netlify CMS.
Resolving a Limitation
Before we proceed, I want to point out an issue that may trip you up as it did me initially. If you were to go ahead accept this invite and log in (though we will be changing the authentication later to support open authoring), you may notice a limitation of this template when using Netlify CMS. The "Documentation Pages" section displays no pages even though the repository has a number of pages. This is because, at the moment, collections in Netlify CMS do not support content in subfolders, although this is a feature that should be added soon.
There are two potential solutions to this in the meantime. The first is to move documentation pages to the root of the the
docs folder. Then make a small change to the Netlify CMS configuration to look for documentation pages in the
docs folder rather than via the root of the site (it's preconfigured to look for any page across the site having
layout: docs in the front matter).
- name: docs label: Documentation Pages folder: docs ...
The biggest drawback to this is that you'll also need to make changes to the documentation layout files to support this change. In particular, you'll need to modify how the templates generate the navigation of documentation sections.
The second solution, which is what I chose to do, is to make the change above and then duplicate the model for each subfolder in the Netlify configuration. You'll need to change the
name,
folder, and
label values for each. So, for example, you might have the following as an additional content model:
- name: docs_faq label: Docs FAQ Section folder: docs/faq ...
While harder to maintain, the benefit of the second solution is that you can retain content in subfolders and avoid making difficult layout changes. In theory, once Netlify CMS supports this feature, you can just remove all the additional models.
Configuring Netlify CMS for Open Authoring
Firstly, open authoring is a beta feature. So we need to change the project to use the beta release of the project. Open up
admin/index.html and replace the source for
netlify-cms.js with the beta release.
<script src=""></script>
Next, open authoring requires that we use GitHub authentication for the backend. So let's modify the Netlify CMS configuration for this and then enable open authoring. Open
admin/config.yaml and change the
backend to use
github rather than the
git-gateway and define the associated
repo (note that the
repo value does not need the
github.com portion). Also add a value for
open_authoring and set it to
true. When you are finished, your
backend should look something like this:
backend: name: github branch: master repo: remotesynth/ragequit-tips open_authoring: true
The next change you'll need to make in the config is to change to an editorial workflow. This means that content must go through a review and approval process before being published. Because of the way open authoring works, this is required. In the root of the
config.yaml file add
publish_mode and set it to
editorial_workflow. For instance, mine is right above
collections and below the
public_folder.
--- media_folder: images public_folder: /images publish_mode: editorial_workflow collections:
You'll also need to enable GitHub authentication via the visitor access settings in your Netlify admin console. To do this, first you'll need to set up an OAuth app in GitHub. In GitHub, go to Settings > Developer Settings > OAuth Apps. You'll need to provide a name and a URL (you can use your netlify.com domain if you like for now) and an authorization callback URL that should be set to.
This should give you a client ID and secret, which you'll need to copy into Netlify.
Next, in Netlify, go to Settings > Access Control > OAuth and then click the install provider button. It should default to GitHub and here you can paste in the client ID and secret provided by GitHub.
If you commit these changes or test locally and go to your site's
admin, you'll get the log in with GitHub option instead of log in with Netlify. After clicking that, you'll have to grant the site access via the GitHub OAuth process, but then you should have complete access to your admin as you did before. Note, though, that due to the editorial workflow, you'll need to save and then set the status to "Ready" before hitting "Publish" and pushing your change live.
That's it! Open authoring is now enabled and anyone can access your
/admin and add or edit content. Their experience will be slightly different than yours though, so let's take a look at that.
The End User Experience
Assuming someone now accesses your
/admin, what's the experience going to be like?
When they get to the admin, they'll be prompted to log in with GitHub, same as you were. They can use an existing account or create one, and they will have to accept the permissions on their account.
Once they do, if this is the first time they are making edits, they will be asked to fork the repository. They will need to agree to fork it to proceed into the admin. (Note that I do think this language could be improved for non-technical users who may not be familiar with terms like "fork" but who sign up for GitHub to contribute nonetheless. I also think it could be useful to clarify that the the "Don't fork the repo" option is effectively a choice not to proceed.)
Once they accept and enter the admin, they'll need to follow the workflow to add or edit pages. For instance, to edit a page, they would make their edits and click the "save" button in the upper-left hand corner of the page.
Once they've completed all of their changes, they will need change the status of the content to "In Review" via the drop-down in the upper-right hand corner of the page.
This will submit the changes to be reviewed and accepted into the site as a pull request in GitHub, although that will be transparent to them. Adding new content follows a similar flow.
Making It Easy to Edit Pages
It's unlikely you'll want to just dump folks into the
/admin and let them figure things out. The best bet is to drop links on content that leads them directly to the pages they may want to edit or create in the CMS.
The good news is that this is just requires linking to the right spot in the
/admin. It's just a matter of ensuring that the link goes to the proper collection or page within the CMS. For example, let's say you want a link to add a new post to the blog, you could use:
<a href="/admin/#/collections/post/new" class="button">Add a Post to Our Blog</a>
This works because there is a collection with
name: post in the
config.yml for Netlify CMS. If you wanted to edit the specific blog post, you'd put the file name (through without the extension) instead of
new in that URL path. Most static site generators offer page variables that could do this. In Jekyll, you could do:
<a href="/admin/#/collections/post/{{page.name | replace: ".md", ""}}" class="button">Edit this post</a>
Let's look at one more example of something slightly more complicated. As you may recall from much earlier in this post, in my case, I created a number of content mappings comprising the resources section of RageQuit.tips. In this section, I wanted you to be able to edit any existing page or add a page to the current section. The way I did this without needing to create a different layout template for each subsection was to standardize how the sections were named in the config based upon their subfolder. So, for example,
/resources/faq would be defined as a content model of
resources_faq in the CMS. I could then replace text within the path and link to the correct section in the CMS.
{% assign collection_path = page.path | replace: '.md', '' %} {% assign collection_array = collection_path | split: "/" %} <!-- the root content model name is just resources so checking if we aren't in the root --> {% if collection_array.size >= 3 %} {% assign collection_path = collection_path | replace: "resources/", "resources_" %} {% endif %} <!-- this is used to swap out the page name with new for the new post link --> {% assign page_cms = page.name | replace: ".md", "" %} <p> <a href="/admin/#/edit/{{collection_path}}" class="button">Edit this page</a>{% if collection_path != "resources/index" %} <a href="/admin/#/collections/{{collection_path | replace: page_cms, 'new'}}" class="button" >Add a New Page to This Section</a >{% endif %} </p>
You can see more details about the current end-user editing experience in the RageQuit.tips contribution guide.
A Powerful Tool for Enabling Community Contribution
Open authoring in Netlify CMS is a really great addition. I think it has some rough edges that might hinder non-technical users from contributing - things like the GitHub account requirement and the prompt to "fork", for instance. It is a beta feature after all. However, despite what the length of this post might imply (verbosity is my core competency), it's actually surprisingly easy to implement and use.
If you want to see the full source code of the demo I referenced, which includes all the necessary updates to the Netlify CMS content model and a number of other tweaks to the Stackbit generated template, you can view it on GitHub.
With all that being said, I'd also like to invite you to contribute to RageQuit.tips. This isn't just a demo site, it's meant to be a true community resource for anyone coping with burnout. If you've experienced burnout, share resources that helped you or add your story to the blog. We can use our experiences to help others who may be coping with similar struggles. Leverage the power of the community by creating a JAMstack site that anyone can edit and contribute using NetlifyCMS's open authoring. | https://www.stackbit.com/blog/open-authoring-netlifycms/ | CC-MAIN-2022-05 | refinedweb | 2,596 | 61.26 |
Distribute Web Apps
You can build and distribute web applications created with the Data Inspector Library components in a number of ways, as explained below.
Note: HERE Copyright Notice
Be aware that, according to HERE terms, if your products and/or services use map data that is made accessible through HERE Services, you need to show the (c) 20XX HERE copyright statement (where XX denotes the current year). Make sure that this statement is clearly visible on the map and is linked to the HERE SUPPLIER TERMS APPLICABLE TO LOCATION CONTENT page:.
Run a web app on a local HTTPS web server and enable external access to this server if needed.
Note: Limitation on using an HTTP web server
The use of a local HTTP web server instead of HTTPS to share web applications has a limitation: it can work only in Firefox. There is no limitation for local development because localhost has a special security policy. For more info, see the option below.
Share a web app through a local network.
The Data Inspector Library includes
UserAuthFormused for user authentication and depends on
Web Crypto APIthat is available via a browser's
crypto.subtleproperty. Some browsers (for example, Google Chrome) may not allow the usage of the
Web Crypto APIfor non-secure origins. So, to be able to use custom applications via a local network, the Data Inspector Library provides
Generic Token Requester.
The example below shows how you can use it with the
DataInspector:
import { DataInspector, requestToken } from "@here/interactive-mapview-ui"; ... const dataInspector = new DataInspector({ ... widgets: { ... authForm: { ... tokenRequester: requestToken } }, ... });
Share a web app as a ZIP archive with the source code.
To run the web app, you need to set up and configure your environment as described in the Prerequisites chapter.
Build a static web page and distribute it as an archive.
Currently, this works only in Mozilla Firefox or Microsoft Edge, since Google Chrome does not support web workers and CORS requests from web pages served from a local filesystem. Static web pages should be served by a local web server to work in Chrome.
Integrate the Data Inspector as a component in another web app.
The Library does not use the global scope and, therefore, does not interfere with any external code.
Bundle a static web page as a cross-platform desktop application.
You can use Electron to do this. | https://developer.here.com/cn/documentation/data-inspector-library/dev_guide/pages/distribution.html | CC-MAIN-2020-29 | refinedweb | 395 | 53.61 |
I've been working, on and off, with fRiSi on a resolution to this issue:
Advertising
I'm feeling like I need some backup from someone with a better understanding of i18n than I currently possess. Is there anyone on list who'd like to look at that issue and fRiSi's and my comments and perhaps suggest a proper fix for the current issue? The problem I'm having is that the issue with CMFPlone fRiSi pointed to on the ticket seems to me to indicate that the portlet's title and description need to be in the 'plone' i18n namespace in order to have them appear in the @@manage_portlets view as translated. However, our current solution puts them in the namespace of the newly created package. This brings up some interesting problems. Can we have more than one i18n namespace for a package? Is having more than one a good idea? If not, should all translations for the new package be in the plone namespace if there's a portlet present? Am I just missing something obvious and over-thinking the whole problem? I'd appreciate any advice someone with solid i18n experience might be able to provide. | https://www.mail-archive.com/zopeskel@lists.plone.org/msg00029.html | CC-MAIN-2017-51 | refinedweb | 200 | 69.01 |
By Jakob Lind, @karljakoblind.
How many of your users access every single page of your app, or use every single feature of your site?
It’s probably only you and your integration tests.
Most of your users have a specific goal. For example, one user might want to browse your product catalog only to see what you have in your webshop. He is not ready to buy yet and will not see your checkout. And he will not click the “show reviews” tab on the product pages.
With one bundle for the whole app, this user has to download code that he will never run.
If you want to make fast sites, you must send as little JavaScript as possible to the browsers. Not only does it take time to download the JavaScript bundle, but the browser also has to extract the code and parse it — which also takes lots of time.
Slow sites make users leave. And it’s also bad for SEO — Google rewards quick sites.
What you should be doing is to send only the JavaScript the user needs for viewing and interacting with the pages he visits — nothing more or less. That way, the site will load much quicker and your users get a much better experience.
Well, guess what — it’s possible with webpack and dynamic imports.
When you use dynamic imports, you serve just the bare minimum of JavaScript on page load and serve the rest dynamically when (and if) the user needs it.
How to configure webpack dynamic imports
Dynamic loading sounds nice, but how do you configure your webpack project to support it?
There is actually no webpack configuration involved at all because dynamic imports work out-of-the-box in webpack 2 and later (if you are still on webpack 1, now is a good time to upgrade). You don’t have to do any configuration at all in your
webpack.config.js to get it to work.
What you do need to do however is to configure Babel. You also need to write your code that handles imports with a slightly new syntax. We will come back to that syntax later. First, let’s look into Babel.
Dynamic import is a TC39 proposal in stage 3. Stage 4 is the “finished” stage, so it’s getting really close to becoming a standard. Because it’s still a proposal, browsers do not support it yet. So, to get it to work, you need to configure Babel to transpile your dynamic imports.
To do that, you first need to install the Babel plugin
plugin-syntax-dynamic-import:
npm install --save-dev @babel/plugin-syntax-dynamic-import
And then use it in the
.babelrc file:
{ "plugins": ["@babel/plugin-syntax-dynamic-import"] }
The syntax for dynamic imports
Now that you have configured Babel, you can use dynamic imports in your project. Before I describe how to do that, let’s see how an import looks like that is not a dynamic import.
import Text from "./Text"
This line of code should be very familiar to you. When you import this way, you can access the module inside
./Text.js with the new variable
Text. You can access any function in the module right after the import.
With dynamic imports, the statement looks slightly different.
import("./Text").then(Text => { // you can access Text inside here. })
We still use the import keyword, but we don’t assign it to a variable with the from keyword as we did previously. Instead,
import("./Text") returns a promise. And inside that promise, you have access to the module.
What happens under-the-hood is that when you call
import("Text") it makes an Ajax request to fetch only the part of your bundle that contains the bundle Text. The app doesn’t load this bundle until it sees this statement.
This means that, if you put this code in an
onClick handler, the code for the module will not be fetched until the user presses that button.
An example of dynamic imports
Let’s look at how we can use this in an example app. We will use React as an example, but the same principles can be applied to any framework or no framework at all. First, we create the
Text component in
Text.js:
import React from "react"; export default () => <div>This text is loaded dynamically</div>
Next, we will use it in
index.js. Instead of importing it at the top of the file like we usually do, we will import it dynamically inside the root component:
class App extends React.Component { constructor(props) { super(props); this.state = { Text: null } this.loadComponent = this.loadComponent.bind(this); } loadComponent() { import("./Text").then(Text => this.setState({Text: Text.default})); } render() { let { Text } = this.state; return ( <div> <button onClick={this.loadComponent}>Load component</button> {Text ? <Text/> : null} </div> ) } }
When the user clicks the button, the
Text component will be dynamically imported and put in component state.
App renders the
Text component in the
render function.
If you look at the network tab of your browser, you can see that the chunk that includes the
Text component is loaded only when you press the button.
There is less code to fetch on page load, which means a faster load speed!
Now, try this out on your own project. See if you can use dynamic imports to make the size of your entry point bundle go down.
More optimizations for your app
Webpack is a seriously awesome tool that gives the power to you as a dev. It’s great because you have the power to create the app your users need. But that also means you can’t blame someone else if your site starts to get slow.
There are so many things you can do to reduce the bundle size it gets overwhelming. There are millions of optimizations out there. Which one applies to you? Which one gives you the best bang for the buck?
I created a tool that gives you a custom report on what optimizations improvements you should do for your webpack project. This gives you some ideas on where to start optimizing so you don’t have to spend endless days googling and RTFM.
Be sure to try out the webpack optimization tool for your project.
Also, if you're using webpack to bundle applications with sensitive logic, protect them against code theft and reverse-engineering by following our guide. | https://blog.jscrambler.com/how-to-make-your-app-faster-with-webpack-dynamic-imports | CC-MAIN-2022-27 | refinedweb | 1,074 | 74.19 |
What is Array Reverse in Java?
To implement array reverse in Java Programming, the array size and thereafter the array elements have to be entered by the user. In the next step, the array elements are swapped. A variable (temp) of the same type is created for placing the first element in variable temp, then the element coming last is placed in the first, temp is placed in the last, and so forth – the process continues till the entire array is reversed.
In Java, mostly primitive types of arrays - int, long, string and double arrays – are required to be reversed for the purpose of specific codes. Apache commons lang, which is an open source library attributed to the Apache software foundation, provides class ArrayUtils. This interesting class is used in association with the java.util.Arrays class for playing with object and primitive arrays in Java. The API provides easy-to-use overloaded methods for reversing different types of arrays in Java – be it int, log, double, float or object arrays.
Read on to know about this and other methods pertaining to how to reverse an array in java – the right way.
How to Reverse Array in Java with Examples
There are many methods to reverse an array in Java. You may consider writing a function on your own that loops across the array and keep swapping all the elements until the full array is sorted. In another method of array reverse in Java, an array can be converted into an ArrayList, after which a specific code can be used for reversing the ArrayList. Yet another method of array reverse in Java comprises of using the Apache Commons ArrayUtils.reverse() program for the sake of reversing any kind of Java array. This method can be overloaded for the cause of reversing short, long, int, byte, float, double or string type arrays. Users may like to implement any method to reverse an array in java as per their choice and nature of the array in the reckoning.
Method 1: Reverse Array in Place
In this simple means of reversing a Java array, the algorithm is made to loop over the array and keeps swapping the elements until the midpoint is reached. As no additional buffers are used, this method of reversing an array in Java is also referred to as an array in-place.
for(int i=0; i<array.length/2; i++){ int j= array[i]; array[i] = array[array.length -i -1]; array[array.length -i -1] = j; }
The time complexity of the above algorithm is O(n/2). In other words, it is O(N) as the iteration across the loop takes place till its midpoint only. This method provides an ideal solution for interviewees as the remaining two methods are apt for practical purposes.
Method 2 - Using an ArrayList
This particular method of array reverse in Java converts the given array into an ArrayList and then utilizes the Collections.reverse() method that takes up the items in the list and reverses the elements in linear time. Arrays of int, string or other types can be reversed with the help of this method.The following example depicts a reversal of a string type array in Java:
//Simple Java Program to reverse a string array import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class ArrayReverse { public static void main(String args[]) { String[] arrayColor = {"Red", "Green", "Blue", "Orange","Yellow"}; System.out.println("Array Before: " + Arrays.toString(arrayColor) ); List<String> arrayNewColor = Arrays.asList(arrayColor); Collections.reverse(arrayNewColor); String[] reversed = arrayNewColor.toArray(arrayColor); System.out.println("Array Reverse: " + Arrays.toString(reversed) ); } }
Output
Array Before: [Red, Green, Blue, Orange, Yellow]
Array Reverse: [Yellow, Orange, Blue, Green, Red]
As is evident from the output provided above, the original order of elements has been reversed in the final array as returned by the toArray() method of the List class.
Method 3 - By using ArrayUtils.reverse()
Apache commons refers is a collection of numerous utility libraries used for effective Java development. This library is often added by default by coders to their projects with a view of complementing JDK. The Apache Commons Lang offers class ArrayUtils that comprises of overloaded reverse() methods for the cause of reversing int, float as well as object type arrays in Java. This particular method reverses any given array in its place; in other words, a new array is not created for the purposes of array reverse in the Java code.
The following code will aptly depict this method:
import java.util.Arrays; import org.apache.commons.lang3.ArrayUtils; public class Byarrayutilis { public static void main(String args[]) { String[] arraycolor = {"Red", "Green", "Blue", "Orange","Yellow"}; System.out.println("Array before: " + Arrays.toString(arraycolor)); ArrayUtils.reverse(arraycolor); System.out.println("Array after: " + Arrays.toString(arraycolor)); } }
Output
Array Before: [Red, Green, Blue, Orange, Yellow]
Array Reverse: [Yellow, Orange, Blue, Green, Red]
The ArrayUtils class belongs to Apache Commons Lang. Commons-lang3-3.4.jar has to be added into the application's class path for this method to take place. Alternatively, in the case of Maven is being used then the following dependency has to be included in the pom.xml file.
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency>
How do I Print reverse of an array in Java?
At the very onset, values have to be provided to the array that needs to be reversed in Java.
int[] var = { 1, 2, 3 };
Next, the loop counter has to be initialized. This initialization process can take place from within the loop structure. The loop can be defined as:
for (int i = var.length - 1; i >= 0; --i){ System.out.println(var[i]); }
The output is 321 that will be printed to the console.
Conclusion
The above-mentioned methods go a long way in helping coders reverse int & String array in Java. Reverse array in Java can be appropriately implemented in line with the above three methods. In case you have to answer an interview question pertaining to a java program to reverse an array then use the in-place algorithm. The others methods include usage of the ArrayList class and the utility method ArrayUtils.reverse() belonging to the Apache commons lang library. Choose the method that applies to your reverse array in java programming needs in the best possible way! | https://www.stechies.com/reverse-array-java/ | CC-MAIN-2020-29 | refinedweb | 1,064 | 56.35 |
Previous Chapter: Sets and Frozen Sets
Next Chapter: Functions
Next Chapter: Functions
Shallow and Deep Copy
Introduction
As we have seen in the chapter "Data Types and Variables", Python has a strange behaviour - in comparison with other programming languages - when assigning and copying simple data types like integers and strings. The difference between shallow and deep copying is only relevant for compound objects, which are objects containing other objects, like lists or class instances.
In the following code snippet y points to the same memory location than X. This changes, when we assign a different value to y. In this case y will receive a separate memory location, as we have seen in the chapter "Data Types and Variables".
>>> x = 3 >>> y = xBut even if this internal behaviour appears strange compared to programming languages like C, C++ and Perl, yet the observable results of the assignments answer our expectations. But it can be problematic, if we copy mutable objects like lists and dictionaries.
Python creates real copies only if it has to, i.e. if the user, the programmer, explicitly demands it.
We will introduce you to the most crucial problems, which can occur when copying mutable objects, i.e. when copying lists and dictionaries.
Copying a list
>>> colours1 = ["red", "green"] >>> colours2 = colours1 >>> colours2 = ["rouge", "vert"] >>> print colours1 ['red', 'green']
As we have expected, the values of colours1 remained unchanged. Like it was in our example in the chapter "Data types and variables", a new memory location had been allocated for colours2, because we have assigned a complete new list to this variable.
>>> colours1 = ["red", "green"] >>> colours2 = colours1 >>> colours2[1] = "blue" >>> colours1 ['red', 'blue']
In the example above, we assign a new value to the second element of colours2. Lots of beginners will be astonished that the list of colours1 has been "automatically" changed as well.
The explanation is that there has been no new assignment to colours2, only to one of its elements.
Copy with the Slice Operator
It's possible to completely copy shallow list structures with the slice operator without having any of the side effects, which we have described above:
>>> list1 = ['a','b','c','d'] >>> list2 = list1[:] >>> list2[1] = 'x' >>> print list2 ['a', 'x', 'c', 'd'] >>> print list1 ['a', 'b', 'c', 'd'] >>>But as soon as a list contains sublists, we have the same difficulty, i.e. just pointers to the sublists.
>>> lst1 = ['a','b',['ab','ba']] >>> lst2 = lst1[:]
This behaviour is depicted in the following diagram:
If you assign a new value to the 0th Element of one of the two lists, there will be no side effect. Problems arise, if you change one of the elements of the sublist.
>>> lst1 = ['a','b',['ab','ba']] >>> lst2 = lst1[:] >>> lst2[0] = 'c' >>> lst2[2][1] = 'd' >>> print(lst1) ['a', 'b', ['ab', 'd']]
The following diagram depicts what happens, if one of the elements of a sublist will be changed: Both the content of lst1 and lst2 are changed.
Using the Method deepcopy from the Module copyA solution to the described problems is to use the module "copy". This module provides the method "copy", which allows a complete copy of a arbitrary list, i.e. shallow and other lists.
The following script uses our example above and this method:
from copy import deepcopy lst1 = ['a','b',['ab','ba']] lst2 = deepcopy(lst1) lst2[2][1] = "d" lst2[0] = "c"; print lst2 print lst1If we save this script under the name of deep_copy.py and if we call the script with "python deep_copy.py", we will receive the following output:
$ python deep_copy.py ['c', 'b', ['ab', 'd']] ['a', 'b', ['ab', 'ba']]
Previous Chapter: Sets and Frozen Sets
Next Chapter: Functions
Next Chapter: Functions | http://python-course.eu/deep_copy.php | CC-MAIN-2017-09 | refinedweb | 613 | 58.82 |
A class is a user-defined type where the programmer can specify the representation, the operations, and the interface. The C++ core guidelines have a lot of rules for user-defined types.
The guidelines start with quite general rules but also include special rules for constructors and destructors, class hierarchies, overloading of operators, and unions.
Before I write about the special rules that are way more interesting, here are the eight general rules.
struct
class
I will only write as much to the general class rules to make their intention clear.
If data is related, you should put it into a struct or class; therefore, the second function is very easy to comprehend.
void draw(int x, int y, int x2, int y2); // BAD: unnecessary implicit relationships
void draw(Point from, Point to); // better
An invariant is a logical condition that is typically established by a constructor.
struct Pair { // the members can vary independently
string name;
int volume;
};
class Date {
public:
// validate that {yy, mm, dd} is a valid date and initialize
Date(int yy, Month mm, char dd);
// ...
private:
int y;
Month m;
char d; // day
};
The class Date has the invariants y, m, and d. They are initialised and checked in the constructor. The data type Pair has no invariant; therefore it is a struct.
Due to the invariant, the class is easier to use. This is exactly the aim of the next rule.
The public methods are in this case the interface of a class and the private part is the implementation.
class Date {
// ... some representation ...
public:
Date();
// validate that {yy, mm, dd} is a valid date and initialize
Date(int yy, Month mm, char dd);
int day() const;
Month month() const;
// ...
};
From a maintainability perspective, the implementations of the class Date can be changed without affecting the user.
If a function needs no access to the internals of the class, it should not be a member. Hence you get loose coupling and a change of the internals of the class will not affect the function.
Such a helper function should be in the namespace of the class.
namespace Chrono { // here we keep time-related services
class Date { /* ... */ };
// helper functions:
bool operator==(Date, Date);
Date next_weekday(Date);
// ...
}...if (date1 == date2){ ... // (1)
Thanks to argument-dependent lookup (ADL) the comparison in (1) will additionally look for the identity operator in the Chrono namespace.
I admit: defining a class and declaring a variable of its type in the same statement confuses me.
// bad
struct Data { /*...*/ } data{ /*...*/ };
// good
struct Data { /*...*/ };
Data data{ /*...*/ };
This is a quite useful and often used convention. If a data type has private or protected members, make it a class.
This rule is also called data hiding and is one of the corner stones of object oriented class design. It means that you should think about two interfaces to your class. A public interface for the general use case and a protected interface for derived classes. The remaining members should be private.
I will continue with the more special rules. Here is an overview:
Let's continue with the two rules to concrete types.
First of all, I have to write about concrete types and regular types.
A concrete type is "the simplest kind of a class". It is often called a value type and is not part of a type hierarchy. Of course, an abstract type can not be concrete.
A regular type is a type that "behaves like an int" and has, therefore, to support copy and assignment, equality, and ordering. To be more formal. A regular type Regular supports the following operations.
Regular a;
Regular a = b;
~Regular(a);
a = b;
a == b;a != b;
a < b;
The built-in types are regular such as the container of the standard template library.
If you have no use-case for a class hierarchy, use a concrete type. A concrete type is way easier to implement, smaller and faster. You have not to think about inheritance, virtuality, references or pointers including memory allocation and deallocation. There will be no virtual dispatch and, therefore, no runtime overhead.
You just have a value.
Regular types (ints) are easier to understand. They are per se intuitive. This means if you have a concrete type think about upgrading it to a regular type.
The next post will be about the lifetime of objects: create, copy, move, and destruct. 7803
Yesterday 6384
Week 7803
Month 166234
All 5035548
Currently are 170 guests and no members online
Kubik-Rubik Joomla! Extensions
Read more...
You have touched some nice points here. Any way keep up wrinting.
articles. Ι will bookmark үour blog and check аgain hеre frequently.
Ӏ'm quite suгe I wіll learn mаny new stuff right here!
Best of luck for the next!
I have got you bookmarked to check out new things you post… | http://www.modernescpp.com/index.php/c-core-guidelines-class-rules | CC-MAIN-2020-50 | refinedweb | 805 | 66.64 |
On Jun 18, 6:29 pm, Nick Craig-Wood <n... at craig-wood.com> wrote: > Karthik <karthik301... at gmail.com> wrote: > > Hello Everybody, > > > I'm trying to create a packed structure in ctypes (with one 64-bit > > element that is bitfielded to 48 bits), > > unsuccessfully: > > > =================================== > > from ctypes import * > > > class foo (Structure): > > _pack_ = 1 > > _fields_ = [ > > ("bar", c_ulonglong, 48), > > ] > > > print("sizeof(foo) = %d" % sizeof(foo)) > > =================================== > > I'm expecting that this should print 6 - however, on my box, it prints > > 8. > > > The following piece of C code, when compiled and run, prints 6, which > > is correct. > > =================================== > > struct foo { > > unsigned long long bar: 48; > > }; > > > printf("sizeof(foo) = %d", sizeof(foo)); > > =================================== > > > So... what am I doing wrong? > > I compiled and ran the above with gcc on my linux box - it prints 8 > unless I add __attribute__((__packed__)) to the struct. > > I'm not sure that using bitfields like that is a portable at all > between compilers let alone architectures. > > I'd probably do > > from ctypes import * > > class foo (Structure): > _pack_ = 1 > _fields_ = [ > ("bar0", c_uint32), > ("bar1", c_uint16), > ] > def set_bar(self, bar): > self.bar0 = bar & 0xFFFFFFFF > self.bar1 = (bar >> 32) & 0xFFFF > def get_bar(self): > return (self.bar1 << 32) + self.bar0 > bar = property(get_bar, set_bar) > > print "sizeof(foo) = %d" % sizeof(foo) > f = foo() > print f.bar > f.bar = 123456789012345 > print f.bar > > Which prints > > sizeof(foo) = 6 > 0 > 123456789012345 > > -- > Nick Craig-Wood <n... at craig-wood.com> -- Oops, sorry about the missing __attribute__((packed)) - that was an error of omission. Thank you, Nick :) I'm looking at some C code that's using bitfields in structs, and I'm writing python code that "imports" these structs and messes around with them - unfortunately, I'm not at liberty to change the C code to not use bitfields. Your solution works fine, so that's what I'm going to use. Thanks, Karthik. | https://mail.python.org/pipermail/python-list/2009-June/540937.html | CC-MAIN-2016-40 | refinedweb | 303 | 73.58 |
Hi Sorry to take so long: I've spent a week watching paint dry, so I can confirm that this is more interesting. Jon Cast wrote: > > Con. That's a fair point. As these fieldy things are two monoids plus distributive laws, they deserve special recognition. Do they have a name (semirings, or something?). Generally speaking, (return (), (>>)) seems to be just one instance of the fact that if m is a monad and x is a monoid wrt (zero, plus), say, then (m x) is also a monoid wrt (return zero, liftM2 plus). It's the ability to push application under m (with appropriate laws) which makes this possible: monads are just one structure which allows this to happen. A non-monadic example: [IO Int] has {zero = [], plus = (++), one = return (return 0), times = liftM2 (liftM2 (+))} with distributive laws etc, but ([] . IO) is not monadic. > >> This is basically an unfortunate consequence of some design choices in the class system, rather than a good thing per se. Pragmatically, it's really annoying, at least to me, that I can't classify both of these monoid structures as monoids, in order to use monoid-generic operators (e.g. flattening) on either. I can't help thinking that newtype offers a better workaround than making the monoidal aspect of MonadPlus not a Monoid. But I would prefer to have some way to be more specific about choice of monoid (indeed of instance, generally) in some localized way. Merry Christmas Conor | http://www.haskell.org/pipermail/haskell-cafe/2003-December/005640.html | CC-MAIN-2014-41 | refinedweb | 246 | 63.9 |
.BufferedReader ;58 import java.io.IOException ;59 import java.io.OutputStream ;60 61 public class CLStdIOHandler implements CLIOHandler {62 63 private String prompt = ">";64 65 public void write(OutputStream out, String message, boolean doPrompt) throws IOException {66 write(out, (message).getBytes());67 if (doPrompt) {68 write(out, (prompt + " ").getBytes());69 }70 }71 72 public void write(OutputStream out, byte[] b) throws IOException {73 for (int i = 0; i < b.length; i++) {74 out.write(b[i]); 75 }76 77 out.flush();78 }79 80 public String read(BufferedReader in) throws IOException {81 return in.readLine();82 } 83 84 public void setEcho(OutputStream out, boolean echo) throws IOException {85 }86 87 public void setPrompt(String prompt) {88 this.prompt = prompt;89 }90 91 }92
Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ | | http://kickjava.com/src/org/lateralnz/common/cli/CLStdIOHandler.java.htm | CC-MAIN-2018-05 | refinedweb | 138 | 60.92 |
std::int_least32_t, and used to keep track of the sum of all the numbers you’ve seen so far. The second should be of type std::int_least8_t, and used to keep track of how many numbers you’ve seen so far. You can divide them to find your average.
std::int_least32_t
std::int_least8_t
2a) Write all of the functions necessary for the following program to run:
and produce the result:
4
6
12
6.5
7
7
Hint: Remember that 8 bit integers are usually chars, so std::cout treats them accordingly.
char
std::cout std:
For question 3 I wrote a private member function to copy the array like this:
and called it both from the copy ctor and operator=
My reasoning was that this way I avoid repeating myself and since I initialised the int array with either
or
there shouldn't be any harm in calling delete[] on it. Is there a reason I shouldn't do it this way?
Greetings! For question 4(d), I had a slightly different answer for overloaded unary operator- and operator==;
And;
Are there any advantages/disadvantages to using the above overloads compared to those provided in the solution? Also, I noticed someone below had an issue with their binary operator+ working with anonymous objects (r-values) because they didn't set the function parameters as const. However I am able to get this to work with non-const function parameters and a non-const double typecast overload;
Are you able to enlighten me on why this worked? Seems counter-intuitive to me.
James
For Quiz 3
Maybe it could be pushed to templates?
I need a companion Youtube video to explain it.
3. Quiz 3 Feedback
Did not know how to start on Quiz 3 beyond the first few steps.
Just went straight to the solution.
//This is dynamically allocating a new pointer
int ptr* { new int{} };
delete ptr;
ptr = nullptr;
Too many errors trying to figure things out.
The Quizzes are getting harder to DIY.
+= was not covered explicitly in the earlier Chapter 9 topics.
It is extremely confusing.
."
I hope this is acceptable.
//4
//6
//12
//6.5
//7
//7
//ERROR
//1.E0898 nonmember operator requires a parameter with class or enum type
//You need to place a class in parameters for operator+, it doesn't do integers
//When you overload operator+, are they purely for adding classes?
//2.E049 no operator "/" matches these operands.
//3.Assumed we had to overload + and = separately. You actually don't do that. You just overload +=.
//Why did I think that way? Because x += y is x= x+y.
//4. friend Average& operator+= (int value);
//Average operator += (int value)
//{
// return ((value.m_total + value) / value.m_number);//
//}
//I tried to make it normal function due to Error 3. Chain mistakes. += should be a member function
//Else, C8203 and E0345
//5. C26495 Always intialize a member variable (type.6)
//This peculiar error does not go away until you {} the member variables and Debug.
//Building the program again does nothing.
//6. If you remove the "friend" from the std::ostream, you get E0344 (too many parameters) EO349 (no operator "<<" matches these opearands).
//Why do you still need to "friend" it when it is already a member function?
//It's peculiar logic as I assumed "friend" is for normal functions trying to get access to private member variables.
1. Feedback
For Quiz 1, could you add in parenthesis operators as well?
If you’re overloading assignment (=), subscript ([]), function call (()), or member selection (->), do so as a member function.
If you’re overloading a unary operator, do so as a member function.
If you’re overloading a binary operator that does not modify its left operand (e.g. operator+), do so as a normal function (preferred) or friend function.
If you’re overloading a binary operator that modifies its left operand, but you can’t modify the definition of the left operand (e.g. operator<<, which has a left operand of type ostream), do so as a normal function (preferred) or friend function.
If you’re overloading a binary operator that modifies its left operand (e.g. operator+=), and you can modify the definition of the left operand, do so as a member function. {Seems to be missing this part}
For 4d I am not able to overload operator==
Apparently overloading it manually makes it so there are a total of 3 overloads:
- Arithmetic == Arithmetic
- double = FixedPoint2
- const FixedPoint2 &fp1, const FixedPoint2 &fp2
It works without overloading the operator== for me.
Please post your code and error message. No error should occur when you add this operator.
The error is as mentioned above:
more than one operator "==" matches these operands:
built-in operator "arithmetic == arithmetic"
function "operator==(const FixedPoint2 &fp1, const FixedPoint2 &fp2)"
operand types are: double == FixedPoint2
hope thats all you need.
Your `operator+` doesn't work with temporaries, because its parameters are non-const references. Temporaries can't bind to non-const references, so `FixedPoint2{ 0.75 } + FixedPoint2{ 1.23 }` can't use your operator. Instead, the 2 `FixedPoint2`s are converted to `double`, then the built-in `operator+(double, double)` is used. Then you try to do `double+FixedPoint2`, which is ambiguous.
I feel like I missed something along the line somewhere. In the final program of the review, why does the following work:
but this doesn't:
For some reason when I use the braces, the compiler complains about a narrowing conversion, which doesn't make sense. It should be a valid anonymous class object either way.
C++ can only perform integer arithmetic on full integers, not smaller types. `m_base` is `std::int_least16_t`, so the `-` converts it to an `int`.
Because the `FixedPoint2` constructor wants a `std::int_least16_t` but you're giving it an `int`, the compiler complains, as this conversion could be lossy, which is not allowed in list initialization.
I've updated the solution to use list initialization and casts. Thanks for pointing it out!
Few doubts in the following program:
It's output on my machine:
I am unable to understand what is being called when uniform initialization happens on lines 87 and 90.
Neither of the default constructor nor the copy constructor nor the assignment operator function are called as seen in the output.
Also, I just looked up all special functions provided by C++ in classes and when I delete IntArray(IntArray&&) constructor, lines 82 and 87 show errors but not line 90 (even when I remove the reference). So which function is being called when you do uniform initialization and is it doing deep copy?
For 4c, is it okay to do it like that?
Prefer initialization over assignment. Assignment is more expensive and not always possible.
Assigning to `m_decimal` is ok, because it depends on another member variable, but `m_base` should be initialized in the member initializer list.
Hey, I have a question, in the last lesson you implemented a void function to do the deep copy and then called it within both assignment operator and copy constructor. why is that ? why have you implemented deep copy separately in assignment and copy constructor here ? thanks a bunch.
another thing, please take a look at code below: I deleted implementation of my deepCopy to see if I will get undefined behavior, but I'm getting the same answer everytime,why is that ?thanks again.
any Idea guys ? I'm stuck and struggling here :(.
by the following sentence I mean I get the right output everytime."another thing, please take a look at code below: I deleted implementation of my deepCopy to see if I will get undefined behavior, but I'm getting the same answer everytime".
I'd appreciate any help thanks!
I won't comment on the `deepCopy` function because that lesson should use copy-swap, but lesson updates are on hold right now. Please read up on the copy-swap idiom yourself.
You're leaking memory because `m_arr` is never `delete`d. If you fixed the leak by deleting `m_arr` in the destructor, you'd get undefined behavior.
This definition is also not needed:
You've told the compiler how to cast `FixedPoint2` numbers into doubles, and it'll do that on its own without this definition.
You've already overloaded `operator[]`, so you can index `array` directly here:
In fact, if the class had a public member function that told you the array's length (which seems natural to include...) then you don't need to implement the overload of `operator<<` as a friend function at all.
Two questions for exercise 3.
1) The destructor seems to be destructing my code, but code works pretty fine without it.
2) I didn't really need to overload the assignment operator = to make my code work. Why do we have to use it?
1) You're leaking memory which may or may not be cleaned up by your operating system. If you allocate something, you're responsible for freeing it.
2) `a` and `b` point to the same memory. Modifying one affects the other. Deleting them causes a double free, which causes undefined behavior.
Name (required)
Website
Save my name, email, and website in this browser for the next time I comment. | https://www.learncpp.com/cpp-tutorial/chapter-13-comprehensive-quiz/ | CC-MAIN-2021-04 | refinedweb | 1,535 | 65.32 |
Nowadays with Zope you tend to use buildout, and you get loads and loads of eggs, that are namespace packages. WingIDE 3.1 supports name space packages, which is great. Question: Am I correct in thinking that the best way to get WingIDE to find all these eggs is to add each of the to the python path? Or is there a better way? In that case I probably need to write a buildout recipe for WingIDE that creates a custom wingude shell script with the correct PYTHONPATH (unless somebody else already have). -- Lennart Regebro: Zope and Plone consulting. +33 661 58 14 64 | http://wingware.com/pipermail/wingide-users/2008-June/005516.html | CC-MAIN-2016-40 | refinedweb | 104 | 90.39 |
Compute with Images¶
Pictures on a computer are broken up into little bits called pixels, for picture (pix) elements (els). These are laid out on a grid, from left to right (the horizontal or x dimension) and top to bottom (the vertical or y dimension).
Figure 1: A grid with horizontal (x) and vertical (y) dimensions
Pixels are quite small. Even this small picture below has 180 columns and 240 rows of pixels:
Figure 2: Picture of an arch from Oxford, England
csp-1-6-1: Which way does y increase on an image?
- From left to right
- The x value increases from left to right
- From right to left
- The horizontal direction is the x direction
- From top to bottom
- The y value increases from top to bottom
- From bottom to top
- This is common on a Cartesian coordinate system, but it is not true here
Each pixel has a color associated with it: An amount of red, an amount of green, and an amount of blue. The amount can be in the range of 0 to 255 where 0 is none of that color and 255 is the maximum amount of that color. A pixel is displayed using light, not paint, so it may work a bit differently than you might expect if you only have experience making colors by mixing paint. For example, you would mix blue and yellow paint to make green, but you mix red and green light to make yellow light. See for a procedure to try this out for yourself.
All image manipulations in Photoshop and all filters in Instagram or Hipstamatic are created through manipulating those red, green, and blue color components in each pixel.
Let’s remove the red from this picture. The program below does that.
There are lot of lines in the program below. Don’t worry if they don’t all make sense to you right now.
- Especially when we write programs to manipulate images, you can ignore many of the lines. Some read in a library to allow us to work with images, like
from image import *. Others like
win = ImageWin(img.getWidth(),img.getHeight())and
img.draw(win)let us see the result.
- Words after the
#are ignored by the computer. They are comments to human readers to help them understand a program.
The lines that are important are under the comments (lines that start with a
#). Press the
button to hear an audio explanation of the important lines. Press the
button to run the program and show the changed image. Please note that processing all those pixels can take a few minutes.
csp-1-6-2: What do you think happens when you set all the colors to 0? Try adding
- You still see the picture, but it is all in shades of gray.
- Not if you set all the color values to 0.
- The picture is all white.
- Did you try it? This would be true if you set all the values to 255 instead of 0.
- The picture is all black.
- Black is the absence of light so setting all colors to 0 results in an all black image since there is no light.
p.setBlue(0)and
p.setGreen(0)to the program above after the
p.setRed(0)and run it to check.
Note
Discuss topics in this section with classmates. | http://interactivepython.org/runestone/static/StudentCSP/CSPrinTeasers/computeImages.html | CC-MAIN-2018-47 | refinedweb | 560 | 72.87 |
I'm learning Python and I made a simple guessing game and I don't understand why every time I input a number the response is that the number is too low. It only says the number is too high if it's way over the actual number.
I think the problem is in "def Eval(x, y)" somewhere.
It's probably a very stupid error on my part since I'm just beginning to learn.
Here is the code:
- Code: Select all
import sys
import random
def Start():
print 'Welcome to the guessing game.'
print 'Try to guess the number between 1-10'
y = random.randint(1, 10)
Game(y)
def End():
decide = raw_input ('Enter [q] to quit or Enter [n] to play again: ')
if decide == 'q':
sys.exit(0)
elif decide == 'n':
Start()
else:
print 'Sorry that was not a choice.'
End()
def Win():
print 'Congratulations, you are correct!'
End()
def Eval(x, y): # the problem is somewhere here I think
if x == y:
Win()
else:
if x >> y:
print 'y', y # I added these prints to see if there is a problem with x, y. There is no problem.
print 'x', x
print 'Sorry your number is too high'
return
else:
x << y
print 'y', y
print 'x', x
print ' Sorry your number is too low'
return
def Game(y):
x = input ('Guess: ')
Eval(x, y)
print y
x = input ('Guess: ')
Eval(x, y)
x = input ('Guess: ')
Start() | http://www.python-forum.org/viewtopic.php?f=6&t=9336 | CC-MAIN-2016-50 | refinedweb | 241 | 77.77 |
>7513 // Create an shistory entry for the old load, if we have a channel >7514 if (failedChannel) { >7515 mURIResultedInDocument = PR_TRUE; >7516 OnLoadingSite(failedChannel, PR_TRUE, PR_FALSE); >7517 } else if (failedURI) { >7518 mURIResultedInDocument = PR_TRUE; >7519 OnNewURI(failedURI, nsnull, nsnull, mLoadType, PR_TRUE, PR_FALSE, >7520 PR_FALSE); >7521 } >7522 >7523 // Be sure to have a correct mLSHE, it may have been cleared by >7524 // EndPageLoad. See bug 302115. >7525 if (mSessionHistory && !mLSHE) { >7526 PRInt32 idx; >7527 mSessionHistory->GetRequestedIndex(&idx); >7528 if (idx == -1) >7529 mSessionHistory->GetIndex(&idx); >7530 >7531 nsCOMPtr<nsIHistoryEntry> entry; >7532 mSessionHistory->GetEntryAtIndex(idx, PR_FALSE, >7533 getter_AddRefs(entry)); >7534 mLSHE = do_QueryInterface(entry); >7535 } >7536 >7537 // Set our current URI >7538 SetCurrentURI(failedURI); >7539 >7540 mLoadType = LOAD_ERROR_PAGE; >7541 } >7542 >7543 PRBool onLocationChangeNeeded = OnLoadingSite(aOpenedChannel, PR_FALSE); These 30 liens of code calls SetCurrentURI(..) thrice and, what's worse, fires onLocationChange(...) twice (7516, 7519, 7538, 7543), though it's not causing a serious problem atm.
Created attachment 574859 [details] [diff] [review] Fix v1 Note: > mURIResultedInDocument = true; is called right before this block.
Comment on attachment 574859 [details] [diff] [review] Fix v1 > // Create an shistory entry for the old load, if we have a channel >- if (failedChannel) { >- mURIResultedInDocument = true; >- OnLoadingSite(failedChannel, true, false); >- } else if (failedURI) { >- mURIResultedInDocument = true; >- OnNewURI(failedURI, nsnull, nsnull, mLoadType, true, false, >- false); >- } >+#ifdef DEBUG >+ bool errorOnLocationChangeNeeded = >+#endif >+ OnNewURI(failedURI, failedChannel, nsnull, mLoadType, true, false, >+ false); So is it really guaranteed that failedURI or failedChannel is non-null here. The old code has null checks. >- SetCurrentURI(failedURI); >+ MOZ_ASSERT(!errorOnLocationChangeNeeded && >+ "We have to fire onLocationChange again."); Er what? expressiong && const char*
(In reply to Olli Pettay [:smaug] from comment #2) > So is it really guaranteed that failedURI or failedChannel is non-null here. > The old code has null checks. And the newer has the check only on debug build. You mean NS_ENSURE_TRUE is the better? > >- SetCurrentURI(failedURI); > >+ MOZ_ASSERT(!errorOnLocationChangeNeeded && > >+ "We have to fire onLocationChange again."); > > Er what? expressiong && const char* That is to leave a comment on the console on exit. I'm not too sure there's a smarter way, which is compatible with mfbt. BTW, I'm very busy this week. I'm sorry in advance.
Created attachment 605405 [details] [diff] [review] Fix v2 I realized was checked in in January. Anyway, approaching review comments.
Comment on attachment 605405 [details] [diff] [review] Fix v2 Please ping me on IRC if reviewing takes time ;)
(In reply to Olli Pettay [:smaug] from comment #5) > Please ping me on IRC if reviewing takes time ;) hmm, this is an extremely trivial bug, and I know you are always very busy. Generally speaking, it's somewhat difficult for me to send a ping. Besides, I had left out your review comment for 2 months this time...
(In reply to O. Atsushi (Torisugari) from comment #6) > (In reply to Olli Pettay [:smaug] from comment #5) > > Please ping me on IRC if reviewing takes time ;) > > hmm, this is an extremely trivial bug, this is not, which is why it is good if this gets landed early in the FF15 cycle.
Thanks for the patch. Please include a patch description in the future, though.
Sorry, I backed this out on inbound: because this changeset or another one from the same push caused 'make check' failures in Windows debug builds: TEST-PASS | jit_test.py -m -d -n | e:\builds\moz2_slave\m-in-w32-dbg\build\js\src\jit-test\tests\debug\Object-defineProperties-03.js command timed out: 300 seconds without output, attempting to kill We can use the Try server to figure out whether this patch caused the errors. If it does not cause the errors, we can re-land it.
If a test which uses onLocationChange or its bubbles (wrongly) expects docshell fires this event exactly twice, checkin may cause a timeout. is not using onLocationChange, apparently. If the patch is really guilty, it will take some time to find out where to modify.
Which other patches were backed out?
Backing out this patch did not fix the hangs, so I re-landed it. (We ended up fixing the hangs by backing out some other patches.)
Backed out: | https://bugzilla.mozilla.org/show_bug.cgi?id=673752 | CC-MAIN-2017-26 | refinedweb | 678 | 54.73 |
I'm migrating a website made in ASP.NET that was created with Visual Studio 2005 to Visual Studio 2013. When I try to upgrade Infragistics Version 13.1, Version Utility Tools "finds something" that won't let it update the solution. This is the message that I'm getting:
Unknown error (0x80005000) Infragistics.VersionUtilitySupport.Core.File.Types.SolutionFile.ModifySolutionEntrySinceItsUsingIIS(String& solutionFileEntry) at Infragistics.VersionUtilitySupport.Core.File.Types.SolutionFile.Analyze()
Please let me know if you need any files to determine the solution to the problem.
Hello Jesus,
Welcome to the community!
What is the version of the product you are trying to update to 13.1? Are you using the VersionUtility shipped with 13.1 or some previous version of the VersionUtility Tool?
If you are migrating prior to NetAdvantage11.2 version to NetAdvantage 13.1, the version utility will not be of help, as the controls set is built on completely different architecture and the code logic should be changed accordingly. In such case simple change in the referenced assemblies will not be sufficient.
Here is a longshot you could try. Please notice, according our official documentation: “There are three editions of the utility depending on the interface used – a command line interface, an Add-in interface and a Stand-Alone application.” So I suggest you try starting the VersionUtility as a standalone application from All Programs/Infragistics/NetAdvantage13.1. Make sure Visual Studio is not running and navigate to the desired project/site to update.
Also if the product you are trying to migrate is 11.2 or later, you could change the references manually, instead of using the VersionUtility.
Reference to the official documentation:
You could also reference to the following forum thread for details:
Hello Ivaylo, thanks for your answer.
Unfortunately, I don't know what version of the product I'm trying to upgrade, as I've never worked with Infragistics before, and I'm new to the project I'm working on. I was given NetAdvantage_ASPNET_2013.exe to install, though. I tried using the stand-alone application like you said, but the application stopped, claiming that the project had nothing to upgrade. However, I'm not sure if VersionUtility is exactly what I need for my project to work.
Let me explain exactly what the problem is: I was given an ASP.NET website made in vs2005 so I could modify it. I want to open it in vs2013, but when I open it I encounter a couple of errors in the code. Visual Studio doesn't recognize any Infragistics controls. Here's an example:
Inside the <controls> tag there is
<add tagPrefix="igtxt" namespace="Infragistics.WebUI.WebDataInput" assembly="Infragistics2.WebUI.WebDataInput.v10.2, Version=10.2.20102.1011, Culture=neutral, PublicKeyToken=7dd5c3163f2cd0cb"/>
"Infragistics.WebUI.WebDataInput" is what is not recognized. I have other controls that are recognized, only the Infragistics ones are not.
Also, when I try to run the website, I get this error:
Could not load file or assembly 'Infragistics2.Web.v10.2, Version=10.2.20102.1011, Culture=neutral, PublicKeyToken=7dd5c3163f2cd0cb' or one of its dependencies. The system cannot find the file specified. C:\Users\Kibs\Documents\Visual Studio 2013\Projects\slnCFDECO\CFDECO - cfdi QR\Web.config 55
My Web.config's line 55 is <add assembly="Infragistics2.Web.v10.2, Version=10.2.20102.1011, Culture=neutral, PublicKeyToken=7DD5C3163F2CD0CB"/>, which is what I think is the problem. I do not know how to solve this, and thought I would be able to get rid of the error by using the Version Utility. So, any ideas on what I can do?
Let me know if you need to know anything else, and thank you for your time.
It is not possible to upgrade the project using the version utility, as it is as I see from the code shared,using Version=10.2.20102.1011 of our controls. They are different from the controls used in 13.1. They are built on top of different architecture and as such different code logic is used to work with these tools. This includes for example different properties and events. There is no backwards compatibility. So the VersionUtility will not update correctly the references. What is more, even if the references are manually updated to point to the purchased 13.1 version dlls, the project could not be build. This is because the code logic should be completely rewritten. As there are many sources regarding this migration from classic (prior to v11.2) controls, I believe you will find more detailed answer going through the following resources:
Please do not hesitate to ask if you have more questions regarding this.
Hi Infragistics team,
In our project, we are planning to migrate as per below:
1) Win project from v8.2/8.3 to latest version (16.2).
2) WPF v8.2 to latest version (16.2).
3) Asp.net web from v7.2/6.3 to latest version (16.2).
Could you please suggest the best way to migrate in all above cases.
Thanks,
Tarun Parashar | https://www.infragistics.com/community/forums/f/ultimate-ui-for-windows-forms/93195/problem-upgrading-infragistics-version-with-version-utility-tools/517146 | CC-MAIN-2018-13 | refinedweb | 844 | 51.44 |
Revision: 230
Author: mbaas
Date: 2008-02-17 03:08:34 -0800 (Sun, 17 Feb 2008)
Log Message:
-----------
'Abort' feature
Modified Paths:
--------------
cgkit/trunk/cgkit/simplecpp.py
Modified: cgkit/trunk/cgkit/simplecpp.py
===================================================================
--- cgkit/trunk/cgkit/simplecpp.py 2008-02-17 10:57:17 UTC (rev 229)
+++ cgkit/trunk/cgkit/simplecpp.py 2008-02-17 11:08:34 UTC (rev 230)
@@ -38,17 +38,31 @@
class Context:
"""This class carries information about a particular source file.
+
+ Each #include command produces a new context that gets pushed
+ onto the stack.
"""
def __init__(self, filehandle):
# The file handle (file-like object)
self.filehandle = filehandle
- # The current line number (i.e. the line number of the next read line)
+ # The current line number (i.e. the line number of the next line read)
self.linenr = 1
+ # The line number where the current (continued) line started.
+ # This is only different from self.linenr when lines were continued
+ # with a backslash at the end of a line. In this case start_linenr
+ # is the line number where the long line began and linenr is the
+ # last line number of the long line.
+ self.start_linenr = 1
# The file name
self.filename = getattr(filehandle, "name", "<?>")
+ # This is basically a stack that contains the evaluated conditions
+ # of the #if, #ifdef, etc. commands
self.condition_list = []
# Flag that specifies whether a line should be ignored or not
+ # (because it is inside an #ifdef ... #endif block, for example).
+ # If this flag is False there is still be output generated, but
+ # it's just an empty string)
self.output_line = True
@@ -98,7 +112,10 @@
self.includedirs = []
if includedirs!=None:
self.includedirs.extend(includedirs)
-
+
+ # This flag can be used to abort the preprocessor
+ self.abort_flag = False
+
def __call__(self, source, errstream=None):
"""Preprocess a file or a file-like object.
@@ -153,6 +170,8 @@
stripped = out.strip()
# Preprocessor directive?
if stripped[:1]=="#":
+ # Invoke the appropriate directive handler method...
+ # (i.e. onInclude(), onIfdef(), ...)
s = stripped[1:].strip()
a = s.split()
directive = a[0].lower()
@@ -161,10 +180,11 @@
handler = getattr(self, handlername, None)
if handler!=None:
handler(directive, arg)
+ # no preprocessor directive but regular code...
else:
out = ""
for s in intervals:
- # Do substitutions if it's not a string
+ # Do macro substitutions if it's not a string
if s[0:]!='"':
for name,value in self.substitution_list:
s = s.replace(name, value)
@@ -174,17 +194,38 @@
self.output(out)
else:
self.output("")
+
+ # Should preprocessing be aborted?
+ if self.abort_flag:
+ break
self.context.linenr += 1
+ self.context.start_linenr = self.context.linenr
linebuffer = ""
self.popContext()
def output(self, s):
- """This method is called for every output line.
+ """This method is called for every (extended) output line.
+
+ Lines that were split using '\' at the end of the line are
+ reported as one single line.
"""
self.output_buffer.append(s)
+ def abort(self):
+ """Tell the preprocessor to abort operation.
+
+ This method can be called by a derived class in the output()
+ handler method.
+ """
+ self.abort_flag = True
+
+ # Directive handler methods:
+ # Each method takes the lowercase directive name as input and
+ # the argument string (which is everything following the directive)
+ # Example: #include <spam.h> -> directive: "include" arg: "<spam.h>"
+
def onInclude(self, directive, arg):
"""Handle #include directives.
"""
@@ -334,7 +375,6 @@
return None
-
def iterStringIntervals(self, s):
"""Iterate over the separate 'intervals' in the given string.
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. | http://sourceforge.net/p/cgkit/mailman/message/18607913/ | CC-MAIN-2015-40 | refinedweb | 562 | 53.68 |
ADO Fundamentals
Microsoft ActiveX Data Objects
ADO With MSVB Express
The .NET Framework is a library, developed by
Microsoft, that can be used to create different types of applications, including
databases, using a low-level common language that is translated from a known,
and somewhat easier or regular language such as Microsoft Visual C#. The .NET
Framework comes with a technique of creating and managing databases known
ADO.NET. Although ADO is a true library,
ADO.NET is not a library: it is only a technique of dealing with databases. The
ADO part suggests that it uses concepts similar to the ADO approach of solving
database operations. The .NET part of the name means that it uses the .NET
Framework.
Using ADO in the .NET Framework
If you want to create an ADO database application in
Microsoft Visual C#, the .NET Framework provides a namespace named ADODB
that is equipped with various interfaces and classes. To access the ADODB namespace if
your project, you can first create a reference to its library. To do this, in
the Solution Explorer, right-click the name of the project and click
References... In the Property Pages, click Add New Reference... In the COM tab of the Add Reference dialog box, locate the Microsoft ActiveX Data Objects version
Library
Click OK. In the .NET Framework, ADO is represented by the ADODB
namespace. The classes used to create and manage tables are stored in the ADODB
namespace.
The Data Source of an Application
Introduction in a network. Another database can be
created and stored in a server to be accessed through the Internet. These
and other related scenarios should be dealt with to create and distribute
the database.
A Data Source
You may plan to create a database that would be used
by one person using one computer. As your job becomes more effective, you
could be asked to create another database that would be accessed by
different people. Regardless of why and how, after creating a database,
you should have a way of making it available to those who would use it. To do
this, you can create a data source.. | http://www.functionx.com/vcsharp2003/ado/Lesson03.htm | CC-MAIN-2017-04 | refinedweb | 357 | 64.41 |
The Android of Things platform has some big advantages compared to Arduino or Raspbian. We Android developers can use the same tools we use for building applications for our projects, including all our favorite libraries, Google Play Services, and of course Kotlin.
The Android of Things platform has some big advantages compared to Arduino or Raspbian. We Android developers can use the same tools we use for building applications for our projects, including all our favorite libraries, Google Play Services, and of course Kotlin.
On the other hand, there’s a big disadvantage. Compared to Arduino, the Raspberry Pi can’t handle the low level custom protocols of some sensors. And compared to Raspbian, many of the available HATs are currently not supported.
How can we get the best of both worlds together? By using the right tool for the job. Let’s use the Arduino controller to read and write to our cheap and widely available sensors and use the Raspberry Pi to implement all the complex logic the same way we build Android applications.
Then, we will use the UART (universal asynchronous receiver/transmitter) of both platforms to exchange data between them. This is also known as the Serial on Arduino.
Connecting the two devices is very simple:
However there’s still one thing to do:
Take a look at the Configuring the UART mode in the official documentation:
☞ Arduino with Ardublockly: Block based Arduino Programming
Since the UART Bluetooth mode is enabled by default, you can’t start using the UART to talk with the Arduino out-of-the-box. You need to go through that configuration step!
I’ll like to give all the credit of this idea to Marcos Placona, who wrote an article about the same topic months ago and helped me get started:
☞ Arduino Bootcamp : Learning Through Projects
The library he started didn’t fit my needs so I went with a simpler, one class solution that you can copy and modify for your projects:
import android.util.Log import com.google.android.things.pio.PeripheralManagerService import com.google.android.things.pio.UartDevice class Arduino(uartDevice: String = "UART0"): AutoCloseable { private val TAG = "Arduino" private val uart: UartDevice by lazy { PeripheralManagerService().openUartDevice(uartDevice).apply { setBaudrate(115200) setDataSize(8) setParity(UartDevice.PARITY_NONE) setStopBits(1) } } fun read(): String { val maxCount = 8 val buffer = ByteArray(maxCount) var output = "" do { val count = uart.read(buffer, buffer.size) output += buffer.toReadableString() if(count == 0) break Log.d(TAG, "Read ${buffer.toReadableString()} $count bytes from peripheral") } while (true) return output } private fun ByteArray.toReadableString() = filter { it > 0.toByte() } .joinToString(separator = "") { it.toChar().toString() } fun write(value: String) { val count = uart.write(value.toByteArray(), value.length) Log.d(TAG, "Wrote $value $count bytes to peripheral") } override fun close() { uart.close() } }
Arduino.kt
This class provides three simple methods that cover the following:
On the Arduino project, you need to handle the received commands and write the responses afterwards. This is an example of how to do it:
Arduino.c
if (Serial.available() > 0) { char command = (char) Serial.read(); switch (command) { case 'H': Serial.write("Hello World"); break; } Serial.flush(); }
You can write an “H” to the UART, and read back “Hello World” from it:
Example.kt
val arduino = Arduino() arduino.write("H") Thread.sleep(100) // let Arduino reply val hello = arduino.read() // hello = "Hello World"
Now you can happily communicate your Android of Things applications with Arduino and use all the arsenal of sweet sweet cheap Arduino sensors on your Android of Things projects.
In this article, I am going to show you how to send sensor sensor data to a local webserver using esp8266.
Before delving into this article , let me explain the term localhost.
Localhost refers to the local computer that a program is running on. For example, if you are running a Web browser on your computer, your computer is considered to be the "localhost".
The deliverables for this project are:
Xamp webserver download it here
Arduino IDE download here
ESP8266 official website
Smartphone used as a router.
Project requirement: Create a folder in the xamp/htdocs named esp8266. In this folder you are going to save the postData.php and databaseConfig.php
To send the sensor data to a database, we need to write an arduino sketch using a TCP protocol to communicate wirelessly to the local webserver.
Let's get it done now!
Step 1: Install esp8266 board the link to the procedure can be found here
Step 2: The arduino sketch is shown below. I create two function connectWifi() and sendSensorData() which I invoke respectively in the void setup and void loop. If you are confused please look for a tutorial on basic arduino code.
#include <WiFiClient.h> #include <ESP8266WebServer.h> #include <ESP8266HTTPClient.h> const char *ssid = "MelleB"; //ENTER YOUR WIFI ssid const char *password = "refj4497"; //ENTER YOUR WIFI password void setup() { connectWifi(); } void loop() { SendSensorData(); } //function to connect to wifi void connectWifi(){ delay(1000); Serial.begin(115200); WiFi.mode(WIFI_OFF); //Prevents reconnection issue (taking too long to connect) delay(1000); WiFi.mode(WIFI_STA); //This line hides the viewing of ESP as wifi hotspot WiFi.begin(ssid, password); //Connect to your WiFi router Serial.println(""); Serial.print("Connecting"); // Wait for connection while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } //If connection successful show IP address in serial monitor Serial.print("Connected to "); Serial.println(ssid); Serial.print("IP address: "); Serial.println(WiFi.localIP()); //IP address assigned to your ESP } //function to send sensor data void SendSensorData() { HTTPClient http; //Declare object of class HTTPClient String sensorData1,sensorData2,sensorData3,sensorData4,sensorData5,sensorData6,sensorData7, postData; sensorData1="High"; sensorData2="High"; sensorData3="High"; sensorData4="High"; sensorData5="High"; sensorData6="High"; sensorData7="High"; //Post Data postData = "sensor1=" + sensorData1 + "&sensor2=" + sensorData2+ "&sensor3=" + sensorData3+ "&sensor4=" + sensorData4+ "&sensor5=" + sensorData5+ "&sensor6=" + sensorData6+ "&sensor7=" + sensorData7; http.begin(""); //change the ip to your computer ip address http.addHeader("Content-Type", "application/x-www-form-urlencoded"); //Specify content-type header int httpCode = http.POST(postData); //Send the request String payload = http.getString(); //Get the response payload Serial.println(httpCode); //Print HTTP return code Serial.println(payload); //Print request response payload http.end(); //Close connection delay(5000); //Post Data at every 5 seconds }
Step 3: Create the database sensor and the table name logs and save it in the esp866 folder as databaseConfig.php
//connect to localhost if not exists $servername = "localhost"; $username = "root"; $password = ""; // Create connection $conn = new mysqli($servername, $username, $password); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Create database $sql = "CREATE DATABASE sensor"; echo "Database created successfully"; } else { echo "Error creating database: " . $conn->error; } $conn->close(); echo "<br>"; //Connect to database and create table $servername = "localhost"; $username = "root"; $password = ""; $dbname = "sensor"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "CREATE TABLE logs ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, sensor1 VARCHAR(30), sensor2 VARCHAR(30), sensor3 VARCHAR(30), sensor4 VARCHAR(50), sensor5 VARCHAR(50), sensor6 VARCHAR(50), sensor7 VARCHAR(50), \`Date\` DATE NULL, \`Time\` TIME NULL, \`TimeStamp\` TIMESTAMP NULL DEFAULT CURRENT\_TIMESTAMP ON UPDATE CURRENT\_TIMESTAMP)"; if ($conn->query($sql) === TRUE) { echo "Table logs created successfully"; } else { echo "Error creating table: " . $conn->error; } $conn->close(); ?>
Step 4: Create postData.php in the esp866 folder and paste the code below in it.
//Creates new record as per request //Connect to database $servername = "localhost"; $username = "root"; $password = ""; $dbname = "sensor"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Database Connection failed: " . $conn->connect_error); } //Get current date and time date\_default\_timezone_set('Asia/Kolkata'); $d = date("Y-m-d"); //echo " Date:".$d."<BR>"; $t = date("H:i:s"); if(!empty($\_POST\['sensor1'\]) || !empty($\_POST\['sensor2'\])) { $sensorData1 = $_POST\['sensor1'\]; $sensorData2 = $_POST\['sensor2'\]; $sensorData3 = $_POST\['sensor3'\]; $sensorData4 = $_POST\['sensor4'\]; $sensorData5 = $_POST\['sensor5'\]; $sensorData6 = $_POST\['sensor6'\]; $sensorData7 = $_POST\['sensor7'\]; $sql = "INSERT INTO logs (sensor1, sensor2,sensor3,sensor4,sensor5,sensor6,sensor7, Date, Time) VALUES ('".$sensorData1."', '".$sensorData2."', '".$sensorData3."', '".$sensorData4."', '".$sensorData5."', '".$sensorData6."', '".$sensorData7."', '".$d."', '".$t."')"; if ($conn->query($sql) === TRUE) { echo "OK"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } } $conn->close(); ?>
Step 5: software testing
Please let me know in case of any errors.
Get Started with Machine Learning on Arduino .Arduino is on a mission to make Machine Learning simple enough for anyone to use. We’ve been working with the TensorFlow Lite team over the past few months and are excited to show you what we’ve been up to together:.
Running the pre-trained micro_speech inference example..
Arduino Nano 33 BLE Sense board is smaller than a stick of gum
There are practical reasons you might want to squeeze ML on microcontrollers, including:
There’s a final goal which we’re building towards that is very important: ML applications in the future.What you need to get started
The Arduino Nano 33 BLE Sense has a variety of onboard sensors meaning potential for some cool Tiny ML applications:
Compiling an example from the Arduino_TensorFlowLite library:
For advanced users who prefer a command line, there is also the arduino-cli.Training a TensorFlow Lite Micro model for Arduino
Gesture classification on Arduino BLE 33 Nano Sense, output as Emojis to sampling.
To program the board with this sketch in the Arduino IDE::
punch.csv
flex.csv:
Training in TensorFlowTraining in TensorFlow
$ cat /dev/cu.usbmodem[nnnnn] > sensorlog.csv:
punch.csvand
flex.csvdataClassifying IMU Data
Next we will use model.h file we just trained and downloaded from Colab in the previous section in our Arduino IDE project:
model.h
3. Open the
model.h tab and paste in the version you downloaded from Colab
4. Upload the sketch: Sketch > Upload
5. Open the Serial Monitor: Tools > Serial Monitor
6. Perform some gestures
7. The confidence of each gesture will be printed to the Serial Monitor (0 = low confidence, 1 = high confidence) 👊.Conclusion
It’s an exciting time with a lot to learn and explore in Tiny ML.”
For my latest project, I teamed up with my friends to create the world’s smallest Arduino compatible board named Atto! Below video shows Atto in action with its RGB (rainbow) LED lighting up
Wondering how small Atto is? How’s about 0.4” x 0.45” small? (10.3 mm x 11.5 mm for my fellow metric brothers and sisters).
For those of you who may be unfamiliar, Arduino is a general-purpose circuit board with a tiny processor that can be programmed to do pretty much whatever you want, and it has a huge community behind it. Having a huge community (for anything really) is great since you have support from all around the globe (kind of like Medium)! So, you may be wondering, what can you do with such a tiny device when you can barely hold or see the darn thing?
Well, a lot! Imagine you want to create a new tech for wearables where earrings or other jewelries change colors based on your body temperature or heartbeat. Or, how about a tiny robotics project where Atto acts as the brain of the robot? The possibilities are endless!
So, we now know what kind of hardware product we want to create but how do we actually make it? It starts with engineering specs or as I usually call it, the process of going from shower thoughts to scribbled thoughts on a paper. The specs tell us exactly what we want to achieve from our hardware which in turn gives us an idea what components will be needed to build the hardware.
Once the specs are in place, we can begin our circuit design, specifically the schematic and layout. It’s tedious work but a good initial design will help us in the long run and save us a lot of development costs. So, it’s very important!
After we finish the schematic and layout, we want to ensure our component placements (the physical body shown above) is designed with manufacturing and maintenance in mind. The last thing we want is to struggle with assembling the products because of bad component placements!
The completed circuit design is sent to the magical land known as China to get it fabricated. Now, we have two choices here. First choice is to provide the circuit component list to the fabrication facility and have the prototypes fully assembled for us. Second choice is, as you may have guessed, we buy the parts and assemble it ourselves.
First choice is preferable but is costly whereas second choice is cheaper but requires a lot of manual labor. Being a poor grad student living off ramen and free lunches at school events, I opted out for the second choice. Above picture shows my soldering station and my hot air rework station that can blow at temperatures over 300 deg C (572 deg F) for assembling the boards. I named my hot air rework station, “The Manager” for obvious reasons.
After the circuits have been assembled, it’s time to program the initial test firmware on our prototype!
With the firmware programmed on Atto, we’re ready for testing (validation)! Our initial testing will be checking the input and output pin behaviours after powering it up. This is usually done by directly connecting the circuit board to the computer or by using a multimeter/oscilloscope. I personally use my trusty (a.k.a old and relatively cheap, but super reliable) Extech EX330. Not sponsored by Extech (… but I wish it was).
After validation is complete, you either have something working or something burnt to a crisp with magic smoke flying everywhere. Luckily, the latest revision of Atto survived and it’s ready to get lost somewhere in your room since it’s so darn small! (I may have lost one or two Attos already during the validation phase…).
Once we finish gathering our test data, we check to ensure that our initial specs were met, and we continue our testing to see if any necessary improvements are needed. And this, my friends, is the circle of l̶i̶f̶e̶ development.
Thanks for taking the time to read through my post and I hope you’ve enjoyed and learned something new! If you’re interested, you can check us out at.
Interactoutputs
<strong>A little I knew about electrical engineering or electrical circuits, only until I saw a web page programmed on the ESP8266 microchip.</strong>
A little I knew about electrical engineering or electrical circuits, only until I saw a web page programmed on the ESP8266 microchip.
A little I knew about electrical engineering or electrical circuits, only until I saw a web page programmed on the ESP8266 microchip. Ever since, a new realm was opened for me, the Arduino and open-source hardware realm. But for the sake of sticking to web development, I will not dive deep into it and focus only on the web aspect of it that caught my attention the most.
The ESP8266 is a microchip with WiFi and full TCP/IP capabilities. It’s manufactured by a company called Espressif from Shanghai. It’s not affiliated with the Arduino company which is itself a separate entity but the ESP8266 can be added to the Arduino microcontroller board to give it WiFi capability which it doesn’t have out of the box. Although the Arduino company have their own WiFi Shield, the ESP9266 is a cheaper alternative and it’s available as a separate development board module. It’s also more popular among hobbyists therefore it has more popularity and more support in the community.
In the following section I will be using the Arduino IDE to program a web server on the ESP8266 NodeMCU board. It won’t be a detailed tutorial and I encourage you to search for more introductory content online if you want to get deeper into the details. The sole purpose of this article is to encourage web developers to get to know the Arduino ecosystem and how they can benefit from it as web developers.
So I mentioned programming a web server so far but what kind of web page am I going to serve on it? Well, it’s a Temperature and Humidity monitoring web page with the help of the DHT11, a basic, ultra low-cost digital temperature and humidity sensor. The web page can be accessed by any device that has a browser and sits on the local network.
First in the Arduino IDE we need to install the ESP8266 board library
Select the ESP8266 board from the list
#include "ESP8266WiFi.h"> #include "DHT.h"
DHT dht(D5, DHT11); dht.begin();
const ssid = "YOUR_NETWORK_SSID"; const password = "YOUR_NETWORK_PASSWORD"; WiFi.begin(ssid, password);
WiFiServer server(80); server.begin();
Serial.println(WiFi.localIP());
float hum = dht.readHumidity(); float temp = dht.readTemperature();
WiFiClient client = server.available(); if (client) { // serving the web page (Step 11) }
client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println("Connection: close"); client.println(); // your actual web page that displays temperature and humidity client.println("<!DOCTYPE HTML>"); client.println("<html>"); client.println("<--! YOUR_WEBPAGE_HTML_HEADER_GOES_HERE -->"); client.println("<body><span>Temperature: "); client.println(celsiusTemp); client.println("°C</span>"); client.println("<span>Humidity: "); client.println(humidityTemp); client.println("%</span>"); client.println("</body></html>");
⚠️ At line 8, we inject our web page’s html header tags and include all assets inline. I found this tool that can be very helpful!
For the complete code here you go!
If the code compiled and was successfully uploaded, the ESP8266 should now be connected to the local network and has its own IP address (Step 8)
And just to make it more interesting I turned that web page into a Google Chrome extension that can be embedded on my desktop:
Recommended Courses:
☞ Mastering Arduino program (Guides to Arduino programming)
☞ Arduino 101 - Intel Curie
☞ Arduino Bootcamp : Learning Through Projects
☞ Advanced Arduino Boards and Tools | https://morioh.com/p/270271ec843f | CC-MAIN-2019-47 | refinedweb | 2,965 | 56.05 |
I don't exactly understand what you're trying to do, but the expression you
have above will store the words in a list, it is not a dictionary.
You could actually:
print('the words in this synset are ' + word[0] + ',' + word[1])
Note that you need to use [] and not () as you write above.
More elegant would be the following:
print ("the words in this synset are {0}".format(", ".join(word)))
because that works with an unknown number of words.
def main():
coins = {}
for kind in ['5c','10c','20c','50c','$1','$2']:
coins[kind] = int(raw_input("Enter the number of " + kind
+ " coins you wish use: ").strip() or 0)
Anytime you ask yourself how you could create dynamic variables, the answer
is "use a dictionary".
l=dict()
for i in range(n):
k='row%d'%(i,)
l[k] = map(int, raw_input().split())
Here is one option:
L = [(0, 1, 2, 3, 4, 5), (6, 7, 8, 9, 10, 11), (11, 12, 13, 14, 15, 16)]
multiple_index = [(entry[0], entry[3], entry[4]) for entry in L]
Or using operator.itemgetter():
from operator import itemgetter
indices = itemgetter(0, 3, 4)
multiple_index = [indices(entry) for entry in L]
extend doesn't return a value. Thus, printing a.extend(b) will be None.
Thus, if you have a = [5, 6, 7, 8, 9].extend(range(15, 20)) and print a it
will show None. A way around it would be to concatenate lists a = [5, 6, 7,
8, 9] + range(15, 20)
[5, 6, 7, 8, 9][2] - everything is as should be as it starts counting
elements from 0. It is not modifying list, it is merely returning a certain
element from the list.
[5, 6, 7, 8, 7].count(7) and [5, 6, 7, 8, 7].index(8) show the expected
output. First one is the number of times 7 occurs in the list, second one
is an index of number 8 (again, counting starts from 0).
So, all in all the use of hardcoded list behaves as expected in all of the
examples you've produced.
Try
myfile = open('input','r')
link = dict()
for line in myfile:
line = line.split(",")
IDs = line[1].split()
link[line[0]]=IDs
myfile.close()
for name in link.keys():
for ID in link[name]:
print ''.join(["",name,"/",ID])
function getBackList(urlName, globalVariableName) {
$.ajax({
type: "GET",
url: urlName,
}).done(function (returned_data) {
window[globalVariableName] = $.parseJSON(returned_data);
});
}
Pass in the global variable's name instead ^^^
Try following code. Read a comment I added.
from Tkinter import *
import Tkinter as ttk
from ttk import *
root = Tk()
root.title("Age Selector")
mainframe = Frame(root)
mainframe.grid(column=0,row=0, sticky=(N,W,E,S) )
mainframe.columnconfigure(0, weight = 1)
mainframe.rowconfigure(0, weight = 1)
mainframe.pack(pady = 10, padx = 10)
var = StringVar(root)
# Use dictionary to map names to ages.
choices = {
'Bob': '35',
'Garry': '45',
'John': '32',
'Hank': '64',
'Tyrone': '21',
}
option = OptionMenu(mainframe, var, *choices)
var.set('Bob')
option.grid(row = 1, column =1)
Label(mainframe, text="Age").grid(row = 2, column = 1)
age = StringVar()
# Bind age instead of var
age_ent = Entry(mainframe, text=age, width = 15).grid(column =
There is a list construct baked right into the core of Python, below is a
pretty good introduction:
You could re-write the code above pretty much identically in python, just
changing the syntax from C++ to python. However, there may be a more
pythonic way of doing what you require, it is hard to say without having
more context around the code.
while i < r and j < u:
if a[i] <= a[j]:
b[k] = a[i]
i += 1 # No increment operator in python
else:
b[k] = a[j]
j += 1
k += 1
You can't change an iterable while using it to drive an iteration, but you
could easily make an iterable to hold your results and pass it in to the
recursive function as an argument:
results = []
def recurse(level, results):
level += 1
results.append(level)
if level < 10: recurse(level, results)
print recurse(0, results)
>>> [1,2,3,4,5,6,7,8,9,10]
but in this example you could not do
for item in results:
recurse (item, results)
This is explained in the FAQ, under How do I create a multidimensional
list?
The problem is in this part of the code:
board = []
for i in range(7):
board.append(line)
You're creating a list with 7 references to the same list, line. So, when
you modify one, the others all change, because they're the same list.
The solution is to create 7 separate lists, like this:
def createBoard(self):
board = []
for i in range(7):
line = []
for i in range(7):
line.append(' ')
board.append(line)
return board
Or, more simply, make separate copies of the original list:
def createBoard(self):
line = []
for i in range(7):
line.append(' ')
board = []
for i in range(7):
board.append(line[:])
return board
While we
The comma operator will return the value of the right expression, so
writing this:
src < 8, dst >= 0;
As a condition will be the same as just writing dst >= 0. The src <
8 will be completely ignored in this case, as it's evaluated separately
from the second condition, and then the second condition is returned. This
doesn't evalute to AND or to OR, but in fact just has the effect of
"throwing away" the first check entirely.
If you want to evaluate this correctly, you should use one of your two
options (explicitly specifying the behavior via || or &&).
For details, see Comma Operator:
When the set of expressions has to be evaluated for a value, only the
rightmost expression is considered.
The idea is pretty much the same as for in. Note that you don't need to
make a variable from the list length, also you don't need to specify a
start for the range(), it's 0 by default.
def prod(L):
p = 1
for i in range(len(L)):
p *= L[i]
return p
print(prod([1,2,3,4])) # prints 24)
You can use arrays for that:
A=({a..z}) B=({1..26})
for (( I = 0; I < 26; ++I )); do
echo "/dev/sd${A[I]} /disk${B[I]}
ext4 noatime 1 1" >> test
done
Example output:
/dev/sda /disk1 ext4
noatime 1 1
...
/dev/sdz /disk26 ext4
noatime 1 1
Update:
As suggested you could just use the index for values of B:
A=('' {a..z})
for (( I = 1; I <= 26; ++I )); do
echo "/dev/sd${A[I]} /disk${I}
ext4 noatime 1 1" >> test
done
Also you could do some formatting with printf to get a better output, and
cleaner code:
A=('' {a..z})
for (( I =
Although this is only a guess without seeing your actual indented code, I
believe your problem is this:
while 0 <= px <= width:
while 0 <= py <= height:
# a whole mess of logic
If py goes out of bounds, you'll escape the inner loop, but then just keep
repeating that inner loop until px also goes out of bounds.
If px goes out of bounds, you'll still be stuck inside the inner loop until
py also goes out of bounds.
What you want is to escape as soon as either goes out of bounds. In other
words, you want a single loop, that keeps going as long as both are in
bounds. Which you can translate directly from English to Python:
while 0 <= px <= width and 0 <= py <= height:
# same whole mess of logic
If insertion_sort worked before, I guess it works now, too. The problem is
that usfl contains only one element, the content of the file.
If you have a fruit on each line, you can use this to populate your list:
usfl = [line.rstrip () for line in unsorted_fruits]
or if it is a comma separated list, you can use:
usfl = unsorted_fruits.read ().split (',')
Just store the old functions in a dictionary:
old = {'a': a, 'b': b, 'c': c}
then use the globals() dictionary to restore them:
globals().update(old)
This only works if a, b and c were globals to begin with.
You can use the same trick to assign d to all those names:
globals().update(dict.fromkeys(old.keys(), d))
This sets the keys a, b and c to the same value d.
Give this a try, I can't test it using label & textbox object but it
can work tuning it better:
1..8 | ForEach-Object {
IF ( (iex "`$Label$_.Text.Length") -ne 0 )
{
iex "`$Label$_.Visible = `$true"
iex "`$TextBox$_.Visible = `$true"
iex "`$TextBox$_.Text = 'Enter new name for ' + `$Label$_.Text"
}
}
If you need to do this with a while loop, you could do it by appending each
element to a list rather than printing it, and then returning that list:
def everythird(l):
i = 0
ret = []
while i < len(l):
ret.append(l[i])
i += 3
return ret
Though as you note, it would certainly be preferably to do
def everythird(l):
return l[0::3]
Or if you were allowed to use a for loop:
def everythird(l):
ret = []
for i in range(0, len(l), 3):
ret.append(l[i])
return ret
Finally, if you were allowed to use a list comprehension:
def everythird(l):
return [l[i] for i in range(0, len(l), 3)]
The slice indexing is certainly the best, but in any case a while loop
might be the worst way to do it.
bakeries = ['a','b','c']
breadtypes = ['flat','rye','white']
results = []
for i in bakeries:
print('How many of each type of bread for {0}:'.format(i))
number_of_types = []
for bread in breadtypes:
number_of_types.append(input('{0}:'.format(bread)))
results.append(number_of_types)
for k,v in enumerate(bakeries):
print('Here are the different types of breads for {0}'.format(v))
print(''.join('{0}:{1}'.format(a,b) for a,b in zip(breadtypes,
results[k])))
with open('data.txt', 'r') as data:
for _input in data:
line = _input.split(' ')
data = {'Index':line[0],
'Origin Time':line[-3:][-1].strip()
}
data.update(dict(zip(line[1:-3][0::2], line[1:-3][1::2])))
print data
Here is a way to rotate the characters in a string around, assuming there
are only A-Z letters in your string.
string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(10):
string = "".join([chr((ord(letter) - ord('A') + 1) % 26 + ord('A')) for
letter in string])
print string
The idea is that each letter has an ASCII code difference from the letter
A. So letter A would be 0, letter B is 1. When letter Z is shifted forward,
it needs to go back to A. This is where the modulo (%) comes in, it shifts
the letter Z back to A if needed.
Output:
Yes, and no. You can get a list of global variables:
for name, val in globals().items():
if val is obj:
yield name
You can also get a list of local variables:
for name, val in locals().items():
if val is obj:
yield name
However, you will with this miss all variables in other contexts than local
to your function or global to the module. You can find variables in calling
contexts with frame-magic, but you won't be able to find anything that is
global to other modules, for example.
What you would use this for, I don't know.
You will also not find any attributes that reference the object, but
attributes aren't variables so maybe that's OK.
You can get all objects that reference your object though. And that will
include the globals and locals for all the functio
Try this,
<c:forEach
<div id="col${count}">
<c:out
</div>
</c:forEach>
your list is not 2000 long, you start at 2..
>>> primes=list(range(2,2001))
>>> print len(primes)
1999
So when you do the while loop, it doesn't get up to 2000... :)
-a is the AND operator in test:
if [ -n "$variableA" -a -n "$variableB" -a -n "$variableC" -a "$variableD"
-eq 1 ]
then
echo "Bye bye"
fi
If you want OR, the operator is -o. These are both in the test man page.
How about this:
scala> val numbers = List(1, 2, 3)
numbers: List[Int] = List(1, 2, 3)
scala> val List(hours, minutes, seconds) = numbers
hours: Int = 1
minutes: Int = 2
seconds: Int = 3
From your python script, output one variable per line. Then from you bash
script, read one variable per line:
Python
print "foo bar"
print 5
Bash
#! /bin/bash
python main.py | while read line ; do
echo $line
done
Final Solution:
Thanks Guillaume! You gave me a great starting point out the soultion. I am
just going to post my solution here for others.
#! /bin/bash
array=()
while read line ; do
array+=($line)
done < <(python main.py)
echo ${array[@]}
I found the rest of the solution that I needed here
A method in Python is a function. If you want to get a value from a member
function you have to end it with (). That said, some refactoring may help
eliminate boilerplate and reduce the problem set size in your head. I'd
suggest using a @property for some of these things, combined with a slight
refactor
class variable:
def __init__(self, length):
self.length = length # time length`
@property
def state_dynamic(self):
return self.np_length
@property
def state_static(self):
return self.np_length
@property
def control_dynamic(self):
return self.np_length
@property
def control_static(self):
return self.np_length
@property
def scheduling(self):
return self.np_length
@property
def np_length(self):
return np.zeros(2, np.size(self.length))
That way you can us
There are a number of ways that you could go about this. The simplest is
probably to initialize an empty string before the if statements. Then,
instead of printing split[1] and ip[2], concatenate them to the empty
string and print that afterwards. So it would look something like this:
printstr = ""
if re.search...
...
printstr += "Label for first item " + split[1] + ", "
if re.search...
...
printstr += "Label for second item " + ip[2]
print printstr
You cannot use an augmented assignment statement on multiple targets, no.
Quoting the augmented assignment documentation:.
Emphasis mine.
In-place augmented assignment is translated from target -= expression to
target = target.__isub__(expression) (with corresponding __i...__ hooks for
each operator) and translating that operation to multiple targets is not
supported.
Under the hood, augmented assignment is a specialisation of the bina
You are creating one instance, then copying the reference to that instance
nlst times:
dlst = [Myclass(0)]*nlst
This does not create a list of nlist instances of Myclass(0); it creates a
list of nlst references, all pointing to one object.
Use a list comprehension instead:
dlst = [Myclass(0) for _ in range(nlst)]
In a list comprehension, the expression on the left is re-executed for each
iteration of the loop.
Short answer: what you want is strncpy
Long answer: In defining name as a character array in a struct, you are
allocating a set amount of memory in that struct to store the characters in
the name. To move characters into that space, you have to copy them, and
that's where strncpy comes in.
You could also have defined name as a pointer to char (char *), in which
case your assignments would make sense. In C, when you use a literal
string, you're really including those bytes somewhere within your
executable, and that "..." syntax returns the pointer to where those
characters are statically stored, as a char *. From a type standpoint, char
* is a less specific type than char[30], and so you cannot directly assign
that pointer into your player.name variable. From a C implementation
standpoint
request.GET in your view is a dictionary; by doing request.GET['search3']
you're just accessing the value of its search3 key. So in your template,
you should be able to just add other <select> elements with their own
names and retrieve their submitted values from request.GET in the same way.
You can second time use your parse method for results from first running.
In this case you will receive not exactly the same you want but very
similar:
def stat(lst, index):
"""Calculate mean and std deviation from the input list."""
n = float(len(lst))
mean = sum([pair[index] for pair in lst])/n
stdev = sqrt((sum(x[index]*x[index] for x in lst) / n) - (mean * mean))
return mean, stdev
def parse(lst, n, index):
cluster = []
for i in lst:
if len(cluster) <= 1: # the first two values are going
directly in
cluster.append(i)
continue
mean, stdev = stat(cluster, index)
if (abs(mean - i[index]) > n * stdev): # check the "distance"
yield cluster
cluster[:] = [] # reset cluster to th
You have to remember the thread could also be looking at a stale copy, by
locking you assure that the version of the variable you are looking at is
being refreshed
When I first started coding and thought that maybe I don't need the
freshest copy of the variable I would get stuck in infinite loops because I
assume the variable would be updated eventually, but if the variable was
cached then it would never update
I included examples with brief descriptions, don't worry about the way the
thread is started, that is not relevant
private static bool _continueLoop = true;
private static readonly object _continueLoopLock = new object();
private static void StopLoop()
{
lock(_continueLoopLock)
_continueLoop = false;
}
private static void ThreadALoopWillGetStales()
{
while(_c | http://www.w3hello.com/questions/Assigning-multiple-variables-from-a-list-in-a-for-loop-in-Python | CC-MAIN-2018-17 | refinedweb | 2,908 | 71.04 |
*
Doubt in OCP Practice Exams question
Chandramohan Thalappally
Greenhorn
Joined: Dec 28, 2010
Posts: 4
posted
Dec 28, 2010 14:36:02
0
In Question # 39, class Untuned, the answer given is as "A" (answer -1), which is wrong. Because the method toCompare takes Object a, Object b as arguments, so infact, it will give a compilation error saying that the interface Comparator is not correctly implemented. So, if the code should work, it should be like this - note the the Object a and Object b were correctly cast to
String
in the compareTo method.
Can Kathy or Bert can comment on this. Likewise, I have seen problems, elsewhere in the Practise Exam guide.
import java.util.*; public class Unturned { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String [] towns = {"aspen","Vail","trade", "dillion"}; MySort ms = new MySort(); Arrays.sort(towns, ms); System.out.println (towns[0] + towns[1]+ towns[2]); System.out.println (Arrays.binarySearch(towns, "dillion",ms)); } static class MySort implements Comparator { public int compare (Object a, Object b) { return ((String)b).compareTo((String)a); } } }
Bert Bates
author
Sheriff
Joined: Oct 14, 2002
Posts: 8764
5
posted
Dec 28, 2010 16:17:36
0
Hi Chandramohan,
Welcome to Javaranch.
It's great for you to ask questions like this, and perhaps you've found a bug too. But here's how to do this the official JavaRanch way:
- First off, since this is a question about the
SCJP
certification exam, you should put your question in the SCJP forum.
- Second, you should always post the exact code that's in the mock exam that you want to talk about. Remember that not everyone has a copy of all the mock exams. As long as you tell us where the mock exam question came from, it's fine to copy the question out of the book or wherever.
- Third, each time you have a question, it's best to start a new thread and the title should be something like:
"Doubt concerning a collections question in the XYZ mock exam"
Remember, sometimes you might find an error in a mock exam, and sometimes you might be wrong
- so it's best to describe your question as a doubt.
Once you've posted the question (and any other code, like you've done), in the proper forum, we wait to see what the other ranchers think. Once we've all agreed, then, and only then, if it's an error, we'll make a note of it.
I didn't study your specific question because you didn't include the original code, so I can't agree or disagree at this point. Besides, it's better for certification candidates to discuss these kinds of things in the certification forums.
I look forward to seeing your "doubt" in the SCJP forum.
hth,
Bert
Spot false dilemmas now, ask me how!
(If you're not on the edge, you're taking up too much room.)
Chandramohan Thalappally
Greenhorn
Joined: Dec 28, 2010
Posts: 4
posted
Dec 28, 2010 19:10:04
0
Hello Bert,
Thanks for your prompt reply and kind guidance. The reason for posting this specific question (#39 of Practice Exam 1) as this thread is related to this specific book (OCP Java SE6 Programmer Practice Exam - Exam 310-065) written by Kathy and yourself. I have a Kindle edition of it. As the inner static class "MySort" implements Comparator, we should implement "public int compare (Object a, Objectb)" and then cast the two objects to String like - return ((String)b).compareTo((String)a), before returning the int value, otherwise compiler wont let you go ahead. So, this question is related to that book and this thread is about that book and thta's why I posted here. I hope you have a copy of that specific question in your hand. Sorry for the inconvenience. I will try to post the original question and corrected question in SCJP Exam thread shortly. I wish, I could have clarified more on this verbally. The JavaRanch site is enriching me enormous amount of knowledge on Java. I admire Kathy and you for maintaining it so great.
Regards
Ankit Garg
Sheriff
Joined: Aug 03, 2008
Posts: 9280
17
I like...
posted
Dec 30, 2010 06:07:10
0
I pulled the rank and transferred the question to a new topic.
Because the method toCompare takes
The method name is actually
compareTo
which is a part of Comparable interface and the Comparator interface has a
compare(Object a, Object b)
method. I'm actually confused as to what the code in the book is (as I don't have the book) so if you could post the exact code of the book, it would be easier to understand if the book's code is wrong...
SCJP 6 | SCWCD 5 |
Javaranch SCJP FAQ
|
SCWCD Links
Frank Callahan
Greenhorn
Joined: Dec 30, 2010
Posts: 15
posted
Dec 30, 2010 09:50:05
1
Hi Chandramohan,
Question 39 in the first exam in the OCPJP practice exam (page 77) reads as follows, at least in my copy:
import java.util.*; public class Unturned { public static void main(String[] args) { String[] towns = {"aspen", "vail", "t-ride", "dillon"}; MySort ms = new MySort(); Arrays.sort(towns, ms); System.out.println(Arrays.binarySearch(towns, "dillon")); } static class MySort implements Comparator<String> { public int compare(String a, String b) { return b.compareTo(a); } } }
The code does compile, and the output is -1, which is the correct answer as stated on page 121. There's some misdirection in the question that could lead you to answer as if the binary search had been made in a String[] sorted in reverse, i.e, [vail,t-ride,dillon,aspen], making C. 2 the right answer. But as the book explains, answer A. -1 is the most
likely
output, since the binarySearch method that is called is the two param version without a Comparator ref as the third param. Strictly speaking though, even if -1 is the actual output from the Oracle/Sun jdk1.6.0_23 version that I'm using, the javadocs for the
java.util.Arrays
class say that the result of a binary search in an unsorted (or not sorted in the natural ordering of the class) array is
undefined
:
public static int binarySearch(Object[] a, Object key)
Searches the specified array for the specified object using the binary search algorithm. The array must be sorted into ascending order according to the natural ordering of its elements (as by the sort(Object[]) method) prior to making this call.
If it is not sorted, the results are undefined.
...
So, there is a conflict between the documentation and the observed behavior of the Arrays class, which may reliably produce a -1 index from running this code, but by the docs, could output any number at all, that is, the expected output is
undefined
. Use of the word
likely
in question 39 may be a way of getting at your experience of using binarySearch(), and not of just being familiar with the documentation. However, the question is kind of unfair in that if the word
likely
was removed, A, B, C and D could all be correct.
Regards,
Frank
Chandramohan Thalappally
Greenhorn
Joined: Dec 28, 2010
Posts: 4
posted
Dec 30, 2010 11:15:23
0
Hello Frank
The code I have from my Kindle Edition (I purchased and downloaded from Javaranch site for 16 bucks) has a raw type Comparator implementation (quoted below). It does not have the <String> (the Comparator is not typed). That's where the whole ocnfusion arised. But I do not understand why your code has <String> (the type Comparator implementation and the code I have is a raw type Comparator implementation). So, as the code exists in my kindle edition and the compiler will give a warning saying that Comparator.compare(Object,Object) must be implemented.
So, the Kind Edition code I have is not a typed-Comparator. It is a raw Comparator. So, just for exercise, just removed the <String> from your Comparator implementation. the compiler will squak at you as I stated above.
import java.util.*;
public class Unturned {
public static void main(String[] args) {
String[] towns = {"aspen", "vail", "t-ride", "dillon"};
MySort ms = new MySort();
Arrays.sort(towns, ms);
System.out.println(Arrays.binarySearch(towns, "dillon"));
}
static class MySort implements Comparator {
public int compare(String a, String b) {
return b.compareTo(a);
}
}
}
Frank Callahan
Greenhorn
Joined: Dec 30, 2010
Posts: 15
posted
Dec 30, 2010 11:36:31
0
Hmm, it looks like the Kindle version is different from the printed book. I typed in the exact code from the book. What explanation does the Kindle version give for -1 being the right answer?
Update - Amazon.com has a review of the Kindle version that explains what is going on:
This review is from: OCP Java SE 6 Programmer Practice Exams (Exam 310-065) (Kindle Edition)
I love the quality of McGraw Hills books and specially the ones to prepare the Java Certify exams. I'm also a Kindle user with very good experiences reading books in Kindle versions.
But this one is completely useless. As you may know, Kindle books are actually a kind of HTML code (with labels like: '<'html'>', '<'body'>', '<'p'>', etc.). Well, Java ALSO use these kind of labels for its GENERIC parameters, so when you open this book in Kindle version you lose every generic argument (and there are a lot of them in the exams) because the book reader thinks they are HTML labels and don't show them.
This problem also affects to EVERY comparation expression which uses the characters ">" or "<" or ">=" or "<="...
Frank
Chandramohan Thalappally
Greenhorn
Joined: Dec 28, 2010
Posts: 4
posted
Dec 30, 2010 12:03:04
0
Thanks Frank on this help information. I also noticed that several less than symbol (<) are missing. Now, shame on Amazon and without properly
testing
the Kindle Edition for Java's syntax and semantics, they are selling for the public. I would like to have proper explanation from Amazon or its publisher. Either they should refund the money or after correcting these mistakes, they should give an update of the Kindle Edition to its already purchased users. People are struggling day and night by studying these mock-up questions in the best hope of passing these highly challenging examinations and these publishers are selling erroneous mock-up questions for making money. Is there any way to bring this to the attention of Amazon, and get an updated/corrected version of this Kindle Edition.
Thanks for your valuable help in this matter.
Paul Anilprem
Enthuware Software Support
Ranch Hand
Joined: Sep 23, 2000
Posts: 3198
2
posted
Dec 30, 2010 12:13:19
0
It might be more beneficial if you contact the publisher (instead of Amazon) and ask for a
pdf
copy instead of kindle format.
Not sure if Amazon can do anything about it since they can't really check whether every book from every publisher works or not. I imagine it would be the publisher's responsibility.
Enthuware - Best Mock Exams and Questions for Oracle/Sun Java Certifications
Quality Guaranteed - Pass or Full Refund!
Bert Bates
author
Sheriff
Joined: Oct 14, 2002
Posts: 8764
5
posted
Dec 30, 2010 12:55:38
0
Hey Guys!
First off, I'm sorry you've encountered this problem!
grr...
I told the publisher about this kindle problem several weeks ago. They promise that they're working with Amazon to fix the problem.
I have also asked that they publish a notice when the problem is fixed and let kindle buyers re-download the fixed book for free.
Now, I don't know if that will happen, but that's what I'm asking for, and I promise I will be very persistent!!!
BTW, from the "Other than that Mrs. Lincoln how did you enjoy the play?", dept... How are you guys liking (or not) the book?
Bert
I agree. Here's the link:
subject: Doubt in OCP Practice Exams question
Similar Threads
Array.binarySearch()
Diff. Between Comparable & Comparator Interface
need help with Arrays.sort() and compareTo()
Please help with sorting multiple columns
BinarySearching an Array sorted in descending order
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/522000/java-programmer-SCJP/certification/OCP-Practice-Exams | CC-MAIN-2014-15 | refinedweb | 2,059 | 61.16 |
Create an RSS 1.0 document using a template or with Java.
RSS 1.0 is a branch from RSS 0.91 that incorporates elements from the W3C's Resource Description Framework or RDF (). Some folks didn't particularly like this branch to RDF because they saw it as too complex. Nevertheless, RSS 1.0 is now a popular format for RSS documents, running a close second to RSS 0.91, according to.
Following is a minimal example of an RSS 1.0 document, available in the file archive as wyeast.rss and at:
<?xml version="1.0" encoding="UTF-8"?> <rdf:RDF <channel rdf: <title>Wy'east Communications</title> <link></link> <description>Wy'east Communications is an XML consultancy.</description> <items> <rdf:Seq> <rdf:li rdf: </rdf:Seq> </items> </channel> <item rdf: <title>Legend of Wy'east</title> <link></link> <description>The Native American story behind the name Wy'east.</description> </item> </rdf:RDF>
The rdf:RDF element from the RDF namespace () is the document element. This element must have exactly one channel child and one or more item children (these elements are in the default namespace,). The rdf:about attribute on channel, from the RDF namespace, identifies the feed with a URI. Following channel are these elements:
A descriptive title for this channel.
A URI for the channel.
A description of the channel.
Contains the RDF elements Seq and li. The resource attribute on rdf:li contains a URI that identifies an item used later in the document.
Like channel, the sole item element holds title, link, and description elements that describe the news item. There can be virtually unlimited item element children after channel here. The rdf:about attribute on item must be unique and should match the content of link.
Two other possible children of channel are image and textinput, which link by means of rdf:resource attributes to other image and textinput elements, optionally used in the document as children of rdf:RDF (i.e., you can have one without the other). The image element links a graphic to the channel and must contain the trio title, link, and url; the textinput element contains a script or form that relates to the site and contains title, link, name, and description elements.
The document wyeast.rss was generated by a Java program, Rss1.java, available in the file archive. This program was written using the XML Object Model or XOM (), an easy-to-use XML API written by Elliotte Rusty Harold.
In order to work, Rss1.java needs Xerces and XOM JARs in the classpath at compile time, and the XOM JAR in the classpath at runtime. You can get xercesImpl.jar from and the XOM JAR from the XOM web site. This program can be adapted to work with any of the RSS or Atom vocabularies.
To use a Perl program to generate an RSS 1.0 document; | https://etutorials.org/XML/xml+hacks/Chapter+6.+RSS+and+Atom/Hack+82+Create+an+RSS+1.0+Document/ | CC-MAIN-2021-31 | refinedweb | 483 | 59.5 |
CodeGuru Forums
>
.NET Programming
>
C-Sharp Programming
> Creating log files
PDA
Click to See Complete Forum and Search -->
:
Creating log files
ujjwalmeshram
February 28th, 2008, 08:18 AM
Hi I m new to c#. I have made a calculator application.
I have given it to client for testing.
Client got some errors and he called me. When I reched to him, he was unable to explain me about the error.
Now I want to modify the program to create a log file(text file) which will store all the events generated by the programm i.e. what inputs are given by user, whta were the values of variables etc..
Means whatever the program will do, I want all that information in log file. so that if any error occurs atclient side, I can trace the error by looking at log file
I think the above explaination is enough to understand my problem.
If u ve any idea or suggestions plz share with me
Thank u
DeepT
February 28th, 2008, 08:40 AM
I created a log file class for some CPP applications, I am sure it would work the same way under C#. I have no idea if there are any special log file API calls.
Basically create a static class that can be called anywhere, like Logger.WriteLog(), or Logger.SetLogLevel(), etc...
The WriteLog function should probably perpend some extra info on each log line such as the current date and time, and perhaps the calling class and method.
The other thing you need to worry about is making sure you do not do unnecessary string operations because they are very expensive and will add up when you gets 100s of log statements in your code.
For example: Logger.WriteLog(3, string.format("The User Name is : %s", userName));
The problem with that is that even if logging is turned off the string.format() is still called every time you pass by it in code. This is bad.
You would want something like:
if ( Logger.CurrentLogLevel >= 3) { Logger.WriteLog(3, ...)));
In CPP I made a macro for that kind of stuff so my code didn't look ugly, but I do not think there is a way to do that in C#.
Anyhow that should give you a starting point.
torrud
February 28th, 2008, 09:17 AM
Another way is to use the Trace namespace or tools like Log4net (). I think there is no need to write an own logger by yourself.
boudino
February 29th, 2008, 01:29 AM
Or you can use Logging Application Block from Microsoft Enterprise Library (). It is free and it works. We are using it on enterprise application.
mariocatch
March 6th, 2008, 10:15 PM
I personally have setup a Logging class that like an above poster said, contains a static WriteToLog(String) method.
codeguru.com | http://forums.codeguru.com/archive/index.php/t-447268.html | crawl-003 | refinedweb | 472 | 72.56 |
As you might be aware, the C++ language is being updated by the ISO standard. The codename for the new C++ language is C++0x, and many compilers have already introduced some of the features. This tutorial is an attempt to give you an introduction to the new changes in the C++ language. Please note that I am explaining the new features for the Visual C++ 2010 compiler only, although they are applicable for other compilers as well. I do not comment for absolute syntax in other compilers.
This article assumes that you have moderate knowledge of C++, and that you know what type casting is, what const methods are, and what templates are (in a basic sense).
Following is the list of the new C++ language features that I will be discussing. I've put more emphasis on lambdas and R-values, since I do not find any digestible stuff anywhere. For now, I've not used templates or STL for simplicity, but I would probably update this article to add content on templates/STL.
auto
decltype
nullptr
The static_assert keyword
static_assert
#ifdef
C++ language features that were already included in VC8 and VC9 (VS2005, VS2008) but were not added into the C++ standard. These features are now classified in C++0x.
This article explains them (not all), in brief.
Let's get started!
The auto keyword now has one more meaning. I assume you do know the original purpose of this keyword. With the revised meaning, you can declare a local variable without specifying the data-type of the variable.
For example:
auto nVariable = 16;
The code above declares the nVariable variable without specifying its type. With the expression on the right side, the compiler deduces the type of the variable. Thus the above code would be translated by the compiler as:
nVariable
int nVariable = 16;
As you can also deduce, the assignment of the variable is now mandatory. Thus, you cannot declare the auto variable like:
auto nVariable ;
// Compiler error:
// error C3531: 'nVariable': a symbol whose type contains
// 'auto' must have an initializer
Here, the compiler does not (cannot) know the data type of the variable nResult. Please note that, with the auto keyword:
nResult
Having said that, no matter how complicated your assignment is, the compiler would still determine the data type. If the compiler cannot deduce the type, it would emit an error. This is not like in Visual Basic or web scripting languages.
auto nVariable1 = 56 + 54; // int deduction
auto nVariable2 = 100 / 3; // int deduction
auto nVariable3 = 100 / 3.0; // double deduction.
// Since compiler takes the whole expression to be double
auto nVariable4 = labs(-127); // long, Since return type of 'labs' is long
Let's get slightly complicated (continuing with the above declared variables):
// nVariable3 was deduced as double.
auto nVariable5 = sqrt(nVariable3);
// Deduced as double, since sqrt takes 3 different datatypes,
// but we passed double, and that overload returns double!
auto nVariable = sqrt(nVariable4);
// Error since sqrt call is ambiguous.
// This error is not related to 'auto' keyword!
Pointer deductions:
auto pVariable6 = &nVariable1; // deduced as 'int*', since nVariable one is int.
auto pVariable = &pVariable6; // int**
auto* pVariable7 = &nVariable1; // int*
Reference deductions:
auto & pVariable = nVariable1; // int &
// Yes, modifying either of these variable with modify the other!
With the new operator:
new
auto iArray = new int[10]; // int*
With the const and volatile modifiers:
const
volatile
const auto PI = 3.14; // double
volatile auto IsFinished = false; // bool
const auto nStringLen = strlen("CodeProject.com");
Arrays cannot be declared:
auto aArray1[10];
auto aArray2[]={1,2,3,4,5};
// error C3532: the element type of an array
// cannot be a type that contains 'auto'
Cannot be a function argument or return type:
auto ReturnDeduction();
void ArgumentDeduction(auto x);
// C3533: 'auto': a parameter cannot have a type that contains 'auto'
If you need an auto return type or auto arguments, you can simply use templates!
You cannot have auto in a class or struct, unless it is a static member:
class
struct
struct AutoStruct
{
auto Variable = 10;
// error C2864: 'AutoStruct::Variable' : only static const
// integral data members can be initialized within a class
};
You cannot have multiple data-types (types that can be deduced to different types):
auto a=10, b=10.30, s="new";
// error C3538: in a declarator-list 'auto'
// must always deduce to the same type
Likewise, if you initialize variables with different functions, and one or more function returns different data types, the compiler would emit the same error (C3538):
auto nVariable = sqrt(100.0), nVariableX = labs(100);
You can use the auto keyword at a global level.
This variable may seem to be a boon for you, but can be a curse if misused. For example, a few programmers assume the following declares float, but actually declares double.
float
double
auto nVariable = 10.5;
Similarly, if a function returns int, and then you modify the function return type to return short or double, the original automatic variable definition would go wary. If you are unlucky, and place only one variable in the auto declaration, the compiler would just deduce that auto- variable with the new type. And, if you are lucky, and mixed that variable with other variables, the compiler would raise a C3538 (see above).
int
short
int nLength = strlen("The auto keyword.");
would return a 4-byte integer on a 32-bit compilation, but would return an 8-byte int on a 64-bit compilation. Sure thing, you can use size_t, instead of int or __int64. What if the code is compiled where size_t isn't defined, or strlen returns something else? In that case, you can simply use auto:
size_t
__int64
strlen
auto nLength = strlen("The auto keyword.");
std::vector<std::string> Strings; // string vector
// Push several strings
// Now let's display them
for(std::vector<std::string>::iterator iter =
Strings.begin(); iter != Strings.end(); ++iter)
{ std::cout << *iter << std::endl; }
You know that typing the type std::vector<std::string>::iterator iter is cumbersome, error prone, and makes code less readable. Though, the option exists to typedef the return type somewhere else in the program and use the type name. But for how many iterator types? And, what if the iterator-type is used only once? Thus, we shorten the code as follows:
std::vector<std::string>::iterator iter
typedef
for(auto iter = Strings.begin(); iter != Strings.end(); ++iter)
{ std::cout << *iter << std::endl; }
If you have been using STL for a while, you know about iterators and constant iterators. For the above example, you might prefer to use const_iterator, instead of iterator. Thus, you may want to use:
const_iterator
iterator
// Assume 'using namespace std'
for(vector<string>::const_iterator iter =
Strings.begin(); iter != Strings.end(); ++iter)
{ std::cout << *iter << std::endl; }
Thus making the iterator const, so that it cannot modify an element of the vector. Remember that when you call the begin method on a const object, you cannot assign it to a non-const iterator, and you must assign it to a const_iterator (const iterator is not the same as const_iterator; since I am not writing about STL, please read/experiment about it yourself).
vector
begin
To overcome all these complexities, and to aid the auto keyword, standard C++ now facilitates the cbegin, cend, crbegin, and crend methods for STL containers. The c prefix means constant. They always return const_iterator, irrespective of if the object (container) is a const or not. Old methods returns both types of iterators, depending on the constness of the object. The modified code:
cbegin
cend
crbegin
crend
// With cbegin the iterator type is always constant.
for(auto iter = Strings.cbegin(); iter!=Strings.cend(); ++iter) {...}
Another example can be an iterator/constant iterator on:
map<std::vector<int>, string> mstr;
map<vector<int>, string>::const_iterator m_iter = mstr.cbegin();
The iterator assignment code can be shortened as:
auto m_iter = mstr.cbegin();
Just like complex templates, you can use the auto keyword to assign hard-to-type, error prone function pointers, which might be assigned from other variables/functions. I assume you do understand what I mean by this, thus no example is given.
Refer to the explanation about lambdas below in this article.
Though not related to lambdas, learning lambda expression syntax is required. So I will be discussing this one after lambdas.
This C++ operator gives the type of the expression. For example:
int nVariable1;
...
decltype(nVariable1) nVariable2;
declares nVariable2 of int type. The compiler knows the type of nVariable1, and translates decltype(nVariable1) as int. The decltype keyword is not the same as the typeid keyword. The typeid operator returns the type_info structure, and it also requires RTTI to be enabled. Since it returns type-information, and not type itself, you cannot use typeid like:
nVariable2
nVariable1
decltype(nVariable1)
typeid
type_info
typeid(nVariable1) nVariable2;
whereas, decltype deduces the expression as a type, perfectly at compile time. You cannot get the type-name (like 'int') with decltype.
decltype is typically used in conjunction with the auto keyword. For instance, you have declared an automatic variable as:
auto xVariable = SomeFunction();
Assume the type of xVariable (actually, the return type of SomeFunction) is X. Now, you cannot call (or don't want to call) the same function again. How would you declare another variable of the same type?
xVariable
SomeFunction
Which one of the following suits you?
decltype(SomeFunc) yVar;
decltype(SomeFunc()) yVar;
The first one declares yVar of type function-pointer, and the second one declares it to be of type X. As you can assess, using the function name is not reliable, since the compiler will not give an error or warning until you use the variable. Also, you must pass the actual number of arguments, and the actual type of arguments of the function/method is overloaded.
yVar
The recommended approach is to deduce the type from the variable directly:
decltype(xVariable) yVar;
Furthermore, as you have seen in the auto discussion, using (typing) the template types is complicated and ugly, and you should use auto. Likewise, you can/should use decltype to state the proper type:
decltype(Strings.begin()) string_iterator;
decltype(mstr.begin()->second.get_allocator()) under_alloc;
Unlike the previous examples, where we used auto to deduce the type from the expression on the right side, we deduce the type without assigning. With decltype, you need not assign the variable, just declare it - since the type is already known. Note that the function is not being called when you use the Strings.begin() expression, it is just deducing the type from the expression. Similarly, when you put the expression in decltype, the expression will not be evaluated. Only the basic syntax check will be performed.
Strings.begin()
In the second example above, mstr is a std::map object, where we are retrieving the iterator, the second member of that map element, and finally its allocator type. Thus, the deduced type is std::allocator for string (see above where mstr is declared).
mstr
std::
map
second
std::allocator
string
Few good, though absurd, examples:
decltype(1/0) Infinite; // No compiler error for "divide by zero" !
// Program does not 'exit', only type of exit(0), is determined.
// Specifying exit without function call would make
// the return type of 'MyExitFunction' different!
decltype(exit(0)) MyExitFunction();
The null-pointer finally got its classification in the form of a keyword! It is mostly the same as the NULL macro or integer 0. Though I am covering only native C++, it must be mentioned however that the nullptr keyword can be used in native (unmanaged code) as well as in managed code. If you write mixed mode code in C++, you may use the __nullptr keyword to explicitly state the native-null-pointer, and nullptr to express the managed null. Even in a mixed mode program, you'd rarely need to use __nullptr.
NULL
__nullptr
void* pBuffer = nullptr;
...
if ( pBuffer == nullptr )
{ // Do something with null-pointer case }
// With classes
void SomeClass::SomeFunction()
{
if ( this != nullptr)
{ ... }
}
Remember, nullptr is a keyword, not a type. Thus, you cannot use the sizeof or decltype operator on it. Having said that, the NULL macro and the nullptr keyword are two different entities. NULL is just 0, which is nothing but int.
sizeof
void fx(int*){}
void fx(int){}
int main()
{
fx(nullptr); // Calls fx(int*)
fx(NULL); // Calls fx(int)
}
(The /clr compiler option requirement is wrong. MSDN is not updated, as of this writing.)
With the static_assert keyword, you can verify some condition at compile time. Here is the syntax:
static_assert( expression, message)
The expression has to be a compile time constant-expression. For non-templated static assertions, the compiler immediately evaluates the expression. For a template assertion, the compiler tests the assert for and when the class is instantiated.
If the expression is true, that means your required assertion (requirement) is fulfilled, and the statement does nothing. If the expression is false, the compiler raises an error C2338 with the message you mentioned. For example:
static_assert (10==9 , "Nine is not equal to ten");
Is it obviously not true, thus the compiler raises:
error C2338: Nine is not equal to ten
The more meaningful assertion, which would be raised when the program is not being compiled as 32-bit:
static_assert(sizeof(void *) == 4,
"This code should only be compiled as 32-bit.");
Since the size of any type of pointer is the same as the target platform chosen for compilation.
For earlier compilers, we need to use _STATIC_ASSERT, which does nothing but declare an array of size-condition. Thus, if the condition is true, it declares an array of size 1; if the condition is false, it declares an array of size 0 - which results in a compiler error. The error is not user friendly.
_STATIC_ASSERT
This is one of the most striking language features added to C++. Useful, interesting, and complicated too! I will start with the absolute basic syntax and examples, to make things clear. Thus, the first few code examples below may not feature the usefulness of lambdas. But, be assured, lambdas are a very powerful, yet code-concise feature of the C++ language!
Before we start, let me brief it first:
The absolute basic lambda:
[]{}; // In some function/code-block, not at global level.
Yes, the above code is perfectly valid (in C++0x only!).
[] is the Lambda-introducer, which tells the compiler that the expression/code followed is lambda. {} is the definition of the lambda, just like any function/method. The lambda defined above does not take any arguments, doesn't return any value, and of course, doesn't do anything.
[]
{}
Let's proceed...
[]{ return 3.14159; }; // Returns double
The lambda coded above does simple work: returns the value of PI. But who is calling this lambda? Where does the return value go? Let's proceed further:
double pi = []{ return 3.14159; }(); // Returns double
Making sense? The return value from the lambda is being stored in a local variable pi. Also, note in the above example the lambda being called (notice the function-call at the end). Here is a minimal program:
pi
int main()
{
double pi;
pi = []{return 3.14159;}();
std::cout << pi;
}
The parentheses at the end of the lambda are actually making a call to the lambda-function. This lambda doesn't take any arguments, but still, the operator () is required at the end so that the compiler would know the call. The pi lambda may also be implemented like:
()
pi = [](){return 3.14159;}(); // Notice the first parenthesis.
which is similar to:
pi = [](void){return 3.14159;}(); // Note the 'void'
Though, it is a matter of choice if you put the first parenthesis for the argument-less lambdas, or not. But I prefer you put them. The C++ standard committee wanted to make lambdas less complicated, that's why they (might have) made the lambda-parameter-specification optional for parameter-less lambdas.
Let's move further, where the lambda takes an argument:
bool is_even;
is_even = [](int n) { return n%2==0;}(41);
The first parenthesis, (int n), specifies the parameter-specification of the lambda. The second, (41), passes the value to the lambda. The body of the lambda tests if the passed number is divisible by 2 or not. We can now implement the max or min lambda, as follows:
(int n)
(41)
int nMax = [](int n1, int n2) {
return (n1>n2) ? (n1) : (n2);
} (56, 11);
int nMin = [](int n1, int n2) {
return (n1<n2) ? (n1) : (n2);
} (984, 658);
Here, instead of declaring and assigning variables separately, I put them in a single line. The lambdas now take two arguments, and return one of the values, which would be assigned to nMin and nMax. Likewise, the lambda can take more arguments, and of multiple types also.
nMin
nMax
A few questions you should have:
Before I answer them one by one, let me present to you the Lambda Expression Grammar with the following illustration:
You can specify the return type after the -> operator. For example:
->
pi = []()->double{ return 3.14159; }();
Remember, as shown in the illustration, if the lambda contains only one statement (i.e., only a return statement), there is no need to specify the return type. So, in the example above, specifying double as the return type is optional. It is up to you if you should specify the return type for automatic inferential return types.
return
An example where specifying the return type is mandatory:
int nAbs = [] (int n1) -> int
{
if(n1<0)
return -n1;
else
return n1;
}(-109);
If you do not specify -> int, the compiler would raise:
-> int
error C3499: a lambda that has been specified to have
a void return type cannot return a value
If the compiler does not see only a return statement, it infers the lambda as having a void return type. The return type can be anything:
void
[]()->int* { }
[]()->std::vector<int>::const_iterator& {}
[](int x) -> decltype(x) { }; // Deducing type of 'x'
It cannot return arrays. It also cannot have auto as the return type:
[]()-> float[] {}; // error C2090: function returns array
[]()-> auto {}; // error C3558: 'auto': a lambda return type cannot contain 'auto'
Yes, of course, you can put a return value of lambda into an auto variable:
auto pi = []{return 3.14159;}();
auto nSum = [](int n1, int n2, int n3)
{ return n1+n2+n3; } (10,20,70);
auto xVal = [](float x)->float
{
float t;
t=x*x/2.0f;
return t;
} (44);
As a last note, if you specify the return-type to a parameter-less lambda, you must use parentheses. The following is an error:
[]->double{return 3.14159;}(); // []()->double{...}
The explanation above is sufficient enough to disclose that a lambda can contain any code a regular function can have. A lambda can contain everything a function/method can have - local variables, static variables, calls to other functions, memory allocation, and other lambdas too! The following code is valid (absurd though!):
[]()
{
static int stat=99;
class TestClass
{
public:
int member;
};
TestClass test;
test.member= labs(-100);
int ptr = [](int n1) -> int*
{
int* p = new int;
*p = n1;
return p;
}(test.member);
delete ptr;
};
Let's define a lambda that determines if a number is even or not. With the auto keyword, we can store the lambda in a variable. Then we can use the variable (i.e., call the lambda)! I will discuss what the type of the lambda is later. It is as simple as:
auto IsEven = [](int n) -> bool
{
if(n%2 == 0)
return true;
else
return false;
}; // No function call!
As you can infer, the lambda's return type is bool, and it is taking an argument. And importantly, we are not calling the lambda, just defining it. If you put (), with some argument, the type of the variable would have been bool, not lambda-type! Now the locally defined function (i.e., lambda) can be called after the above statement:
bool
IsEven(20);
if( ! IsEven(45) )
std::cout << "45 is not even";
The definition of IsEven, as given above, is in the same function in which two calls have been made. What if you want the lambdas to be called from other functions? Well, there are approaches, like storing in some local or class-level variable, passing it to another function (just like a function pointer), and calling from another function. Another mechanism is to store and define the function at global scope. Since I haven't discussed what the type-of-lambda is, we'll use the first approach later. But let's discuss the second approach (global-scope):
IsEven
Example:
// The return type of lambda is bool
// The lambda is being stored in IsEven, with auto-type
auto IsEven = [](int n) -> bool
{
if(n%2 == 0) return true;
else return false;
}
void AnotherFunction()
{
// Call it!
IsEven (10);
}
int main()
{
AnotherFunction();
IsEven(10);
}
Since the auto keyword is applicable only for local or global scope, we can use it to store lambdas. We need to know the type so that we can store it in a class variable. Later on.
As mentioned earlier, a lambda can almost do what a regular function can do. So, displaying a value isn't a remote thing that lambda cannot do. It can display a value.
int main()
{
using namespace std;
auto DisplayIfEven= [](int n) -> void
{
if ( n%2 == 0)
std::cout << "Number is even\n";
else
std::cout << "Number is odd\n";
}
cout << "Calling lambda...";
DisplayIfEven(40);
}
One important thing to note is that locally-defined lambdas do not get the namespace resolution from the upper-scope they are being defined in. Thus, the std namespace inclusion is not available for DisplayIfEven.
std
DisplayIfEven
Definitely. Provided the lambda/function name is known at the time of call, as it is required for the function call in a function.
No.
Now I will discuss the thing I kept empty till now: Capture Specification.
Lambdas can be one of the following:
The state defines how variables from a higher scope are captured. I define them into the following categories:
You should understand the four categories are derivations of the following C++ mantras:
private
Let's play with captures! The capture specification, as mentioned in the above illustration, is given in []. The following syntax is used to specify capture-specification:
[=]
[&]
[var]
var
[&var]
Example 1:
int a=10, b=20, c=30;
[a](void) // Capturing ONLY 'a' by value
{
std::cout << "Value of a="<<
a << std::endl;
// cannot modify
a++; // error C3491: 'a': a by-value capture
// cannot be modified in a non-mutable lambda
// Cannot access other variables
std::cout << b << c;
// error C3493: 'b' cannot be implicitly captured
// because no default capture mode has been specified
}();
Example 2:
auto Average = [=]() -> float // '=' says: capture all variables, by value
{
return ( a + b + c ) / 3.0f;
// Cannot modify any of the variables
};
float x = Average();
Example 3:
// With '&' you specify that all variables be captured by REFERENCE
auto ResetAll = [&]()->void
{
// Since it has captured all variables by reference, it can modify them!
a = b = c = 0;
};
ResetAll();
// Values of a,b,c is set to 0;
Putting = specifies by-value. Putting & specifies by-reference. Let's explore more about these. For shortness, now I am not putting lambdas into an auto variable and then calling them. Instead, I am calling them directly.
=
&
Example 4:
// Capture only 'a' and 'b' - by value
int nSum = [a,b] // Did you remember that () is optional for parameterless lambdas!?
{
return a+b;
}();
std::cout << "Sum: " << nSum;
As shown in example 4, we can specify multiple capture specifications in a lambda-introducer (the [] operator). Let's take another example, where the sum of all three (a, b, c) would be stored into the nSum variable.
a
b
c
nSum
Example 5:
// Capture everything by-value, BUT capture 'nSum' by reference.
[=, &nSum]
{
nSum = a+b+c;
}();
In the above example, the capture-all-by-value (i.e., = operator) specifies the default capture mode, and the &nSum expression overrides that. Note that the default capture mode, which specifies all-capture, must appear before other captures. Thus, = or & must appear before other specifications. The following causes an error:
&nSum
// & or = must appear as first (if specified).
[&nSum,=]{}
[a,b,c,&]{} // Logically same as above, but erroneous.
A few more examples:
[&, b]{}; // (1) Capture all by reference, but 'b' by value
[=, &b]{}; // (2) Capture all by value, but 'b' by reference
[b,c, &nSum]; // (3) Capture 'b', 'c' by value,
// 'nSum' by reference. Do no capture anything else.
[=](int a){} // (4) Capture all by value. Hides 'a' - since a is now
// function argument. Bad practise. Compiler doesn't warn!
[&, a,c,nSum]{}; // Same as (2).
[b, &a, &c, &nSum]{} // Same as (1)
[=, &]{} // Not valid!
[&nSum, =]{} // Not valid!
[a,b,c, &]{} // Not valid!
As you can see, there are multiple combinations to capture the same set of variables. We can extend the capture-specification syntax by adding:
[&,var]
[=, &var]
[var1, var2]
var1
var2
[&var1, &var2]
[var1, &var2]
Till now, we have seen that we can prevent some variables from being captured, capture by-value const, and capture by reference non-const. Thus, we have covered 1, 2, and 4 of the capture-categories (see above). Capturing const reference is not possible (i.e., [const &a]). We will now look into the last one - capturing in call-by-value mode.
[const &a]
Just after the parentheses of a parameter-specification, we specify the mutable keyword. With this keyword, we put all by-value captured variables into call-by-value mode. If you do not put the mutable keyword, all by-value variables are constant, you cannot modify them in lambda. Putting mutable enforces the compiler to create copies of all variables which are being captured by-value. You can then modify all by-value captures. There is no method to selectively capture const and non-const by-value. Or simply, you can think of them being passed to the lambda as an argument.
mutable
int x=0,y=0,z=0;
[=]()mutable->void // () are required, when you specify 'mutable'
{
x++;
// Since all variable are captured in call-by-value mode,
// compiler raises warning that y,z are not used!
}();
// the value of x remain zero
After the lambda-call, the value of 'x' remains zero. Since only a copy of x is modified, not the reference. It is also interesting to know that the compiler raises a warning only for y and z, and not the previously defined (a, b, c...) variables. However, it doesn't complain if you use previously defined variables. Smart compiler - I cannot speak more on it!
x
y
z
Function-pointers do not maintain state. Lambdas do. With by-reference captures, lambdas can maintain their state between calls. Functions cannot. Function pointers are not type safe, they are prone to errors, we must mangle with calling-conventions, and requires complicated syntax.
Function-objects do maintain states very well. But even for a small routine, you must write a class, place some variables into it, and overload the () operator. Importantly, you must do this outside the function block so that the other function, which is supposed to call the operator() for this class, must know it. This breaks the flow of the code.
operator()
Lambdas are actually classes. You can store them in a function class object. This class, for lambdas, is defined in the std::tr1 namespace. Let's look at an example:
function
std::tr1
#include<functional>
....
std::tr1::function<bool(int)>s IsEven = [](int n)->bool { return n%2 == 0;};
...
IsEven(23);
The tr1 namespace is for Technical Report 1, which is used by the C++0x committee members. Please search by yourself for more information. <bool(int)> expresses the templates parameter for the function class, which says: the function returns a bool and takes an argument int. Depending on the lambda being put into the function object, you must typecast it properly; otherwise, the compiler would emit an error or warning for type-mismatch. But, as you can see, using the auto keyword is much more convenient.
tr1
<bool(int)>
There are cases, however, where you must use a function - when you need to pass lambdas across function calls. For example:
using namespace std::tr1;
void TakeLambda(function<void(int)> lambda)
// Cannot use 'auto' in function argument
{
// call it!
lambda(32);
}
// Somewhere in program ...
TakeLambda(DisplayIfEven); // See code above for 'DisplayIfEven'
The DisplayIfEven lambda (or function!) takes int, and returns nothing. The function class is used the same way as the argument in TakeLambda. Further, it calls the lambda, which eventually calls the DisplayIfEven lambda.
TakeLambda
I have simplified TakeLamba, which should have been (shown incrementally):
TakeLamba
// Reference, should not copy 'function' object
void TakeLambda(function< void(int) > & lambda);
// Const reference, should not modify function object
void TakeLambda(const function< void(int) > & lambda);
// Fully qualified name
void TakeLambda(const std::tr1::function< void(int) > & lambda);
Lambdas are very useful for many STL functions - functions that require function-pointers or function-objects (with operator() overloaded). In short, lambdas are useful for those routines that demand callback functions. Initially, I will not cover the STL functions, but explain the usability of lambdas in a simpler and understandable form. The non-STL examples may be superfluous and nonsense, but quite capable of clearing out this topic.
For example, the following function requires a function to be passed. It will call the passed function. The function-pointer, function-object, or the lambda should be of a type that returns void and takes an int as the sole argument.
void CallbackSomething(int nNumber, function<void(int)> callback_function)
{
// Call the specified 'function'
callback_function(nNumber);
}
Here, I call the CallbackSomething function in three different ways:
CallbackSomething
// Function
void IsEven(int n)
{
std::cout << ((n%2 == 0) ? "Yes" : "No");
}
// Class with operator () overloaded
class Callback
{
public:
void operator()(int n)
{
if(n<10)
std::cout << "Less than 10";
else
std::cout << "More than 10";
}
};
int main()
{
// Passing function pointer
CallbackSomething(10, IsEven);
// Passing function-object
CallbackSomething(23, Callback());
// Another way..
Callback obj;
CallbackSomething(44, obj);
// Locally defined lambda!
CallbackSomething(59, [](int n) { std::cout << "Half: " << n/2;} );
}
Okay! Now I want that the Callback class can display if a number is greater than some N number (instead of a constant 10). We can do it this way:
Callback
class Callback
{
/*const*/ int Predicate;
public:
Callback(int nPredicate) : Predicate(nPredicate) {}
void operator()(int n)
{
if( n < Predicate)
std::cout << "Less than " << Predicate;
else
std::cout << "More than " << Predicate;
}
};
In order to make this callable, we just need to construct it with some integer constant. The original CallbackSomething need not be changed - it still can call a routine with an integer argument! This is how we do it:
// Passing function-object
CallbackSomething(23, Callback(24));
// 24 is argument to Callback CTOR, not to CallbackSomething!
// Another way..
Callback obj(99); // Set 99 are predicate
CallbackSomething(44, obj);
This way, we made the Callback class capable of maintaining its state. Remember, as long as the object remains, its state remains. Thus, if you pass an obj object into multiple calls of CallbackSomething (or any other similar function), it will have the same Predicate (state). As you know, this is not possible with function pointers - unless we introduce another argument to the function. But doing so breaks the entire program structure. If a particular function is demanding a callable function, with a specific type, we need to pass a function of that type only. Function pointers are unable to maintain state, and thus are unusable in these kind of scenarios.
obj
Is this possible with lambdas? As mentioned previously, lambdas can maintain state through capture specification. So, yes, it is possible with lambdas to achieve this stateful functionality. Here is the modified lambda, being stored in an auto variable:
int Predicate = 40;
// Lambda being stored in 'stateful' variable
auto stateful = [Predicate](int n)
{ if( n < Predicate)
std::cout << "Less than " << Predicate;
else
std::cout << "More than " << Predicate;
};
CallbackSomething(59, stateful ); // More than 40
Predicate=1000;
CallbackSomething(100, stateful); // Predicate NOT changed for lambda!
The stateful lambda is locally defined in a function, is concise than a function-object, and cleaner than a function pointer. Also, it now has its state. Thus, it will print "More than 40" for the first call, and the same thing for the second call as well.
stateful
Note that Predicate is passed as by-value (non-mutable also), so modifying the original variable will not affect its state in lambda. To reflect the predicate-modification in lambda, we just need to capture this variable by reference. When we change the lambda as follows, the second call will print "Less than 1000".
Predicate
auto stateful = [&Predicate](int n) // Capturing by Reference
This is similar to adding a method like SetPredicate in a class that would modify the predicate (state). Please see the VC++ blog, linked below, for a discussion on lambda - class mapping (the blogger calls it mental translation).
SetPredicate
The for_each STL function calls the specified function for each element in the range/collection. Since it uses a template, it can take any type of data-type as its argument. We will use this as an example for lambdas. For simplicity, I would use plain arrays, instead of vectors or lists. For example:
for_each
using namespace std;
int Array[10] = {1,2,3,4,5,6,7,8,9,10};
for_each(Array, &Array[10], IsEven);
for_each(Array, Array+10, [](int n){ std::cout << n << std::endl;});
The first call calls the IsEven function, and the second call calls the lambda, defined within the for_each function. It calls both of the functions 10 times, since the range contains/specifies 10 elements in it. I need not repeat that the second argument to for_each is exactly same (oh! but I repeated!).
This was a very simple example, where for_each and lambdas can be utilized to display values without needing to write a function or class. For sure, a lambda can be extended further to perform extra work - like displaying if a number is prime or not, or calculating the sum (use reference-by-capture), or to modify (say, multiply by 4) the element of a range.
Well, yes! You can do that. For long, I talked about taking captures by references and making modifications, but did not cover modifying the argument itself. The need did not arise till now. To do this, just take the lambda's parameter by reference (or pointer):
// The 'n' is taken as reference (NOT same as capture-by-reference!)
for_each(Array, Array+10, [](int& n){ n *= 4; });
The above for_each call multiplies each element of Array by 4.
Array
Like I explained how to utilize lambdas with the for_each function, you can use it with other <algorithm> functions like transform, generate, remove_if, etc. Lambdas are not just limited to STL algorithms, they can also be efficiently used wherever a function-object is required. You need to make sure it takes the proper number and type of arguments, and check if it needs argument modifications and things like that. Since this article is not about STL or templates, I will not discuss this further.
transform
generate
remove_if
Yes, quite disappointing and confusing, but true! You cannot use a lambda as an argument to a function that requires a function-pointer. Through sample code, let me first express what I am trying to say:
// Typedef: Function pointer that takes and int
typedef void (*DISPLAY_ROUTINE)(int);
// The function, that takes a function-pointer
void CalculateSum(int a,int b, DISPLAY_ROUTINE pfDisplayRoutine)
{
// Calling the supplied function pointer
pfDisplayRoutine(a+b);
}
CalculateSum takes a function-pointer of type DISPLAY_ROUTINE. The following code would work, as we are supplying a function-pointer:
CalculateSum
DISPLAY_ROUTINE
void Print(int x)
{
std::cout << "Sum is: " << x;
}
int main()
{
CalculateSum(500,300, Print);
}
But the following call will not:
CalculateSum (10, 20, [](int n) {std::cout<<"sum is: "<<n;} );
// C2664: 'CalculateSum' : cannot convert parameter 3 from
// '`anonymous-namespace'::<lambda1>' to 'DISPLAY_ROUTINE'
Why? Because lambdas are object-oriented, they are actually classes. The compiler internally generates a class-model for the lambdas. That internally generated class has operator () overloaded; and has some data members (inferred via capture-specification and mutable-specification) - those may be const, reference, or normal member variables and classic stuff like that. That class cannot be downgraded to a normal function-pointer.
operator ()
Well, because of the smart class named std::function! See (above) that CallbackSomething is actually taking function as an argument, not a function-pointer.
std::function
As with for_each - this function doesn't take std::function, but uses a template instead. It directly calls the passed argument with parenthesis. Carefully understand the simplified implementation:
template <class Iteartor, class Function>
void for_each(Iteartor first, Iterator, Function func)
// Ignore return type,and other arguments
{
// Assume the following call is in loop
// The 'func' can be normal function, or
// it can be a class object, having () operator overloaded.
func(first);
}
Likewise, other STL functions, like find, count_if etc., would work will all three cases: function-pointers, function-objects, and lambdas.
find
count_if
Thus, if you plan to use lambdas in APIs like SetTimer, EnumFontFamilies, etc. - unplan it! Even with forceful typecasting the lambda (by taking its address), it won't work. The program will crash at runtime.
SetTimer
EnumFontFamilies
Let's start with a simple example. Following is a function whose return type is long. This is not a lambda, but a function.
long
auto GetCPUSpeedInHertz() -> long
{
return 1234567890;
}
It returns a long, as you can see. It uses the new syntax of specifying a return type, known as Trailing Return Type. The keyword auto on the left is just a placeholder, the actual type is specified after the -> operator. One more example:
auto GetPI() -> decltype(3.14)
{
return 3.14159;
}
Where the return type is deduced from the expression. Please re-read about the decltype keyword above, to recollect. For both of the functions given above, you obviously need not use this feature!
Consider the template function:
template <typename FirstType, typename SecondType>
/*UnknonwnReturnType*/ AddThem(FirstType t1, SecondType t2)
{
return t1 + t2;
}
The function adds two arbitrary values, and returns it. Now, if I pass an int and a double as the first and second arguments, respectively, what should the return type be? You'd say double. Does that mean we should make SecondType the return type of the function?
SecondType
template <typename FirstType, typename SecondType>
SecondType AddThem(FirstType t1, SecondType t2);
Actually, we cannot. For the obvious reason that this function may be called with any type of argument on the left or right side, and either type can be of a higher magnitude. For example:
AddThem(10.0, 'A');
AddThem("CodeProject", ".com");
AddThem("C++", 'X');
AddThem(vector_object, list_object);
Also, the operator + (in the function) may call another overloaded function that may return a third type. The solution is to use the following:
+
template <typename FirstType, typename SecondType><typename />
auto AddThem(FirstType t1, SecondType t2) -> decltype(t1 + t2)
{
return t1 + t2;
}
As mentioned in decltype's explanation, that type is determined though the expression; the actual type of t1+t2 is determined that way. If the compiler can upgrade the type, it will (like int, double upgrades to double). If type/types are of class(es), and + leads an overloaded operator to be called, the return type of that overloaded + operator would be the return type. If types are not native, and no overload could be found, the compiler would raise an error. It is important to note that the type deduction will only take place when you instantiate the template function with some data-types. Before that, the compiler won't bother checking anything (same rules as with normal template functions).
t1+t2
I assume that you know what call-by-value, by reference, and by constant reference mean. I further assume that you know what L-value and R-value mean. Now, let's take an example where R-value references would make sense:
class Simple {};
Simple GetSimple()
{
return Simple();
}
void SetSimple(const Simple&)
{ }
int main()
{
SetSimple( GetSimple() );
}
Here, you can see that the GetSimple method returns a Simple object. And, SetSimple takes a Simple object by reference. In a call to SetSimple, we are passing GetSimple - as you can see, the returned object is about to be destroyed, as soon as SetSimple returns. Let's extend SetSimple:
GetSimple
Simple
SetSimple
void SetSimple(const Simple& rSimple)
{
// Create a Simple object from Simple.
Simple object (rSimple);
// Use object...
}
Kindly ignore the missing copy constructor, we are using the default copy constructor. For understanding, assume the copy constructor (or a normal constructor) is allocating some amount of memory, say 100 bytes. The destructor is supposed to destroy 100 bytes. Don't get the problem in here? Okay, let me explain. Two objects are being created (one in GetSimple, one in SetSimple), and both are allocating 100 bytes of memory. Right? This is like copying a file/folder to another location. But as you can see from the example code, only 'object' is being utilized. Then, why should we allocate 100 bytes twice? Why cannot we use the 100 bytes allocated by the first Simple object construction? In earlier versions of C++, there was no simple way, unless we wrote our own memory/object management routines (like the MFC/ATL CString class does). In C++0x, we can do that. Thus, in short, we'll optimize the routine this way:
object
CString
null
By this, we save 100 bytes! Not a big amount, though. But if this feature is used in larger containers like strings, vectors, list, it would save huge amounts of memory, and time, both! Thus, it would improve the overall application performance. Though the problem and solution is available in the form of RVO and NRVO (Named Return Value Optimization), in Visual C++ 2005 and later versions, it is not as efficient and meaningful. For this, we use a new operator introduced: R-value Reference Declarator: &&. Basic syntax: Type&& identifier. Now we modify the above code, step by step:
&&
void SetSimple(Simple&& rSimple) // R-Value NON-CONST reference
{
// Performing memory assignment here, for simplicity.
Simple object;
object.Memory = rSimple.Memory;
rSimple.Memory = nullptr;
// Use object...
delete []object.Memory;
}
The above code is for moving the content from the old object to the new object. This is very similar to moving a file/folder. Note that the const has been removed, since we also need to reset (detach) the memory originally allocated by the first object. The class and GetSimple are modified as mentioned below. The class now has a memory-pointer (say, void*) named Memory. The default constructor sets it as null. This member is made public for simplifying the topic.
void*
Memory
class Simple
{
public:
void* Memory;
Simple() { Memory = nullptr; }
Simple(int nBytes) { Memory = new char[nBytes]; }
};
Simple GetSimple()
{
Simple sObj(10);
return sObj;
}
What if you make a call like this:
Simple x;
SetSimple(x);
It would result in an error since the compiler cannot convert Simple to Simple&&. The variable 'x' is not temporary, and cannot behave like an R-value reference. For this, we may provide an overloaded SetSimple function that takes Simple, Simple&, or const Simple&. Thus, you know by now that temporary objects are actually R-value references. With R-values, you achieve what is known as move semantics. Move semantics enables you to write code that transfers resources (such as dynamically allocated memory) from one object to another. To implement move semantics, we need to provide a move constructor, and optionally a move assignment operator (operator =), to the class.
Simple&&
Simple&
const Simple&
operator =
Let's implement moving the object within the class itself with the help of a move constructor. As you know, a copy constructor would have a signature like:
Simple(const Simple&);
The move-constructor would be very similar - just one more ampersand:
Simple(Simple&&);
But as you can see, the move-constructor is non-const. Like a copy constructor can take a non-const object (thus modify the source!), the move-constructor can also take const; nothing prevents this - but doing so forfeits the whole purpose of writing a move-constructor. Why? If you understood correctly, we are detaching the resource ownership from the original source (the argument of the move-constructor). Before I write more words to confuse you, let's take an example where the so-called move-constructor may be called:
Simple GetSimple()
{
Simple sObj(10);
return sObj;
}
Why? The object sObj has been created on the stack. The return type is Simple, which would mean the copy-constructor (if provided; otherwise, the default compiler provided) would be called. Further, the destructor for sObj would be called. Now, assume the move-constructor is available. In that case, the compiler knows the object is being moved (ownership transfer), and it would call the move-constructor instead of the copy-constructor.
sObj
Here is the updated Simple class implementation:
class Simple
{
// The resource
void* Memory;
public:
Simple() { Memory = nullptr; }
// The MOVE-CONSTRUCTOR
Simple(Simple&& sObj)
{
// Take ownership
Memory = sObj.Memory;
// Detach ownership
sObj.Memory = nullptr;
}
Simple(int nBytes)
{
Memory = new char[nBytes];
}
~Simple()
{
if(Memory != nullptr)
delete []Memory;
}
};
Here is what happens when you call the GetSimple function:
Simple(Simple&&)
~Simple()
Simple*
DTOR
Memory!=nullptr
We see that we moved the original data to the new object. This way, we saved memory and processing time. As mentioned earlier, this saving is negligent - but when it is employed in larger data structures, and/or when temporary-objects are created and destroyed a lot, the saving is paramount!
Understand the following code:
Simple obj1(40);
Simple obj2, obj3;
obj2 = obj1;
obj3 = GetSimple();
As you know, obj2 = obj1 would call the assignment-operator, there is no ownership transfer. The contents of obj2 are replaced with contents of obj1. If we don't provide an assignment operator, the compiler would provide the default assignment operator (and would copy byte-by-byte). The object on the right side remains unchanged.
obj2 = obj1
obj2
obj1
The signature of the user-defined operator can be:
// void return is put for simplicity
void operator=(const Simple&); // Doesn't modify source!
What about the statement: obj3 = GetSimple()? The object returned by GetSimple is temporary, as you should clearly know by now. Thus, we can (and we should) utilize what is known as Move- Semantics (we've used the same concept in the move-constructor also!). Here is a simplified move assignment-operator:
obj3 = GetSimple()
void operator=(Simple&&); // Modifies the source, since it is temporary
And here is the modified Simple class (previous code omitted for brevity). Self assignment is not taken care of:
class Simple
{
...
void operator = (const Simple& sOther)
{
// De-allocate current
delete[] Memory;
// Allocate required amount of memory,
// and copy memory.
// The 'new' and 'memcpy' calls not shown
// for brevity. Another variable in this
// class is also required to hold buffersize.
}
void operator = (Simple&& sOther)
{
// De-allocate current
delete[] Memory;
// Take other's memory contnent
Memory = sOther.Memory;
// Since we have taken the temporary's resource.
// Detach it!
sOther.Memory = nullptr;
}
};
Thus, in the case of the obj3 = GetSimple() statement, the following things are happening:
Just like the move-constructor, the move-assignment operator, and the destructor (in short, all three) must agree with the same protocol for resource allocation/deallocation.
Assume the Simple class we have been working on is some data container; like string, date/time, array, or anything you prefer. That data container is supposed to allow the following, with the help of operator overloading:
Simple obj1(10), obj2(20), obj3, obj4; // Pardon me for using such names!
obj3 = obj1 + obj2;
obj2 = GetSimple() + obj1;
obj4 = obj2 + obj1 + obj3;
You can simply say, "Provide the plus (+) operator in the class". Okay, we provide an operator+ in our Simple class:
operator+
// This method is INSIDE the class
Simple operator+(const Simple&)
{
Simple sObj;
// Do binary + operation here...
return sObj;
}
Now, as you can see, a temporary object is created and is being returned from operator+, which would eventually cause a call to the move-assignment operator (for the obj3 = obj1 + obj2 expression), and the resource is preserved - fair enough! (I hope you understand it fully before you move to the next paragraph.) For the next statement (obj2 = GetSimple() + obj1), the object on the left itself is temporary. Note that in SetSimple and in the move special-functions, the argument is temporary, not in this. There is no technique (at least in my knowledge) to make this a temporary object. Okay, okay, I am not Bjarne Stroustrup; here is the solution:
obj3 = obj1 + obj2
obj2 = GetSimple() + obj1
class Simple
{
...
// Give access to helper function
friend Simple operator+(Simple&& left, const Simple& right);
};
// Left argument is temporary/r-value reference
Simple operator+(Simple&& left, const Simple& right)
{
// Simulated operator+
// Just shows the resource ownership/detachment
// Does not use 'right'
Simple newObj;
newObj.Memory = left.Memory;
left.Memory = nullptr;
return newObj;
}
Explanation about the code:
What about the last statement (obj4 = obj2 + obj1 + obj3)?
obj4 = obj2 + obj1 + obj3
obj2 + obj1
t1
obj2+obj1
t1+obj3
t2
obj4
Here it goes in a more simplified, non-verbal form (italic is the call being made):
This section lists the C++ features that were not added into the C++0x standard, but were added in VC8/VC9 compilers. They are now part of the C++0x standard.
What is the sizeof enum? Four bytes? Well, depending on the compiler you choose, the size could vary. Does sizeof an enum matter? Yes, if you put the enum as a member in a class/struct. The sizeof class/struct changes, which makes the code less portable. Also, if struct is to be stored in a file or transferred, the problem is further compounded. Strongly typed enums enforce type, thus save from any bug creeping in. They make the code more portable within the software system. The solution is to specify the base-type of an enum:
enum Priority : BYTE // unsigned char
{
VeryLow = 0,
Low,
Medium,
High,
VeryHigh
};
Which results in sizeof(Priority) to be 1 byte. Likewise, you can have any integral type as the base-type for an enum:
sizeof(Priority)
enum ByteUnit : unsigned __int64
{
Byte = 1,
KiloByte = 1024,
MegaByte = 1024L * 1024,
GigaByte = (unsigned __int64)1 << 30,
TeraByte = (unsigned __int64)1 << 40,
PetaByte = (unsigned __int64)1 << 50
};
The sizeof this enum becomes 8-bytes, since the base-type is unsigned __int64. If you do not specify the base-type, in this case, the compiler would warn you for putting an out of range value in the enum. Note: the Microsoft C/C++ compiler implements this feature only partially.
External reference: Proposal N2347.
When you declare templates of templates, like in the example below, you need to put extra white-space between the consecutive right angles (greater-than sign):
vector<list<int> > ListVector;
Otherwise, the compiler would emit an error, since >> is a valid C++ token (bitwise right shift). Other than multiple templates, this operator might appear when you typecast to a template, using the static_cast operator:
>>
static_cast
static_cast<vector<int>>(expression);
With the new C++0x standard, you can use consecutive right-angle brackets (more than twice also), like:
vector <vector<vector<int>>> ComplexVector;
External reference: Proposal N1757
I failed to find the exact purpose and meaning of extern templates. Anyway, I am sharing what I discovered with this term. True, that I might be wrong - and expect you to share your knowledge, so that I could update this section. This is what I ascertained:
Explicating point 1 clearly is out of my comprehension - the details available are vague and overlapping, so I am not discussing point (1). For example, you have a class:
template <typename T>
class Number
{
T data;
public:
Number() { data = 0; }
Number(T t) // or (const T& t)
{ data = t; }
T Add(T t) { return data + t; }
T Randomize(T t) { return data % t; }
};
Now, before you actually instantiate the template for some data-type, you want to make sure that the class compiles for that data type. That is, for this example, the type should support the + and % operators. Thus, you can specify the template instantiation in advance:
%
template Number<int>;
template Number<float>;
which would raise an error for the second specification, since operator % is not valid for float. Likewise, when you specify a template argument that doesn't support the operation the template class might need, the compiler would complain. For this template class, the template-type must support assignment to zero, assignment operator, operator +, and operator %. Note that we did not actually instantiate the template-class. This is just like declaring a function, and specifying the argument and return type. The function is externally defined somewhere else.
External reference: Proposal N1987.
Though this article is almost complete, there are may be a few glitches, spelling/grammatical mistakes, small mistakes in code etc. Please let me know of them. For the downloadable code - I am wondering if this content requires some code?
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
int main()
{
using namespace std;
auto DisplayIfEven= [](int n) -> void
{
if ( n%2 == 0)
std::cout << "Number is even\n";
else
std::cout << "Number is odd\n";
}
cout << "Calling lambda...";
DisplayIfEven(40);
}
// Program lambda1.cpp
#include <iostream>
int main()
{
using namespace std;
auto DisplayIfEven= [](int n) -> void
{
if ( n%2 == 0)
cout << "Number is even\n";
else
cout << "Number is odd\n";
};
cout << "Calling lambda...";
DisplayIfEven(40);
}
g++ -std=c++0x -Wall -pedantic lambda1.cpp
#include <cmath>
#include <iostream>
int main()
{
auto nVariable4 = labs(-127); // long, Since return type of 'labs' is long
auto nVariable = sqrt(nVariable4);
// Error since sqrt call is ambiguous.
// This error is not related to 'auto' keyword!
std::cout << nVariable;
// In fact no error at all - Dugoin
}
sqrt
int
void foo(double);
void foo(float);
foo(100);
template float twice<float>( float original );
template int twice( int original );
template class Array<char>;
template class String<19>;
int a;
[&]()
{
[&]()
{
a = 4; //error a is not visible here
}();
}();
Invalid reference to an outer-scope local variable in a lambda body
class LTest
{
int number;
public:
void access()
{
[&]
{
number =10; // MUST have to use this->number
};
}
};
Ajay Vijayvargiya wrote:Thanks. I love lambdas! Blush
swap()
delete[]
Simple& operator = (Simple&& sOther)
{
std::swap(Memory,sOther.Memory); // swap pointers (sOther deletes old pointer for us)
return *this;
}
swap
Simple& operator = (Simple&& sOther)
{
swap(sOther); // swap our (this) data for sOther data
return *this;
}
std::swap
class MyObject
{
...
// Strong Guarantee: If it throws an exception - objects state remains unchanged.
void assign(const MyObject& obj)
{
MyObject temp(obj); // constuctor allocates memory, etc. - may throw exception
swap(obj); // swaps data pointers, etc. - guaranteed not to throw
// temp destroys (deletes, etc.) previous data stored in this object.
}
};
assign
std::forward
class MyObject
{
void swap(MyObject& obj)
{
std::swap(myPointer, obj.myPointer);
std::swap(myValue, obj.myValue);
}
};
void assign(const MyObject& obj)
{
some_type *pTemp = new some_type[some_size]; // may throw
// Copy obj.myPointer data to pTemp - this should not throw, but it could
...
// We made it without throwing - so it is safe to change the objects state
delete[] myPointer;
myPointer = p;
}
void assign(const MyObject& obj)
{
delete[] myPointer;
// Kaboom! If anything following the above throws, then we are no longer
// in control of the objects state and have no means of recovery. Even if
// we set myPointer to null after deleting it, we are still in trouble.
...
}
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | http://www.codeproject.com/Articles/71540/Explicating-the-new-C-standard-C-x-and-its-implem?msg=4088784 | CC-MAIN-2016-36 | refinedweb | 9,249 | 54.63 |
CREATING GAME ART
FOR 3D ENGINES
BRAD STRONG
CHARLES RIVER MEDIA
Boston, Massachusetts
Copyright 2008 Career & Professional Group, a division of Thomson Learning Inc.
Published by Charles River Media, an Imprint of Thomson Learning and General Manager, Charles River Media: Stacy L. Hiquet
Associate Director of Marketing: Sarah O’Donnell
Manager of Editorial Services: Heather Talbot
Marketing Manager: Jordan Casey
Marketing Assistant: Adena Flitt
Project/Copy Editor: Karen A. Gill
Technical Reviewer: Mike Duggan
CRM Editorial Services Coordinator: Jennifer Blaney
Interior Layout Tech: Judy Littlefield
Cover Designer: Sherry Stinson
Cover Images: Brad Strong
CD-ROM Producer: Brandon Penticuff
Indexer: Joan Green
Proofreader: Sybil Fetter
Charles River Media, Inc.
25 Thomson Place
Boston, MA 02210
617-757-7900
617-757-7969 (fax)
This book is printed on acid-free paper.
Brad Strong. Creating Game Art for 3D Engines.
ISBN-10: 1-58450-548-6
ISBN-13: 978-1-58450-548-8
eISBN-10: 1-58450-604-0
Library of Congress Catalog Card Number: 2007933886
3ds Max is a registered trademark of Autodesk, Inc. Photoshop is a registered trademark of Adobe
Systems Incorporated..
Printed in Canada
08 09 10 11 12 TC 10 9 8 7 6 5 4 3 2 1
Charles River Media titles are available for site license or bulk purchase by institutions, user groups, corporations, etc. For additional information, please contact the Special Sales Department at 800-347-7707.
Requests for replacement of a defective CD-ROM must be accompanied by the original disc, your mailing address, telephone number, date of purchase, and purchase price. Please state the nature of the
problem, and send the information to Charles River Media, Inc., 25 Thomson Place, Boston, MA 02210.
CRM’s sole obligation to the purchaser is to replace the disc, based on defective materials or faulty
workmanship, but not on the operation or functionality of the product.
This book is dedicated to my wife, Åsa,
who was an encouragement and a blessing
from the time this book was just an idea until the final edit.
This page intentionally left blank
CONTENTS
ACKNOWLEDGMENTS
ABOUT THE AUTHOR
INTRODUCTION
CHAPTER 1
xvii
xix
xxi
INTRODUCTION TO 3DS MAX
1
Examining the 3ds Max Interface
Using Drop-Downs and Panels
Adjusting Grid and Snap
Setting Preferences
Creating, Viewing, and Modifying Primitives
Using Viewport Controls
Modifying Primitives
Using Viewing Tools
Using Selection Windows
Box Modeling a Chair
Converting to an Editable Poly
Moving the Vertices of the Editable Poly
Maximizing the Viewport and Using Arc Rotate
Extruding the Legs of the Chair
Extruding the Back of the Chair
Creating the Arms of the Chair
Welding Vertices
Manipulating Vertices
Working with the Material Editor
Applying a Standard Material to an Object
Applying a Custom Material to an Object
2
3
4
4
4
5
5
6
8
8
9
9
11
11
12
12
14
14
15
15
16
v
vi
Contents
CHAPTER 2
Managing Files
Saving Your Work
Merging and Importing Files
Summary
18
18
18
18
L OW P OLY M O D E L I N G
19
Creating Structurally Sound Models
Keeping a Low-Polygon Budget
Modeling a Simple Shape
Modeling a Health Patch
Welding Vertices with Weld Threshold
Creating a Pickup with Three Parts
Modeling a Power Charger
Modeling a Weapon
Creating a Template to Model By
Modeling with a Plane
Adding Symmetry to Mirror and Weld Vertices Simultaneously
Scaling Models to Fit the Torque Engine
Summary
CHAPTER 3
U N W R A P P I N G G AME A R T
Unwrapping the Oil Drum
Deciding Between Material Color and Object Color
Turning Off Smoothing
Applying a Cylindrical Map to the Model
Applying an Unwrap UVW Modifier
Applying a Normal Map
Applying a Utility Material
Correcting Flaws in the UVs
Moving UV Vertices to Improve the Mapping
Rendering Out the UV Template
Using Texporter: An Alternative for UV Rendering
20
21
22
23
25
26
27
41
42
43
47
54
55
57
58
58
58
59
61
66
68
69
71
72
73
Contents
Unwrapping the Weapon
Mirroring and Aligning Normal-Mapped UVs
Normal Mapping the Cooling Fins
Correcting the UVs at the Edges of the Weapon
Breaking and Scaling UVs
Unwrapping the Ammo Box
Unwrapping the Power Charger
Applying a Planar Map
Moving UV Vertices to Improve the Map
Using a Planar Map for More Complex Models
Unwrapping the Health Patch
Summary
CHAPTER 4
vii
75
75
78
79
80
82
84
85
85
86
90
94
T E X T U R I N G G AME A R T
95
Texturing Considerations
Using the Appropriate Equipment
Using Digital Photos for Textures
Making the Lighting Consistent
Creating Textures from Scratch
Creating in Powers of Two
Working with Photoshop
Texturing the Oil Drum
Pushing Pixels with the Liquify Tool
Using Offset to Make the Texture Wrap
Repairing Seams with the Clone Stamp Tool
Reflection Mapping in Photoshop
Defining a Reflective Oil Drum Material in 3ds Max
Assigning Smoothing Groups to the Oil Drum
Texturing the Health Patch
Creating Textured Steel
Applying a Layer Style to Create Raised Steel Panels
Using Layer Masking Instead of Erase
Animating a Pulsing Light Using an IFL Material
96
96
96
96
97
97
97
101
101
102
102
104
105
107
107
107
107
108
109
viii
Contents
Animating a Transparent Exhaust Material
Applying the Materials in 3ds Max
Texturing the Weapon
Texturing the Power Charger
Creating Concrete Using Filters
Creating Ancient Metal
Modifying Smoothing Groups for the Power Charger
Texturing the Ammo Box
Summary
CHAPTER 5
A N I M A T I N G G AME A R T
Understanding Animation Basics
Creating Keyframes
Creating a Loop
Adjusting Key Tangencies
Animating a Simple Shape
Animating the Health Patch
Adjusting Pivot Points with Affect Pivot Only
Creating Parent-Child Relationships
Animating the Weapon
Summary
CHAPTER 6
109
111
112
115
115
117
118
119
122
123
124
124
125
126
127
128
128
129
129
132
E X P O R T I N G G AME A R T
133
Exporting Game Art—Overview
Export Components
Folder Structure
Static Shapes Folders
Health Patches Folder
Weapons Folder
Bounds Boxes
Markers, or “Dummy Objects”
Hierarchy
Pickup Rotation
Animations
134
134
134
135
135
135
135
135
135
136
136
Contents
Setting Up for 3ds Max and Torque
Installing the DTS Exporter
Setting Up Torque for First Person Shooter
Deleting CS.DSO Files So That CS Files Will Be Read
Entering the Torque Editor
Saving and Renaming Missions
Checking the Torque Console Window
Previewing Game Art in Torque Show Tool Pro
Setting Up and Exporting the Simple Shape
Accessing the DTS Export Utilities
Setting Up the Hierarchy of a Simple Oil Drum
Exporting the Simple Shape
Inserting the Simple Shape into the Game
Applying Levels of Detail
Causing Collisions
Setting Up and Exporting the Health Patch
Colliding with Health Objects
Embedding Sequence Objects
Inserting the Health Patch into the Mission
Scripting Health Patch Animation
Analyzing the Characteristics of a Health Patch
Setting Up and Exporting Ammo
Setting Up and Exporting Weapons
Weapons Components
The Projectile
A Simple Weapon Hierarchy
Preparing and Exporting Weapon Animations
Scripting for Weapons and Ammo
Producing Simple Shape Animations
Creating the Simple Shape Datablock
Editing Game.cs to Call Your Script
Troubleshooting
The Shape Does Not Appear in the Game
The Texture Does Not Show Up in the Game
Weapon View in First Person Mode Is Incorrectly Offset
Summary
ix
136
136
137
137
137
138
138
139
140
140
140
141
141
143
145
145
146
146
148
148
149
150
151
152
152
152
152
153
159
159
161
162
162
162
162
163
x
Contents
CHAPTER 7
CHARACTER MODELING
Modeling a Character—Overview
Planning for Unwrapping the Model
Acknowledging Character Polygon Limitations
Setting Up Templates in Photoshop
Posing the Character
Sketching a Front and Right-Side View of the Character
Scanning and Creating Two Matching Images in Photoshop
Turning Down the Brightness and Saving the Images
Setting Up the Template Planes in 3ds Max
Setting Up Units
Creating Template Planes
Orienting the Template Planes
Snapping the Template Planes to the Origin
Applying the Templates to the Planes
Freezing the Templates
Modeling the Astronaut Character Mesh
Starting with a Box
Making the Modeling Process Easier by Adjusting Properties
Adding Symmetry to Speed the Modeling Process
Extruding the Arms and Legs
Moving and Adding Vertices as Necessary
Adding Edges with Row, Loop, and Connect
Adding Volume and Shape to the Mesh
Using Edge Loops
Planning for Movement
Modeling the Hands
Merging and Scaling the Hand to Fit the Body
Modeling the Head and Face
Finishing Off the Head with a Geosphere
Converting to Editable Mesh and Turning Edges
Adding Accessory Meshes
Creating a Helmet with Detached Polygons
Adding a Shell Modifier
Modeling a Robot with Multiple Meshes
Summary
165
166
166
166
166
166
167
168
168
169
169
169
169
170
170
171
171
171
171
172
172
172
174
175
175
176
177
178
180
181
182
183
184
184
186
187
Contents
CHAPTER 8
CHARACTER UNWRAPPING
Unwrapping a Character—Overview
Unwrapping Before You Rig the Model
Understanding the Impact of Stray Vertices
Removing Stray Vertices
Unwrapping the Hands with a Planar Map and Adding Them to the Body
Unwrapping the Body with a Normal Map
Breaking and Overlapping UVs
Breaking and Reorganizing UVs
Adjusting the UVs on the Body
Unwrapping the Character’s Face
Adjusting the UVs on the Face
Unwrapping with the Pelt Map
Creating a Character UV Template
Unwrapping the Helmet
Unwrapping a Component Mesh
Unwrapping with Multiple Material IDs
Creating a Multi/Sub-Object Material
Assigning Mesh IDs to Polygons
Accessing the Selection Sets in the Edit UVWs Dialog Box
Saving, Loading, and Combining UVs
Baking the Texture into the Mesh
Summary
CHAPTER 9
CHARACTER TEXTURING
Texturing the Astronaut
Setting Up in Photoshop
Using the Same Smoothing Group
Creating the Astronaut’s Spacesuit Texture
Using a Layer Style to Create Raised Pixels
Using a Layer Mask to Draw the Ribs
Texturing the Astronaut’s Helmet
Texturing the Astronaut’s Face
Texturing the Robot
Creating a Base Metal Texture
xi
189
190
190
190
190
191
194
195
195
196
197
197
198
200
201
201
202
202
202
203
204
205
205
207
208
208
208
208
209
211
211
211
213
213
xii
Contents
Creating Panels
Creating Rivets
Creating Scratched and Peeling Paint
Modeling Textures in 3ds Max
Troubleshooting
Misaligned Unwrap
Distorted Textures
Summary
C H A P T E R 10
CHARACTER RIGGING
Rigging—Overview
Deciding Between Bones and Biped
Setting Up the Mesh as a 3D Template
Making a Biped
Modifying the Parameters of a Biped After You’ve Created It
Understanding the Biped
Understanding the Biped Center of Mass (COM)
Rotating the Biped
Moving the Biped
Minimizing Vertex Collapse
Minimizing Collapsed Vertices by Modeling
Minimizing Collapsed Vertices by Prerotating Biped Bones
Minimizing Collapsed Vertices by Using Helper Bones
Minimizing Deformations by Using the Joint Angle Deformer
Fitting the Biped to the Character Mesh
Scaling the Pelvis and Clavicles of the Biped
Scaling and Rotating the Legs and Arms of the Biped
Aligning the Biped to the Character Mesh from the Side View
Saving the Figure File
Examining the Skinning Process
Applying a Skeleton via Skin or Physique
Ensuring You’re Ready for Skinning
Applying the Skin Modifier to the Character Mesh
Deciding Which Bones to Add to the Skin Modifier
Adjusting the Envelope
214
214
215
217
219
219
219
219
221
222
222
222
223
223
223
224
224
225
225
226
226
226
230
230
231
231
231
231
232
232
232
233
233
233
Contents
Assigning Weights to Vertices with Absolute Effect
Assigning Weights to Vertices with the Weight Tool
Moving and Rotating Bones to Check Vertex Assignments
Understanding Forward Kinematics and Inverse Kinematics
Avoiding the Chewing Gum Effect
Changing the Skeleton While Skinning
Looking for Vertex Collapse
Keyframing the Biped to Check Mesh Deformation
Creating Optional Controller Objects
Rigging a Robot
Using the Default Player Biped with a Custom Mesh
Taking Advantage of Using the Kork Player Biped with Your Character Mesh
Dealing with the Disadvantages of Using the Kork Player Biped with Your Mesh
Stripping Down the Player.max File
Applying the Skin Modifier to Your Mesh but Using the Kork Player Biped Bones
Minimizing Vertex Collapse with the Kork Player Biped
Combining Bones with Biped
Summary
C H A P T E R 11
C H A R A C T E R A NIMATION
Implementing Character Animation Concepts
Applying Counterpose
Avoiding Twins or Twinning
Using Arcs for Natural Movement
Applying Secondary Motion
Exaggerating Movement
Planning the Animation Cycles
Distinguishing Animation Methods
Choosing Between Full Body, Lower Body, and Blend Animation
Exporting All Animations Together or Separately
Choosing Between Biped and Bones Animation
Animating with Biped
Dealing with Nonintuitive Dependencies in the Biped Skeletal System
Creating and Importing BIP Files
xiii
237
238
241
241
241
242
243
243
244
244
245
246
246
246
246
247
248
249
251
252
252
252
252
252
253
253
253
253
254
254
255
255
255
xiv
Contents
Creating the Root Pose
Animating the Root Cycle
Animating a Run Cycle
Keyframing the Biped to Run
Constraining the Cam Marker
Viewing and Adjusting Trajectories
Improving the Run Cycle
Animating a Back (Backwards Run) Cycle
Animating a Side (Strafe) Cycle
Animating Jump, Fall, and Land Cycles
Animating the Death Fall
Summary
C H A P T E R 12
CHARACTER EXPORTING
Exporting Character Shape (DTS) Files
Required Markers for Character Export
Checklist for Exporting a Simple Character
Position of the Character’s Markers
The Character Hierarchy
Bounding Box
Levels of Detail
MountPoints
Additional Meshes and Collisions
Config File
Export of the DTS Shape
Exporting Character Animation (DSQ) Files
Sequence Object Setup
Footprints and Foot Sounds
Export of the DSQ Animation
Using the Torque Show Tool Pro
Scripting Characters
The Player.cs Animation Script
The Player.cs Datablock Script
Scripting for Different Character Meshes in the Game
256
257
258
258
263
264
264
265
265
266
266
266
269
270
270
270
271
271
272
273
275
275
276
277
278
279
280
280
281
282
282
284
284
Contents
Troubleshooting
Assertion Failed on Skin Object
Improperly Assigned Vertices
Character Is Invisible in the Game
Character Is Not Animating
Cannot Collapse bip01 L Finger00 Because It Is a Bone
Helper Bones and Proxy Objects Are Distorted in the Animation Files
Weapon Is Invisible or Intermittently Visible in First Person Mode
Weapon Is Pointed the Wrong Way or Is Otherwise Misaligned
Footprints Are Not Visible in the Game
Character Stutters Forward and Backward During Run
Character Does Not Fall Down in Death Cycle
Assertion Error During Vertex Merge
Character Does Not Complete Animation
Summary
APPENDIX A
INDEX
O N T H E C OMPANION CD-ROM
xv
287
287
287
287
288
288
288
288
289
289
289
289
290
290
290
293
295
This page intentionally left blank
ACKNOWLEDGMENTS
I
wish to thank the editing team at Charles River Media (Emi Smith,
Karen Gill, Jennifer Blaney, and Jenifer Niles) for their help in getting
this book publish-ready. Thanks, too, to my technical editor, Mike
Duggan. Also deserving recognition are the guys who make the Torque
Game Engine available, GarageGames, who directly or indirectly made
this book and the accompanying CD possible. In particular, I want to
thank Joe Maruschak at GarageGames for the great articles and forum
answers that have helped me and many others get a handle on this engine. I also want to thank Autodesk for a great product (3ds Max) and for
the experience I gathered while there; thank you David Koel for making
me a better AE. Cuneyt Ozdas deserves recognition for writing Texporter,
the handy UV renderer. Thanks also to Matt Summers for writing the
Dark Industries exporter, and to Sam Bacsa for writing Codeweaver,
which helped me to work through some of the scripting challenges. Finally, thanks to Steve Smith at the Art Institute of Colorado for freely
sharing his knowledge while I taught there.
xvii
This page intentionally left blank
ABOUT THE AUTHOR
B
rad Strong, a former Autodesk application engineer, has more
than 18 years of experience using and teaching digital design software in the Rocky Mountain region. He holds a master’s in
computer information systems from Denver University/University College, where his thesis and capstone project was on game-based learning;
a master’s in management from the University of Phoenix, where his
thesis was on effective CAD utilization; and a bachelor’s in art from the
University of Colorado at Denver.
Brad has developed and taught a range of courses on programming,
art, and game development at art and technical colleges in the Colorado
area. Most recently, he taught 3D modeling, materials and lighting, 3D
animation, and online game development for the Art Institute of Colorado. Since 2002, he has been developing 3D learning games. He is the
president of 3dCognition, a game-based learning development studio,
based in Karlskoga, Sweden. The 3dCognition Web site can be found at.
When he’s not working, Brad enjoys theology, philosophy, bass guitar,
and composing fusion-lounge-gospel music with his wife.
xix
This page intentionally left blank
INTRODUCTION
T
his book focuses on how to create game art properly for a game engine, as well as how to export that art to the engine and make script
changes so that the art becomes a viable part of the game.
Although many of the processes and techniques will apply to specific
modeling, texturing, animation, and game software solutions, this book
will use 3ds Max release 8 to generate models and animations, and the
Torque Game Engine for the game-side examples. These two solutions are
at the forefront of their class; 3ds Max has more than 200,000 registered
users and is used by more top-selling game developers for modeling and
animation than any other solution. The Torque Game Engine enjoys a
solid reputation as the most powerful and affordable solution for the small
game development studio, in addition to being a viable choice for students
and hobbyists.
Much of this book comes from my own tribulations as an instructor
for modeling, texturing, animation, and game development courses. A
good instructor learns over a period of semesters and years how to get the
information across as efficiently as possible to minimize everyone’s (his
own included!) frustration.
An equal part of this book stems from my own frustrations as a game
developer for the past five years. It was from my own notes on what was
working and what wasn’t, combined with my own interpretation of the
resources at the Torque Web site (), that
many of these pages were birthed.
Because this book covers so many aspects of game art (modeling, unwrapping, texturing, rigging, animation, exporting, scripting), it will be
impossible to drill too deeply into any one area. However, the goal of this
book is to provide step-by-step exercises and video tutorials that a serious
student can use to create and successfully import game art, from simple
shapes to full-blown characters. There should be more than enough here
for the accomplished or aspiring artist/animator to gain an understanding
of how to create game art and how to make it come alive in a 3D engine.
xxi
xxii
Creating Game Art for 3D Engines
Multimedia is a powerful medium because it engages so many of our
senses. 3D games are the highest and most compelling form of multimedia, because they add competition, instant feedback, immersion, and adventure. We are motivated, challenged, and empowered to do things we
could not do otherwise. The future of game development is promising,
and I believe that the future for game-based learning and interactive simulations is particularly bright. Math, for example, is a dry subject, but if
solving a few equations will help me fly to a far star, I might be interested.
If you have questions or comments on this book, feel free to e-mail
them to brad@3dCognition.com. As feedback is generated from this book,
any noteworthy corrections or additions will be available at.
3dCognition.com.
I hope that this book is instrumental in making your game ideas real.
CHAPTER
1
INTRODUCTION TO 3DS MAX
In This Chapter
•
•
•
•
•
Examining the 3ds Max Interface
Creating, Viewing, and Modifying Primitives
Box Modeling a Chair
Working with the Material Editor
Managing Files
1
2
Creating Game Art for 3D Engines
T
his chapter introduces some of the foundational features of 3ds Max for the
benefit of those who have limited or no experience. Please keep in mind that
for complete coverage of 3ds Max, you should work through a book that is
focused solely on that product. Even then, the vast majority of 3ds Max users do not
use or understand the entire functionality of the product. Because the goal of this
book is to generate game assets and make them functional in the game, we will only
discuss those foundational aspects of 3ds Max that directly pertain to our goal.
We will overview the 3ds Max interface, primitives, viewing tools and options,
transforms, properties, Editable Polys, and basic materials. Each version of 3ds Max
adds a vast amount of functionality; however, on the whole, the look and feel of 3ds
Max has not changed for several releases. This tutorial and the files on the CD-ROM
are being made with Release 8. The features used are primarily found in Release 7
and earlier; Release 8 features will be noted when used. If you are using a version of
3ds Max as early as 4 or 5, you should still be able to follow and apply the majority
of what will be discussed in this book.
EXAMINING THE 3DS MAX INTERFACE
The features of 3ds Max continue to improve with each release, but the general
interface has stayed consistent. We will begin with a brief overview of the interface,
and then we’ll jump right into creating some 3D primitives. The intent here is to stay
laser-focused on those foundational tools and techniques that will help us to build
pickups, weapons, and characters in the following chapters. This walk-through will
be done project-style, so we will discuss the different tools as we come to them in
each project. Our first project will be to model a simple chair.
In Figure 1.1, at the top of the screen, you have drop-down menus with a Standard toolbar immediately below. If your screen resolution is 1024 × 768, the entire
toolbar will not fit on the screen; therefore, you will need to drag it to the right and
left as you work so that you can see the entire set of tools. To the right are the panels. There are panels for Create, Modify, Hierarchy, Motion, Display, and Utilities.
This is typically one of the most heavily used areas of the interface. In this image, the
Create panel is focused on the Geometry tools. This is where you find primitives,
such as boxes, cylinders, and spheres.
At the bottom of the workspace is the animation area, where you can set and
modify keyframes.
At the lower right are the viewing tools. These tools will change based on whether
you are in a perspective view, an orthographic view (such as front, right, back, or top),
or if you are looking through a camera.
The area in the middle is the workspace. By default, you have four viewports. You
can activate any viewport by right-clicking in it. At any time, you can toggle between
four viewports or one viewport by clicking the Maximize Viewport toggle, which
resides in the lower right-hand corner of the screen. If you click the Maximize Viewport toggle while a particular viewport is active, that viewport becomes maximized.
Clicking the toggle again returns you to a four-viewport interface. Click this button a
Chapter 1
Introduction to 3ds Max
3
FIGURE 1.1 The anatomy of 3ds Max.
few times to see what happens. In general, it is best to have as big a viewport as possible when working with a model, but at different times during the development
process, you will need to switch to multiple viewports to see how the model is shaping
up from different points of view.
Depending on what you are doing and where in the interface you click, a rightclick will generate different menus. A right-click on the viewport area will give you
access to the Move, Rotate, and Scale tools, as well as the option to hide selected
objects or hide unselected objects, for example. You also have hotkeys such as F for
front view, L for left view, P for perspective view, U for user view, Alt+W to toggle
between one big viewport and multiple viewports, and G to toggle Grid mode on
and off.
Using Drop-Downs and Panels
3ds Max is set up primarily with two means of creating and editing: drop-down
menus and panels, located to the right of the workspace. For the majority of our
work, you will be using the Create panel and the Modify panel. If you cannot find
the tool you are looking for, try these panels first.
4
Creating Game Art for 3D Engines
Adjusting Grid and Snap
Grid and Snap are related. You can set the size of the grid on the screen by rightclicking the Snaps toggle and accessing the Grid tab. You can toggle the grid off and
on by using the G hotkey. You can set the default Snaps by right-clicking the Snaps
toggle and accessing the Snaps tab. Check the box next to the type of snap you want
enabled, and close the dialog box by clicking the X in the upper-right corner. Then,
as long as the Snaps toggle is enabled, the mouse cursor will snap accordingly. The
Snaps toggle is a tool that should be deactivated most of the time and used only
when you have a specific need for it. Most of the time, having this tool turned on
will get in your way. Likewise, having the Grid turned on will often just add confusion to your viewport.
Setting Preferences
A few adjustments to the Preferences in 3ds Max can make your work more productive. From the Customize drop-down menu, click Preferences; then select the General tab. Setting the Scene Undo level to 100 enables you to click the Undo button
up to 100 times if you’ve made a wrong move. In the Viewports tab, under Mouse
Control, make sure that Middle Button is set to Pan/Zoom and that Zoom About
Mouse Point is checked for both Orthographic and Perspective. This setting allows
you to spin the mouse wheel and zoom in or out on a viewport while causing the
zoom to target wherever your mouse cursor is.
CREATING, VIEWING, AND MODIFYING PRIMITIVES
To become familiar with 3ds Max, start by creating some primitives from the Create,
Standard Primitives panel. Create the geometry by clicking on the shape and then
clicking and dragging in your perspective viewport. Depending on the shape, when
you release the mouse the first time, you may have to define another desired dimension. (For example, after you define the base of the Box primitive, you define its
height.) You can name a primitive and adjust its object color at the time of creation
by accessing the Name and Color rollout on the Create, Standard Primitives panel.
In Figure 1.2, some of the standard primitives have been created on the screen. Create these on your own screen to get a feel for how primitives are created. The green
box has just been created, so you can still change its parameters in the menu at the
right. The most important things to consider for now are the size and number of
segments in the primitive. Create some primitives of your own, and try changing
length, width, and height values. Also, try changing the number of segments. You
will see the number of segments change in the orthogonal viewports (top, front,
left), but the number of segments for each primitive will not show up in the perspective viewport until you make an adjustment. If you want to clear the screen without
saving changes, click File, Reset.
Chapter 1
Introduction to 3ds Max
5
FIGURE 1.2 The Create panel gives you access to standard primitives and their parameters.
Now that you have seen the standard primitives, take some time to look at the
extended primitives as well. Being aware of the basic shapes that can be achieved
with a few button clicks can save you modeling time later.
Using Viewport Controls
The ability to see segments (or edges) on your models will become very important as
you begin to model. If you want to turn on Edged Faces for any particular viewport,
you need to right-click on the viewport name (the name for each viewport is in the
upper left-hand of the viewport) and make sure that Edged Faces is checked. Likewise,
you may want the contents of a viewport to be Smooth+Highlights or Wireframe. The
Views flyout on this right-click menu allows you to change the kind of view you are
looking at; top, front, right, left, user, and perspective are all useful options. If you use
the Arc Rotate tool in any of your orthogonal viewports, the viewports will become
user views. They will lose their straight-on orthogonal quality; any view that is skewed
in any way is either a perspective view or a user view.
Modifying Primitives
As long as your Select tool is active, you can select different primitives by clicking on
them. The Select tool button looks like a white arrow and resides on the Standard
toolbar. When a primitive is selected, the edges of the primitive will turn white, and
there will be a white selection box around it. You can delete selected objects by
pressing the Delete key. Even after you’ve created the primitive, you can change its
size and number of segments by selecting the object and clicking the Modify panel.
6
Creating Game Art for 3D Engines
If we want to move this box, we can click the Select and Move button on the
Standard toolbar. Alternatively, you can select the object first and then activate the
Move tool, or you can perform a select and move simultaneously. The Move tool has
a gizmo (a directional indicator) that is red, green, and blue and is made up of three
axes and three planes. The red axis corresponds to the X direction, the green axis to
Y, and the blue axis to Z. The axes and planes will highlight (turn yellow) as you
pass the mouse over them. Dragging on an axis will move the box only in that axis,
and dragging on a yellow plane of the Move gizmo will move the box only in one of
the three planes: XY, YZ, or XZ. When you release the mouse button, you’ll notice
that the object moved. The Rotate and Scale tools have similar gizmos, where selected objects can be rotated or scaled in an axis or a plane.
In Figure 1.3, a box that was created is being modified via the Modify panel, the
number of segments has been changed to 2 in each direction, and Edged Faces have
been turned on for the perspective viewport. Note also that in this figure, the Move
tool has been turned on in the Standard toolbar, and the Move gizmo is near the box.
FIGURE 1.3 Setting viewports to show Edged Faces, adjusting segments, and the Move gizmo.
Using Viewing Tools
The Zoom, Pan, Arc Rotate, and Maximize Viewport buttons reside in the lowerright corner of the screen. Practice zooming in and out in different viewports by
right-clicking on the viewport to activate it and then spinning the mouse wheel to
Chapter 1
Introduction to 3ds Max
7
zoom. Pressing and holding the mouse wheel causes a pan. In the lower-right corner
of the screen, the Maximize Viewport button is a toggle that maximizes whatever
viewport is current so that it is a single large viewport; clicking this button again returns to a multiviewport state.
The Arc Rotate tool allows you to do a left-click-drag to change your view of the
model. Figure 1.4 displays this process in action; you can see the Arc Rotate tool
turned on in the lower-right corner of the screen. The yellow circle that is displayed
on the screen during Arc Rotate is called a trackball. By clicking inside the trackball,
you can intuitively change the viewpoint of your object. Arc Rotate flyouts are gray
for general purposes, white to focus on selected objects, and yellow to focus on selected sub-objects. In this figure, the Arc Rotate Selected button is active, meaning
that as you click and drag, the selected object will be the center of the rotation.
FIGURE 1.4 Using the Arc Rotate tool to change the viewing angle.
Do not mix up the Arc Rotate tool with the Rotate tool. You use the Arc Rotate
tool for rotating the view of the model, whereas you use the Rotate tool for rotating
the model. Do not use the Rotate tool, located next to the Move tool on the Standard toolbar, to change your view of the object. Doing so will make your model
more difficult to edit, because it will be in an inconvenient orientation for editing.
8
Creating Game Art for 3D Engines
Using Selection Windows
The Selection button on the Standard toolbar in 3ds Max toggles between activating
a Window Selection mode and activating a Crossing Window selection mode. Every
time you left-click-drag on the screen in 3ds Max, you define one corner of a selection window. When you release the mouse button, you define the opposite corner of
the selection window. All objects within that window will be selected. This describes
the behavior of a standard selection window. A Crossing selection window selects not
only the objects within the window but also the objects that are even partially in the
window; that is, it also selects the objects that the selection window crosses.
BOX MODELING A CHAIR
ON THE CD
Walking through the process of modeling a chair will be good practice for the models we will build later in this book. You can find the video ModelingAChair.wmv in the
Videos folder on the companion CD-ROM. Start by creating a simple chair from a
box primitive. Do this by going to the Create panel, activating the Geometry menu,
verifying that you have standard primitives selected from the drop-down list, and
selecting Box from the list of primitives. To create the box, use a click-drag-release
action with the mouse. Perform this drag action in the perspective viewport. The
first click-drag creates the base of the box; when you release and move the mouse
again, you are defining the height of the box. When you click the mouse button, the
box is complete. If this is your first time creating primitives with 3ds Max, spend a
few minutes creating primitives such as spheres and cylinders. When you want to
delete a primitive, select it with left mouse button and press the Delete key. Test
some of the viewing tools that are built into your mouse; spin the mouse wheel to
zoom in and zoom out, and do a click-drag on the middle mouse button/mouse
wheel to pan the screen around.
To modify the box, select it first. Figure 1.5 depicts four important things. First,
the Select button is active in the Standard toolbar. If you find that you cannot select
an object, first check to see that the Select button is active. Second, the box we just
created is selected. This is indicated by a selection box with white edges that highlights the box. Third, the Modify panel is selected. If you have an object selected and
you select the Modify panel, you will generally find that you have access to the
parameters or sub-objects of that selection. In this case, because our object is a box,
we have access to the Length, Width, and Height, as well as the number of segments
for each of these values. Adjust the dimensional values of your box to mimic the
image seen in Figure 1.5 so that your box more clearly resembles the seat of a chair.
Notice that our current viewport is perspective. (The name is in the upper-left
corner.) To display edges in this viewport, right-click on the name of the viewport
(Perspective) and click Edges. Now we are ready to add edges. This is the fourth important thing to notice from the figure. We want three segments for length and
three for width so that we have enough edges to create legs and a back for the chair.
Chapter 1
Introduction to 3ds Max
9
FIGURE 1.5 Edged faces are turned on for the viewport, and edges are added for the box.
If your Move gizmo (or the other transform gizmos, for that matter) is not visible, there are
two possible causes. The first is that you accidentally pressed the X button on your keyboard,
which turns off the transform gizmo. Press X again and see if this corrects the problem. The
second possible cause is that your preferences may have somehow been set to turn the transform gizmos off. If this is the case, try going to the Customize drop-down menu, select Preferences, select the Gizmos tab, and make sure the check box for Gizmos is selected.
Converting to an Editable Poly
Our next step in going from a box to a chair is to convert the box into an Editable
Poly. When we do this, we lose the ability to parametrically adjust the length, width,
and height, but we gain the ability to modify sub-objects such as vertices, edges, and
polygons. To convert the box to an Editable Poly, right-click on the box and select
Convert to Editable Poly. When you do this, you will see the Modify panel change;
the Editable Poly modify menu allows the user to select a sub-object type, each of
which has its own specific modification options. Figure 1.6 displays what the Convert to Editable Poly menu looks like, as well as the Editable Poly menu to the right.
Moving the Vertices of the Editable Poly
The Editable Poly has five different sub-object types: Vertex, Edge, Border, Polygon,
and Element. Our objective at the moment is to move the vertices of the Editable
10
Creating Game Art for 3D Engines
FIGURE 1.6 Where to find Convert to Editable Poly. This box has already
been converted.
Poly so that we can extrude the legs and the back of the chair. Click on the Vertex
sub-object type to activate it. You will know it is active when you see the word
Vertex highlighted in yellow.
Working in sub-object mode can be tricky the first few times you do it. You will
not be able to select any other objects until you properly exit sub-object mode. This
involves clicking on the yellow highlighted bar. The disappearance of the yellow
highlight means you have exited sub-object mode, and you can treat this model as a
regular model or select another model. When you are in sub-object mode, you are
in a sense “locked” inside that model.
Activate the top viewport by right-clicking in it. We will use the top viewport
because it is easier to select a complete row of vertices when all the geometry is flat
to the screen. We can use what can be called an “implied window” technique to
select a row of vertices. This involves doing a click-drag-release from one corner of
the selection area to the other. When you release the mouse button, you should see
a row of red vertices, indicating that all of them have been selected. After you’ve selected these vertices, you can use the Move tool to move them to the left. Figure 1.7
shows the four stages of this process. The implied window is used to select the vertices; they will then turn red when selected. The Move tool is activated and used to
move the entire row of selected vertices closer to the edge of the Editable Mesh.
Continue this process on the other vertices so that all of the vertices are near the
edge of the object. This creates small polygons in each corner, which we can use to
extrude the legs.
Chapter 1
Introduction to 3ds Max
11
FIGURE 1.7 Four stages of moving vertices in Vertex sub-object mode, from within the top viewport.
Maximizing the Viewport and Using Arc Rotate
Up until now, we have had all four standard viewports displayed. When we maximize a viewport, whatever viewport is currently active will enlarge to fill the screen.
Right-click on the perspective viewport to activate it, and then maximize it by clicking on the Maximize Viewport button in the lower-right corner of the screen. The
hotkey for this is Alt+W. Pressing the button or entering the hotkey again will return you to the four default viewports. After you have the Perspective viewport
maximized, use the Arc Rotate tool to move your view of the model so that you are
looking at it from the bottom, where you will extrude the legs. Rotate the view of
the object until your screen looks like Figure 1.8.
Extruding the Legs of the Chair
To generate four legs of the chair, first click on Polygon sub-object mode. (This mode
is the one that looks like a red square under the Selection sub-menu.) Just as Vertex
sub-object mode allowed us to modify vertices of the model, Polygon sub-object
mode will allow us to modify polygons. When we are in the right mode, we can leftclick to select the four corner faces for the legs; to select all four polygons at once,
hold down the Ctrl key. The polygons should turn red when selected. If they do not,
make sure your viewport is set to Smooth+Highlights; if the polygons are still not
shaded, try pressing F2 to toggle Highlight Selected Faces. Click on the Extrude Settings button to the right of the Extrude button, as shown in Figure 1.8, and change
the Extrusion height until you like the result. When you are satisfied, click OK.
12
Creating Game Art for 3D Engines
FIGURE 1.8 Selecting four polygons and using Extrude Settings to adjust their length.
Extruding the Back of the Chair
Rotate the view of the chair again using the Arc Rotate tool so that you are once
again looking down upon it. Select the three polygons at the back of the chair and
extrude them to form the back of the chair. You may want to left-click once on the
gray background of the screen to make sure that the ends of the chair legs are not
still selected; otherwise, they will be extruded again, along with the chair back.
Creating the Arms of the Chair
The Editable Poly modification menu is rather extensive, so it is sometimes useful to
pull the menu out so that more of it can be seen at one time. To do this, click on the
edge of the menu and drag toward the left until another panel width is visible, as
shown in Figure 1.9. Make sure you are back in Vertex sub-object mode, and from
the Edit Geometry rollout, click the Slice Plane button. This will generate a yellow
preview plane, which you can move with your Move transform tool. Move this slice
plane into a position as shown, and click the Slice button. You have more vertices
and polygons available now.
Before you actually rotate the slice plane, activate the Angle Snap toggle so that
your rotation can be more precise. When you are ready to rotate the slice plane, click
the Rotate button. Click-drag on the Rotate gizmo, where you see a green
circle corresponding to the Y axis, until the slice plane has rotated 90 degrees. When
the slice plane has the right orientation, use the Move tool to bring it closer to the front
of the chair and click Slice to complete your final slice for this model. Figure 1.10
Chapter 1
Introduction to 3ds Max
13
FIGURE 1.9 Cutting new edges with the Slice Plane tool.
shows the chair with appropriate slices made. In this figure, we are in Polygon subobject mode and have selected the four polygons we will build the chair arms from.
Each of these polygons is extruded a short distance to give us something to work with.
FIGURE 1.10 Extruding the chair arms.
If we were designing a chair for a movie or almost any other purpose than as a
real-time game asset, we would likely add more details and additional edges to refine
the appearance and prepare the model for adding a MeshSmooth modifier. However, this process would quickly bring the chair’s polygon face count to over 1,000
faces. Because we are rendering all faces real-time, we need to keep our models simple and make up for that simplicity with believable textures.
14
Creating Game Art for 3D Engines
Welding Vertices
There are two basic kinds of welds: general and target. To use either one, you have to be
working with an Editable Poly (or an Editable Mesh), and you must be in Vertex subobject mode. Also, for both types of welds, you need to be sure that there are no polygons between the two vertices. If there are polygons or faces between the two vertices
you want to weld, you have to delete these obstructions first by selecting them in Polygon sub-object mode and pressing Delete. In Figure 1.11, we have deleted the polygons
at the end of each chair arm extrusion so that we can weld the arms together.
The general weld works by selecting or windowing a group of vertices and then
clicking the Weld button. If the threshold is set to 0.25, any of the selected vertices
that are within that distance of each other will be welded together. The target weld
is accomplished by dragging from one vertex to the vertex where you want it to be
welded. It is a left-click-drag-release type of action.
FIGURE 1.11
Welding vertices with target weld.
Manipulating Vertices
Just as we moved vertices in the segmented box at the start of this chair design, we
can move vertices from an orthographic view (a straight-on view) to fix the chair
arm vertices so that they are straighter. Depending on how you created the chair,
you should be able to see a clear view of the side of the chair from the front or the
left viewport. Viewed from the side, there are really only two sets of vertices that
might need to be moved so that the chair arm is straight. By using an implied window, you can select these vertices and move them where you think they should be.
Chapter 1
Introduction to 3ds Max
15
WORKING WITH THE MATERIAL EDITOR
The Material Editor is an interface that is dedicated solely to creating, applying, and
modifying materials. Although it cannot be used like Photoshop to manipulate
pixels and create bitmaps, it does allow us to select and use those bitmaps in a variety of ways.
Applying a Standard Material to an Object
It is a good idea to select the object that you want to apply the material to first and
then launch the Material Editor. You can launch the Material Editor from the Standard toolbar or by pressing the hotkey M. Click the Get Material button to launch
the Material Browser (see Figure 1.12). Set the Browse From group in the Material
Browser to Material Library so that you can see the standard materials. Doubleclicking on a material will place it in the sample slot of the Material Editor. Then you
can apply the material to the object by clicking the Assign Material To Selection
button. The material will not be visible on the model until you click the Show Map
in Viewport button. Also, you may need to make sure your viewport is set to
Smooth+Highlights so that you can see the shaded image in the viewport.
FIGURE 1.12 Applying a standard material to the model.
Look at the material and the way it lies on the model. It looks fine on some faces
but is streaking on others. It is always a good idea to add a UVW Map modifier to
any modeled object so that you have more control over how the material lies on the
model. To apply a UVW Map modifier to the chair, make sure the chair is selected
and that you are not in sub-object mode. Then click the Modifiers drop-down list
described in Figure 1.13 and select UVW Map modifier from the end of the list.
16
Creating Game Art for 3D Engines
Select Box for the map type, and note that the appearance, while still not perfect, is
now at least more consistent than before. Note the modifier stack on the right. By
selecting an object and clicking on the Modify panel, we can quickly understand
what kind of object this is (an Editable Poly in this case) and what modifiers have
been added to it. (The UVW Map modifier has been added.) Note that you can click
the plus sign next to any modifier in the modifier stack to open that same modifier
to access deeper levels.
FIGURE 1.13 Applying a UVW Map modifier to the model to control the
way the material looks.
Applying a Custom Material to an Object
Standard materials are okay for tutorials or traditional texturing work, but for realtime rendering, we will almost always need to create custom textures for our assets.
Create the material by locating a copyright-free image on the Internet, creating it in
Photoshop, scanning an image, using a digital photo, or using some combination of
these methods. Launch the Material Editor and select an empty sample tile. Then
give your new material a name. Scroll down to the Maps section and check the box
that says Diffuse Color. Click the button to the right that normally says None. After
that, double-click on Bitmap and find the material you made (see Figure 1.14).
Using maps other than diffuse is covered in Chapter 4, “Texturing Game Art.”
After you have selected the bitmap, you can close the Material Browser. Your
Material Editor interface will now reflect the parameters of the bitmap you just
added. Here you have access to the Parameters rollout for the bitmap; this is the area
where you can turn on the Alpha channel for reflective or transparent materials, for
Chapter 1
Introduction to 3ds Max
17
FIGURE 1.14 Applying a custom material to the model.
instance. To get back to the general Material Editor interface, click the Go To Parent
button (see Figure 1.15). If you ever want access to bitmap parameters again, simply
click on the bitmap name in the Maps rollout.
FIGURE 1.15 The newly applied material and the Go to Parent button.
18
Creating Game Art for 3D Engines
MANAGING FILES
A big part of art asset development is managing the data. Consider implementing
file-naming conventions, system backups, offsite storage, and a means of tracking
which assets were used for different iterations of a game. At a minimum, being able
to save your work and being able to merge and import files are important skills.
Saving Your Work
You can save your work by selecting File, Save; use File, Save As to give the file a
new name; or use File, Save Copy As to make a copy of the file. The most important
thing is to save your work regularly in case you encounter a crash or lose your work.
The File, Save As dialog has a plus sign (+) to let you automatically save and increment your saved copy to Filename01.max, Filename02.max, and so on. Incremental
file saves are an excellent idea because they not only back up your work, but they
also allow you to backtrack to specific signposts in your design process if you inadvertently destroy your work.
3ds Max also has an Autoback feature that automatically backs up your files.
The setup for Autoback is in Customize, Preferences, Files, in the Auto Backup
group. This feature is especially helpful if 3ds Max crashes; 3ds Max will attempt to
save a backup copy of your work to the Autoback folder where 3ds Max is installed.
Merging and Importing Files
What if we want to bring our chair into a room that has other furniture? First, it
would be a good idea to name this model chair rather than its default name of Box01.
Then we can save this file (let’s call the name of the file chair as well) and open our
room file. Once room is open, select File, Merge from the drop-down menus and find
the chair file. Upon merging the files, you will have the choice of what objects within
that file you want to merge. This is where names are helpful. You can also export and
import 3ds files; 3ds files are a file format that saves only the mesh information of
your models.
SUMMARY
In this chapter, we started by looking at the general interface of 3ds Max and its
viewing tools. We then looked at the model creation process, working from a primitive box to a more refined Editable Poly. We closed this chapter with examples of
how to add UV maps and materials to an object. In the next chapter, we will build
upon these tools and techniques to model the noncharacter components of our
game.
CHAPTER
2
LOW POLY MODELING
In This Chapter
•
•
•
•
•
•
Creating Structurally Sound Models
Keeping a Low Polygon Budget
Modeling a Simple Shape
Modeling a Health Patch
Modeling a Power Charger
Modeling a Weapon
19
20
Creating Game Art for 3D Engines
T
he goal for this chapter is to cover the basics of low poly modeling in 3ds Max.
This includes learning how to repair a model that has problems and how to
minimize the number of faces that a model has. Models for a simple shape, a
health patch, a power charger, and a weapon will be created. Each of these models
will ultimately be unwrapped, textured, and exported to the Torque Game Engine.
More advanced low poly techniques will be presented in Chapter 7, “Character
Modeling.”
When it comes to low poly modeling, there are two primary modeling features:
Editable Mesh, and Editable Poly. Editable Poly is in most cases the best tool because
it has been enhanced so much over the years, and it allows you to handle more
geometry more effectively because you are dealing with polygons instead of triangles. You can convert a model from Editable Poly to Editable Mesh or vice versa, as
often as you wish. In fact, ultimately it will be necessary to convert all geometry you
are going to import to the Torque engine to Editable Mesh. Editable mesh geometry
is made up of triangle faces, which are necessary for the Torque engine. For this reason, it is not necessary to model exclusively in quads. Because you are dealing with
a real-time rendering engine that breaks down all mesh geometry into triangles anyway, triangles are acceptable in the model wherever you want to place them.
CREATING STRUCTURALLY SOUND MODELS
As you work, it is important to build upon structurally sound models. In this section,
we will look at some of the components of a model and how to make sure they work
together properly.
Figure 2.1, on the left side, shows two related issues: unwelded vertices and
overlapping faces. Wherever there are overlapping faces, there are overlapping
edges. A vertex was not properly welded to its neighbor, creating chaos in the
model. This is also apparent on the right side of the box, where a weld is needed to
repair the model. Simply making sure every vertex is welded and that there are no
stray vertices will help to ensure that your models have integrity. In addition, this
model demonstrates what a T-junction is. Whenever you have an edge that stops
abruptly, without flowing into another edge, a T-junction is formed that creates ambiguity in the model. There should be no dead-ends in the model; all edges should
flow into another edge. To repair a T-junction, you either need to remove the edge
that is causing the T-junction, or you need to add one or more edges to connect it to
an existing vertex. Stray vertices are also a problem. If a vertex does not tie at least
three edges together, it is probably a stray vertex. Stray vertices can be easily removed when in Vertex sub-object mode by selecting the vertex and pressing the
Backspace key, or selecting Remove from the Edit Vertices rollout. In addition to
these issues, keep on the lookout for sliver faces. These are faces that are unusually
long and thin and usually point to the need either to cut additional edges or to turn
an interior edge. If given the choice between one long, thin face or two more normally proportioned faces, go with the more normally proportioned faces.
Chapter 2
Low Poly Modeling
21
FIGURE 2.1 Things to avoid: overlapping faces, unwelded corners, stray
vertices, and T-junctions.
The problems with the model in Figure 2.1 are exaggerated for clarity. Usually
you will have to zoom in to see these kinds of issues; it may also be necessary to
enter sub-object mode and begin to poke and prod with the Move tool until the
issue becomes apparent. For example, if you are not sure if the vertices are welded
in the corner of a model, you can enter Vertex sub-object mode and try selecting
and moving the vertex to see what happens.
KEEPING A LOW-POLYGON BUDGET
It stands to reason that the fewer faces you have, the better your game performance,
particularly for machines that are on the slow side. The manufacturers of the Torque
engine recommend a maximum of 500 faces for weapons and a maximum of 2,250
faces for characters. All other objects in the scene should be kept to a minimum face
count. Face counts should be made based on triangle counts, not polygon counts.
An Editable Poly is based on polygons, which are actually two triangles, whereas an
Editable Mesh is based on triangles, so it pays to know which type of model you are
working with. To arrive at the correct number, count the faces in an Editable Mesh,
or double the face count in an Editable Poly. One way to count faces is to use the 7
hotkey, which displays face counts of any selected model. A good tool for counting
faces is the Polygon Counter; to launch it, go to the Utilities panel, click on More,
and select Polygon Counter. This counter lets you choose whether you want to
count triangles or polygons for selected objects as well as the entire scene. It also lets
you set size limits. Finally, you can find an overall summary of the faces used in the
scene by going to File, Summary Info.
22
Creating Game Art for 3D Engines
Thinking low poly is really an acquired state of mind. You are on a serious
budget, where exceeding the budget can mean you must remove other meshes from
the game or pay a performance penalty. Making your assets low poly is much more
effectively done early on, rather than having to remove polygons later. The Multires
and Optimize modifiers can help you simplify a model quickly, but the resulting
mesh is never as clean and ordered as you can achieve by hand, by doing it the right
way initially.
Typically, a low poly model starts as a box primitive. This depends on the geometry of the shape you are trying to achieve, however, and it is a good idea to be
familiar with all the primitives (box, sphere, cone, plane, and so on) and extended
primitives (capsule, oil tank, and so on) available from the Create panel so that you
can save modeling time. In Chapter 1, “Introduction to 3ds Max,” a box primitive
was used to start the modeling process. This was because the box has characteristics
that make it suitable for modeling a chair. For an oil drum, a different sort of primitive must be used.
MODELING A SIMPLE SHAPE
The first model to create will represent an oil drum. A cylinder primitive will work
well because it already has the general shape necessary. Later you can use a texture
to make this look like an oil drum, so you don’t need a lot of detail. The model itself
can be a simple cylinder with 12 sides. In Figure 2.2, note that the drum at the left is
wasting a huge number of faces, because it has 5 height segments that do not appreciably affect the shape of the drum. The cylinder in the middle is wasting faces also,
because it has more than enough side segments to suggest roundness. For the purposes of a game, 12 sides and 1 segment is more than adequate.
FIGURE 2.2
Different settings on a cylinder primitive.
Chapter 2
ON THE CD
Low Poly Modeling
23
Another thing to note in Figure 2.2 is the size of the cylinder. The units for this
session of Max have been set to meters as the default unit type. Because the Torque
Game Engine considers every unit a meter, it makes sense to design in meters. You
can set units in 3ds Max from the Customize drop-down menu by clicking on Units
Setup and then selecting Metric. Because the average character in Torque is about
two meters high, the oil drum should be only a meter or so high. Create a cylinder
similar to the one shown on the right in Figure 2.2 that is a little over one meter tall,
and make sure your viewport is set to Shaded with Edges so that you can see what
you are doing. Save the model as OilDrum.max. A completed version of this file
is available on the companion CD-ROM. It is named OilDrumTextured.max and is
located in Files\OilDrum.
MODELING A HEALTH PATCH
Our next model will be made of three meshes and will be used as a health pickup in
the game.
Figure 2.3 shows the first four steps to creating this model. Start with a cone that
has 6 sides and 2 height segments. Make the cone a little less than 1 meter high.
Then convert it to an Editable Poly by right-clicking on it and selecting Convert to
Editable Poly. In the Editable Poly menu, go into Polygon sub-object mode, and
select all the polygons on the object. In the Polygon Properties group, under
Smoothing Groups, click the Clear All button. This should turn off any inherent
smoothing and give you some nice, faceted faces as are apparent in stage B. At stage
C, the model is in Vertex sub-object mode, and all the vertices along the waistline of
FIGURE 2.3 Four stages in the development of a simple pickup model.
24
Creating Game Art for 3D Engines
the object have been selected with a selection window and scaled down slightly. You
may also want to move the vertices up or down a bit to get the look you want. Stage
D involves getting into Polygon sub-object mode again, using Arc Rotate to look
underneath the model, clicking on the bottom polygon, and pressing the Delete key
on your keyboard to delete it.
When the bottom is open, we can go to the front view and, using Edge subobject mode, select all six edges at the bottom of the model, hold down the Shift key
on the keyboard, and simultaneously move the edges down. This technique copies
the edges, in effect forming new polygons. It is important to note that copying these
edges only works if you delete the polygon under the model first, as indicated in
Figure 2.3. Edges must be “free” or open to be copied. Figure 2.4 depicts the process
of moving the selected edges (while the Shift key is held down) to create additional
polygons.
FIGURE 2.4
Copying edges using Shift+Move.
The view in Figure 2.5 is from under the model. Make sure to use Arc Rotate to
arrive at new viewpoints. Do not make the mistake of using the Rotate tool for this.
The Rotate tool will actually rotate your model, and you will end up with a misaligned model. However, if this misalignment does happen to you, create a box
primitive and use the Align tool on the Standard toolbar to align your model to the
box. Select the misaligned object, and then go to Tools, Align; pick the box primitive;
and from the Align dialog box, check the boxes for X, Y, and Z axis in the Align
Orientation group.
In this last phase, you are once again copying edges, but this time using
Scale+Shift instead of Move+Shift. This enables you to close the opening in the base
Chapter 2
Low Poly Modeling
25
of the model, or at least get most of the way there. Continue scaling the edges even
beyond what is shown in Figure 2.5, until you end up with a very small opening,
which you can weld together in the next step.
FIGURE 2.5
Using Scale+Shift key to copy the edges again and close the opening.
Welding Vertices with Weld Threshold
Looking at Figure 2.6, the opening is quite small, but still apparent. To completely
weld this hole shut, you need to select the vertices. If you still have the edges selected, try holding down the Shift key while you click on Vertex mode. This should
convert the selection set from edges to vertices. Depending on your version of 3ds
Max, this may not work, in which case you can select the vertices with a selection
window. In this image, you can see the number of vertices selected listed in the
Selection rollout; this feedback can help you stay on track.
Now that you are in Vertex sub-object mode, go to the Edit Vertices rollout and
click the Weld Settings button (to the right of the Weld button). This should bring
up the dialog box you see in Figure 2.6, which allows you to set a threshold for
welding. This process only works for the selected vertices. Notice the setting Number
of Vertices, Before and After. In this example, there are 42 vertices in the entire
model. When you move the Weld Threshold value up, it zeros in on the selected
vertices and, if they are within the threshold distance, welds them together. Use this
tool by moving the Weld Threshold value higher and higher as you watch both the
vertices and the number readout. In this case, when the six vertices seem to become
one vertex, or when Number of Vertices goes down to 37, you know you are done.
26
Creating Game Art for 3D Engines
FIGURE 2.6 Adjusting a weld threshold.
Creating a Pickup with Three Parts
Although the health patch is one of the simplest models in this chapter, it will ultimately have some of the most complex materials. Torque allows you to have more
than one mesh in a shape, which presents some interesting possibilities when it
comes to materials. In Figure 2.7, the top of the health patch model has been collapsed by moving the upper vertex down, and two additional cones have been
placed against the main model. Both of these have faces removed where they meet
FIGURE 2.7 Three separate meshes make up our health pickup.
Chapter 2
ON THE CD
Low Poly Modeling
27
the main body of the health pickup. These faces are removed because they will not
be seen, and you don’t need them. To remove faces, get into Polygon sub-object
mode, select Polygons, and press the Delete key on your keyboard.
Finally, convert the model to an Editable Mesh, and save the file as HealthPatch.
max. A copy of this file with texturing applied is located on the companion CD-ROM.
It is named HealthPatchTextured.max, and it is located in Files\HealthPatch.
MODELING A POWER CHARGER
The majority of this geometry will be modeled using an eight-sided cone. Refer to
Figure 2.8 for the approximate size and shape of the cone; the completed model is
shown at the left, and the starting primitive is shown at the right. Here, more height
segments make sense, because you need varying diameters to follow the shape in
the finished example. Note that the height of this model is only 16, but that refers to
16 meters. In the game, this model will be about the size of a four-story building.
FIGURE 2.8 Starting the power station with an 8-sided cone.
Figure 2.9 shows the process of selecting all the polygons in the model and
clearing any smoothing that may already exist. This is always a good idea because
you are better able to see what you are doing, and you don’t want to operate under
any random assumptions. If you want to use smoothing later, you can do so as a deliberate choice when the model is ready for it.
In Figure 2.10, in Vertex sub-object mode, the vertices are being windowed, one
row at a time, and moved up toward the top of the model. Then each row of vertices
is scaled with the Select and Uniform Scale tool. In the image, you can see that the
Scale button is turned on, and the Scale gizmo is active on a set of vertices. At this
point, the model is almost ready for additional features.
28
Creating Game Art for 3D Engines
FIGURE 2.9 The cone is now an Editable Poly. Select Polygon and Clear All
under Smoothing Groups.
FIGURE 2.10 Windowing, moving, and scaling vertices to sculpt the model.
One of the first things to notice is that there is a different rotation on the two
models. The finished model at the left has flat polygons facing the front view,
whereas the primitive on the right has its edges facing the front view. If you are
going to build on to this model, it makes sense to do it in a way that is easily editable
from the established orthographic views. That is, you should try to set up this model
so that you can easily add and edit different features by going to the standard viewing modes—that is, top view, left view, front view, and so on.
Chapter 2
Low Poly Modeling
29
Figure 2.11 shows the same two models from the top view, so that the different
rotations of the models are more apparent.
FIGURE 2.11 From the top view, you can see the different orientations of
the two models.
To set up the new model in the proper orientation, you need to figure out how
many degrees each segment of the eight-sided cone includes. If you start with 360
degrees and divide that by 8, you get 45 degrees for each side. This means that if you
rotate the model 45 degrees, it will still have edges lined up to the standard views
instead of polygons as we would prefer. To get the polygons to face the front view,
rotate the model half of 45 degrees, or 22.5 degrees. See Figure 2.12.
FIGURE 2.12 Determining the rotation of the model.
30
Creating Game Art for 3D Engines
Before rotating the model, make sure you are out of sub-object mode, and that
the model is selected. To rotate the model 22.5 degrees, you need to adjust the Angular Snap value so that when you rotate the model, it will snap to that value. To do
this, right-click on the Angle Snap toggle on the Standard toolbar. Adjust the Angle
setting to 2.5 degrees, as shown in Figure 2.13, click the red X at the upper-right corner of the dialog box to close it, and then rotate the model 22.5 degrees.
FIGURE 2.13 Setting an Angular Snap value and rotating the model 22.5 degrees.
Use the F hotkey to get into the Front view. Make a cut in this front polygon so
you can create a ramp for the character to stand on when he is charging his weapon.
Select the polygon and extrude the ramp; now that you have a good orthogonal
view of the ramp, meaning you can look at it straight-on from the Front view, you
can go to Vertex sub-object mode and move vertices to make the ramp line up.
Finally, go ahead and weld the vertices at the end of the ramp so it makes a
smooth transition to the ground (see Figure 2.15).
Convert this model to an Editable Mesh and then inspect it, looking for how the
topology has changed from when the model was an Editable Poly. Depending on
how you worked, you may find a flaw similar to Figure 2.16 on the right side of the
model. The edge that was cut for the ramp left two T-junctions in the model. An
edge has been exposed that is not as effective for unwrapping or proper shading and
lighting as if the edge were going the other way. You can turn this edge now, or you
can take care to remove the T-junction before you convert the model to an Editable
Mesh. If you want to turn the edge, look ahead to Figure 2.31 for an example of
how this is done. Be warned that this takes a little practice. Handle these ambiguous
Chapter 2
Low Poly Modeling
31
FIGURE 2.14 After the ramp is extruded, adjust the vertices from the Left view.
FIGURE 2.15 Using Target Weld to weld two vertices together.
areas before they become a problem by cutting edges yourself before converting an
Editable Poly to an Editable Mesh. Whenever you see a T-junction, either remove
the offending edge, or create additional cuts until the T-junction no longer exists.
Make sure to convert the model back to an Editable Poly so you can continue to
take advantage of the more robust tools it provides. In Figure 2.17, the model has
been converted back to an Editable Poly, and the T-junctions have been removed
by making cuts. You can think of this as relieving pressure, because a T-junction
will otherwise be prone to creating havoc with your model if left untreated. Another
32
Creating Game Art for 3D Engines
FIGURE 2.16 Note the result of leaving T-junctions in the Editable Poly.
way of looking at it is that you are tying off the vertex so that it is no longer a
liability. A T-junction, when not tied off, can create five sides on the neighboring
polygon. When modeling for real-time rendering, triangles are fine, as are quads,
although you may have to turn the inside edge on some of the quad. But leaving
five or more sides on a polygon leaves too much to chance in how the polygon will
be divided into triangles.
FIGURE 2.17 The Editable Poly gets cuts to repair the T-junctions.
Figure 2.18 depicts an inset being made. Select a polygon, and from the Edit
Polygons rollout, click the Inset settings button to launch the dialog box. If you have
more than one polygon selected, try both the Group setting and the By Polygon setting. By Polygon allows each polygon to perform its own inset.
Chapter 2
Low Poly Modeling
33
FIGURE 2.18 Creating an inset.
Once the inset is created, you may want to adjust the vertices so that they are
not a simple offset from the original polygon edges. To do so, get into Vertex subobject mode, and select any two vertices that you want to bring closer together or
spread further apart. Use the Select and Uniform Scale tool to scale them along the
axis they share. This method is used in Figure 2.19 to make the inset more squareshaped, rather than the rectangular shape that its parent polygon has. You can also
select all four vertices and scale them along an axis.
FIGURE 2.19 Scaling the vertices of the inset while Constraints are set to Face.
34
Creating Game Art for 3D Engines
The Edit Geometry rollout has a Constraints setting that is usually set to None. If
you set it to Face, it keeps your vertices constrained to the face of the polygon while
you are scaling them, saving you repair work later. Make sure to set Constraints
back to None when you have completed your task so that you can edit vertices normally again.
While working on only one face here, it is important to note that you can inset
all the faces on the model at once by using the By Polygon option. Also, with Constraints set to Face, you can move the vertices to adjust the size of the inset as an
entire row, quickly arriving at a model similar to Figure 2.23. However, the process
of developing a model with effective use of polygons is sometimes best done one
panel at a time and then cloning copies of that panel into place. This is particularly
true the more complex a panel gets.
Figure 2.20 shows another useful feature of the Editable Poly menu, Hinge from
Edge. This feature is good for building on to existing faces and changing the face
angle at the same time. Take a moment to experiment with multiple segments and
different angle values.
FIGURE 2.20 Using Hinge to extrude the face.
Developing this panel took some time. Rather than go through that process on
every panel around the model, detach this panel and rotate copies of it into position
around the original model. Make sure you are in Polygon sub-object mode, and select all the faces, as shown in Figure 2.21. From the Edit Geometry rollout, click the
Detach button. Name this new object Hinged Panel. This effectively creates a new
object, which you can replicate all the way around the model.
Chapter 2
Low Poly Modeling
35
FIGURE 2.21 One section is selected, detached, and given a name.
You have to get out of sub-object mode to exit the main model and select the
Hinged Panel object you just created. In Figure 2.22, you can see that the Hinged
Panel object has been selected, and the Rotate gizmo is active. If you hold down the
Shift key while you are rotating around the Z axis (the Z axis is highlighted yellow
because it is selected here), you launch the Clone Options dialog box. Make sure
your settings match those in the figure, typing in seven copies (seven new copies,
+ one original = eight total copies). Max divides 360 degrees into 8 and places one
copy every 45 degrees. You want to copy here because you want each element
created to be a separate object; soon they will be joined back together with the original model.
Clicking Attach, as shown on Figure 2.23, allows you to select any object you
want to attach to the current object, one at a time. If you want to select multiple objects from a list, click the Settings button to the right of the Attach button.
At this point, the panels are attached, but their vertices have not been welded
together with the main model. This is impossible to see with the naked eye, but you
can prove it to yourself if you attempt to move one of the vertices where the panels
meet each other. If you can move a vertex and it comes away from the model, something is wrong with that model. To weld everything together, get into Vertex subobject mode, select all the vertices in the model, click the Weld Settings button, and
manipulate the Weld Threshold value until you see a significant change in the number of vertices. If you set the Weld Threshold too high, too many vertices are welded
together. To guard against this, keep a close eye on the model when you perform
this operation. This type of weld only operates on selected vertices, so minimizing
your selection set can help to control the results.
36
Creating Game Art for 3D Engines
FIGURE 2.22
FIGURE 2.23
Rotate+Shift launches the Clone Options dialog box.
The Attach settings button allows you to attach several objects at once.
In Figure 2.24, an extrusion, a hinge, and another extrusion have been added to
the protrusion that is on the front face of the power charger. A uniform scale is
being added to the last extrusion. You can also achieve this effect by using a Bevel
feature.
Chapter 2
Low Poly Modeling
37
FIGURE 2.24 Scaling uniformly to add angular impact to the protrusion.
A commonly used shaping method is demonstrated in Figure 2.25, where a
group of vertices has been window-selected and is going through a process of being
moved and rotated to achieve a more interesting design.
FIGURE 2.25 Rotating selected vertices to achieve a better look.
Figure 2.26 demonstrates using the uniform scale gizmo to reposition vertices.
Select two, four, or more vertices and click-drag the X, Y, or Z axis to bring them
closer together or farther apart.
38
Creating Game Art for 3D Engines
FIGURE 2.26 Using axial scaling to reshape the end of the protrusion.
If you want to snap to particular points, the 3D snap tool is useful. Set your
snaps by right-clicking the Snaps toggle. Select the check boxes you want to use, and
close the dialog by clicking the X in the corner. In Figure 2.27, snaps are being set to
Endpoint and Midpoint.
FIGURE 2.27
accuracy.
Snaps are being set to Endpoint and Midpoint for speed and
If the Snaps toggle is active, your cursor should snap to whatever points you
have it set to; just get into the Cut feature and feel around with the mouse for the
snap, as shown in Figure 2.28. Make sure to turn the Snaps toggle off when you are
finished, because this tool can make normal work difficult if it is kept on.
Chapter 2
Low Poly Modeling
39
FIGURE 2.28 Using the 3D Snap tool to snap to midpoints of an edge.
In Figure 2.29, notice how the new edge created in the previous figure was
terminated by connecting it to two separate vertices. This potential T-junction has
been “tied off,” so you should not have surprises when you convert this model to an
Editable Mesh at the end of this process.
FIGURE 2.29 Cuts are completed with no T-junctions to be found.
40
Creating Game Art for 3D Engines
After you have the basic edges in place, it is easy to add volume and shape to the
model by moving them out a bit, as shown in Figure 2.30. This is most accurately
done from an orthogonal view like front, right, left, or top.
FIGURE 2.30 Moving the new edges to add volume to the protrusion.
ON THE CD
Before this model is ready for unwrapping, it needs to be converted to an Editable
Mesh. This significantly changes the look of the model, because each triangle becomes more obvious. Triangles are not obvious on an Editable Mesh while selected;
you have to click on the 3ds Max background, effectively deselecting the model, to
see the triangles. It is a good idea to use the Arc Rotate tool to inspect the model
from all sides to check the assumptions that Editable Mesh makes about where to
put triangles. In Figure 2.31, the model has been converted into an Editable Mesh,
and an inside edge is being turned using the Turn button, which is available when
you are in Edge sub-object mode. First activate the Turn button, and then click the
edge until you like the result. For clarity, two copies of the same protrusion are
shown in this image. Edge number 1 has just been turned and used to look like edge
number 2.
The last step for this model is to convert it to an Editable Mesh and ensure that
it still looks the way you want it to. Use the Arc Rotate tool to inspect the ways that
triangles were formed, and turn any edges as necessary. In Figure 2.32, the power
charger is ready to be unwrapped. Save the file as PowerCharger.max. A copy of this
file with texturing applied is located on the companion CD-ROM. It is named PowerChargerTextured.max, and it is located in Files\PowerCharger.
Chapter 2
Low Poly Modeling
41
FIGURE 2.31 Turning an edge to further define the shape.
FIGURE 2.32 The model in its finished
state as an Editable Mesh.
MODELING A WEAPON
To model our weapon, a plane is created in the front view and an image applied to it
to use as a template. This template will serve as a guide while modeling. It’s always
a good idea to have references when modeling, texturing, or animating.
42
Creating Game Art for 3D Engines
Creating a Template to Model By
ON THE CD
Reset Max and set units under Customize, Units Setup to metric. Create a plane
in the front view with Length equal to 200 units and Width equal to 550 units.
Set Length Segments to 1 and Width Segments to 1. Use the technique discussed
in Chapter 1 to apply a custom material to the object. The template material is
GunTemplate.jpg, found in Files\Raygun on the companion CD-ROM.
In Figure 2.33, the Material Editor is being launched in order to apply the material to the plane. From this stage in the process, you can see that GunTemplate.jpg is
550 × 200 pixels. Knowing the width and height of the template image is useful,
because if you can put that template on a plane that has the same aspect, or widthto-height ratio, the image will not stretch. There are a few different ways to make a
template fit well on a plane, but setting the size of the plane to the size of the image
(or some multiple of the image) keeps the aspect consistent and is the most straightforward method to explain.
FIGURE 2.33 Creating a plane and applying a template to it to use as a guide for the model.
If the material comes in on the plane upside down or sideways, you can either
rotate the plane 90 or 180 degrees and adjust the height and width values of the
plane accordingly, or you can apply a UVW Map modifier and rotate the gizmo for
the map as necessary. Keep Snap Angle toggle turned on at all times so your rotations are exact.
After you apply the material to the plane, freeze the plane so that you do not
accidentally select it during the modeling process. Objects that are frozen cannot be
selected.
Chapter 2
Low Poly Modeling
43
What you really want here is for the plane to be frozen but the image to be visible. To do this, select the plane and right-click it. From the right-click menu, select
Properties. See Figure 2.34 for a screen shot of this dialog box. Check the Freeze box
and uncheck the Show Frozen in Gray box. This allows this frozen object to retain
its color and material visibility. If you end up freezing the plane and the image turns
gray, right-click again, select Unfreeze All, and try the procedure again.
FIGURE 2.34
Turning on Freeze, and turning off Show Frozen in Gray.
Modeling with a Plane
You have modeled with 3D primitives, but you can also model with a flat plane. After
your material is successfully applied to the template plane, it is time to make another
plane, which can be used to build the weapon. Create a plane, and make sure it is
only one segment in each direction. Position it so that it lies over the stock of the gun.
Although you will be modeling in the front view, go to the top view and move the
modeling plane down so that it is in front of the template. You want the modeling
plane to be in front of the template plane; ultimately, you will be looking through the
modeling plane at the template plane and using the template plane as a guide.
Activate and maximize the front view. Then convert the modeling plane to an
Editable Poly. Right-click the Editable Poly and, from the right-click menu, select
Properties to access the Properties dialog box. Click the See-Through check box to
make it transparent (see Figure 2.35). You can also accomplish this using the hotkey
Alt+X as a toggle for “x-ray” mode.
44
Creating Game Art for 3D Engines
FIGURE 2.35 Convert the plane to an Editable Poly and set it to See-Through.
Move the vertices so that they fit the stock of the gun. Get into Edge sub-object
mode, select the right edge of the plane and, holding down the Shift key, move the
edge toward the right. Continue this Shift+Move process, following the contours of
the template as well as possible along the top vertices of the plane. Figure 2.36 shows
this process. Notice that the Move gizmo is visible in the image. By clicking on the yellow
XY plane of the gizmo, it is easy to create each new plane. Don’t worry about the
lower vertices; they will be matched up later. Stop where the gun barrel starts; because
the barrel is so cylindrical, you are better off using a cylinder to model it separately.
FIGURE 2.36
With the edge of the Editable Poly selected, Shift+Move creates new polygons.
In Figure 2.37, Vertex is the sub-object mode and vertices have been moved to
match up with the lower points on the template. Notice that this template was designed so that the upper vertices line up with the lower vertices, and there are a
planned number of segments of the gun. Having a plan makes plane-modeling go
smoother. Also notice that some parts of the model are being ignored for now, and
will be extruded later.
Chapter 2
Low Poly Modeling
45
FIGURE 2.37 The vertices have been moved to conform to the template.
When you have the basic shape, add edges as necessary for the wings on the
butt of the gun. (See Figure 2.38 to locate these.) Figure 2.38 also shows how to
copy the edges all around the gun to add some depth to it. You will need to change
your view (Arc Rotate) before you do this so that you can see the Y axis of the Move
gizmo. If you need to select additional edges, hold down the Ctrl key and continue
to select edges. Clicking the same edge twice deselects it. When ready, simply
Shift+Move along the Y axis, as shown in the figure. Just as with the health patch,
the edges are copied, in effect creating a new group of polygons.
FIGURE 2.38 Select only the outside edges of the Editable Poly, and then press Shift+Move.
46
Creating Game Art for 3D Engines
It is common to make a few mistakes when working with vertices and edges and
end up with a mess, where the vertices and edges are no longer lying in the same
plane. The next two figures demonstrate how to repair these misaligned vertices. As
shown in Figure 2.39, the first step is to select all the vertices that you would like to
have in a planar alignment.
FIGURE 2.39 If you have misaligned vertices, the first step is to select them.
Figure 2.40 demonstrates what you should do with the selected vertices. Do not
bother with this step unless you need to realign vertices that have somehow been
moved out of alignment. The simplest way to get the selected vertices into alignment
is to activate an orthogonal view that is flat to the plane you want the vertices to
lie within. In Figure 2.40, this means activating the front view. Then, from the Edit
Geometry rollout, click View Align. All selected vertices are then aligned with the
active viewport.
FIGURE 2.40 Activate the viewport that is planar to the vertices, and click View Align.
Chapter 2
Low Poly Modeling
47
Move the edges and vertices as necessary to give the viewport form and volume.
Try to avoid the areas that still need to be added to, where the grip is, and near the
front of the gun. Figure 2.41 shows this stage of the modeling process.
FIGURE 2.41
Adjusting the edges of the model to give it some form and volume.
Adding Symmetry to Mirror and Weld Vertices Simultaneously
Symmetry allows you to mirror a model so that it has two sides, while allowing you to
weld the vertices of the two sides together. Select an edge (it doesn’t matter which
edge, as long as it is somewhere along the seam of the model), and add a Symmetry
modifier from the Modifier drop-down list. Figure 2.42 notes a good edge to use, as
well as the settings that will likely work well for you to apply symmetry correctly.
A common problem when using the symmetry feature is welding together more
vertices than intended. Symmetry welds the vertices together if they are within the
threshold setting. If you don’t take the time to inspect your model carefully as you
are adding symmetry, you may have to go back at some point and do some timeconsuming rework of your mesh.
Setting the threshold too high is even more of a problem when modeling for the
Torque Game Engine than otherwise; this is because for Torque, every unit is a
meter. Max is unitless by default, yet most people model as though each unit were
an inch. If you are designing a couch, 24 × 36 × 72 inches across, a threshold of 0.1
inch is about right; it is a small percentage of the overall size of the model. If you are
designing a weapon that is 1 × 0.2 × 0.4 meters, a threshold of 0.1 meter is a large
percentage of the overall size of the model. Whether you lower the threshold default
on your Symmetry modifier or not, it is a good idea to inspect your model before applying symmetry and moving on.
48
Creating Game Art for 3D Engines
FIGURE 2.42
Selecting an edge and adding a Symmetry modifier to the Editable Poly.
Now that the model has some thickness, it’s time to collapse the Symmetry
modifier. It will be added again after a few more edits. To collapse a modifier in the
modifier stack, right-click it and, from the resulting menu, click Collapse All (see
Figure 2.43). This simplifies the model and allows you to perform necessary edits to
the grip of the gun and the front area of the gun.
FIGURE 2.43
Collapsing the Symmetry modifier.
Chapter 2
Low Poly Modeling
49
When you collapse a modifier, you get the warning shown in Figure 2.44. Click
Yes. If you are unsure about collapsing modifiers, you can opt to click the Hold/Yes
button, which saves a copy of your current modifiers. You can restore this copy by
clicking Fetch from the Edit drop-down menu.
FIGURE 2.44 This warning comes up when you collapse the stack. Click Yes.
In Figure 2.45, the faces at the grip and the body of the gun are being selected
and will soon be extruded a bit. The character will ultimately use these areas to grip
the gun.
FIGURE 2.45
Select the faces where you need to extend the shape of the gun and extrude.
50
Creating Game Art for 3D Engines
There is a lot going on in Figure 2.46. Two faces at the front of the gun, where
the gun barrel will attach, were deleted. Two edges were added, one on each side of
the gun. These edges bring the total number of edges to eight where the barrel will
attach, which is perfect if you create an eight-sided barrel. Creating these edges also
created a T-junction, which was dealt with by creating two edges on each side of the
gun. Finally, this open area was prepared to receive the gun barrel by moving the
existing eight vertices until they had a rounder shape.
FIGURE 2.46
Adding cuts and moving vertices to prepare the end of the gun for the barrel.
In Figure 2.47, the barrel area is zoomed-in. The gun barrel could easily be
created by extruding a cylinder, the same way the power charger was built. However, it is actually faster to draw a line (which creates a spline) and revolve it into a
gun barrel shape. Go to the Create panel, choose Shapes, and select the Line tool.
Draw this line in the front view, and make sure your settings match those in this
screenshot; in the Creation Method rollout, Initial Type should be Corner, and Drag
Type should be Corner. These are the best settings for low poly splines, because they
minimize the number of faces created. When you get the Close Spline dialog box,
click Yes. If you do not get this dialog box, delete the line and start over.
As long as the line is still selected, you can go to the modify panel, enter Vertex
sub-object mode, and move the vertices around until you are satisfied with the
shape of the gun barrel, as shown in Figure 2.48.
Go into Segment sub-object mode, select the axis of the line (the upper horizontal line segment) and, from the Modifier List, add a Lathe modifier. This will not
come up looking proper at first; you will have to adjust some of the settings shown
in Figure 2.49. Direction will probably need to be set to X, for instance. Even then,
the lathed shape will look like it is inside out, which is common for lathed objects.
The face normals have become flipped, meaning that they are facing the wrong way.
Chapter 2
Low Poly Modeling
51
FIGURE 2.47 Drawing a spline, which we will lathe for the gun barrel.
FIGURE 2.48
You can move the vertices of the completed spline to fine-tune.
Just check the Flip Normals check box, and it should look like the gun barrel in the
image. Finally, set the number of segments to 8, so this gun barrel will match up to
the gun body that is waiting for it.
Now that the lathe has been used to create our barrel, right-click the barrel and
select Convert to Editable Poly.
52
Creating Game Art for 3D Engines
FIGURE 2.49
This lathed object took some adjusting via the menu at the right.
The first thing to deal with on this gun barrel is to delete the faces where it will
attach to the gun body. This is necessary because you cannot weld the two shapes
together otherwise—you need openings in both ends for the vertex welds to work.
There are two views shown in Figure 2.50: top view and front view. Use them
both to make sure your gun barrel is aligned to the rest of the gun before getting into
the attachment procedure.
FIGURE 2.50 Both parts aligned. Polygons have
been removed where they will attach.
Chapter 2
Low Poly Modeling
53
Select either the gun body or the gun barrel, and use Attach to attach one object
to the other. At that point, the two will actually be one editable body, even though
you can see some space between them.
Figure 2.51 is a close-up of the vertices at the end of the gun body being welded
to the gun barrel. By welding from the gun body to the gun barrel geometry, you
take advantage of the more perfect cylindrical alignment of the vertices that the gun
barrel has. This is because it was lathed, whereas the vertices at the end of our gun
body were positioned by hand and guesswork.
FIGURE 2.51
Attach the two objects and weld from the gun body to the barrel.
Now that you have the basic shape of the gun complete, it is time to delete half
of the polygons. This sets up the model for another Symmetry modifier. This is being
done so that more modeling and tweaking can be done on only one side of the gun,
yet it will affect the other side of the gun simultaneously. In Figure 2.52, the top
view is current for a clear shot of these polygons, which can then be selected with
the selection window.
In Figure 2.53, symmetry has been added. Remember to select an edge along the
seam of the model before adding symmetry; this helps 3ds Max know where the middle of the symmetry is. You can now edit one side of the gun and have the other side
stay in sync. Notice in this image that the Editable Poly is the current modifier, yet the
Symmetry modifier is active. This is a powerful feature—the ability to work with the
foundational geometry yet see the results of a Symmetry modifier that was added later.
The key to making this work is that the Show End Results On/Off toggle is toggled On.
54
ON THE CD
Creating Game Art for 3D Engines
FIGURE 2.52
From the top view, select half of the polygons, delete, and resymmetry.
FIGURE 2.53
Move vertices on one side of the gun, and the other side stays in sync.
Symmetry is a great tool that can allow you to work twice as fast as usual in
many circumstances. It is deceptively easy to get caught up in modeling both sides of
a symmetrical object; this is a waste of your time. Symmetry can allow you to work
on only one side of the object yet see the results of your efforts on the entire model
dynamically. If you need to add a feature that is unique to one side of the model,
add it after you have collapsed the Symmetry modifier.
At this point, the gun is pretty much ready to go. Perform a final collapse of
the Symmetry modifier, convert the model to an Editable Mesh, and inspect the
triangles to see that the form and flow of the edges is still satisfactory. Save the file as
Raygun.max. A copy of this file in its completed state is named RayGunTextured.max
and is located in Files\Raygun on the companion CD-ROM.
Scaling Models to Fit the Torque Engine
If you imported this weapon in to the Torque Game Engine as it is, it would be as big
as a skyscraper, but you can scale it down easily. Get into Vertex sub-object mode,
and perform a uniform Scale on the model. Check the actual size of the model by
Chapter 2
Low Poly Modeling
55
selecting it and then right-clicking Properties. The Properties menu displays a size for
X, Y, and Z dimensions of the model. Scale all the vertices of the model until the
longest dimension is approximately equal to 1 meter.
If you scale a model and you are not in a sub-object mode, 3ds Max does not
register the actual change in scale properly. The model appears a different size, but if
you check the properties of the model, the scale has not changed. This can affect
how Torque sees the model as well. For that reason, it is recommended that if you
have to scale a model, you either do it at the sub-object level, or you scale it normally
and use a method known as the box trick to force 3ds Max to reevaluate the scale of
the model.
The box trick involves creating a box primitive, converting it to an Editable Poly
or Editable Mesh, using Attach to attach your model to the box, and then, at the
Polygon sub-object level, deleting the polygons that make up the box. This leaves
you with a model that has in effect been reevaluated by 3ds Max and will now register the proper dimensions in Properties.
SUMMARY
We’ve built a simple shape, a pickup, a power charger, and a weapon. Each of these
models has taught us something about 3ds Max that is essential to being a wellrounded modeler. The simple shape taught us about taking care when setting
segments on primitives. The health patch gave us more practice with sub-objects, as
well as showing us how to copy edges, threshold welds, scaling vertices, and deleting
faces. The power station took us through clearing smoothing groups, working with
Angular Snap, targeting welds, dealing with T-junctions, creating insets, using the
scale gizmo axes, applying face constraints, creating a hinge, detaching faces, copying
with the Clone tool, and using the 3D snap. The weapon exercise covered creating
a template in the viewport, plane modeling, using view align, applying symmetry,
collapsing the modifier stack, creating and editing a spline, using the Lathe modifier,
and scaling a model.
In the next chapter, we will look at ways to unwrap these models so that we can
effectively paint textures on them.
This page intentionally left blank
CHAPTER
3
UNWRAPPING GAME ART
In This Chapter
•
•
•
•
•
Unwrapping the Oil Drum
Unwrapping the Weapon
Unwrapping the Ammo Box
Unwrapping the Power Charger
Unwrapping the Health Patch
57
58
Creating Game Art for 3D Engines
U
nwrapping is by no means absolutely necessary for putting a material on a
model; the example in Chapter 1, “Introduction to 3ds Max,” demonstrates
how to apply a custom material to a model. This may be completely adequate for some models and situations, but it almost always results in a general kind
of texture that doesn’t allow for details like edges of panels, rivets, eyes, wrinkles,
and so forth. For more compelling and precise textures, you need to unwrap the
model.
Unwrapping is a means of flattening a 3D model so that you can paint on it. It is
like taking the skin off a 3D model and laying it flat like a canvas. It is of additional
help if the faces you unwrap are right-side up, the way you would normally look at
them, so that as you paint them they make sense. Effort and detail in this phase of
the process make the texturing phase go that much more smoothly and ultimately
result in better work.
UNWRAPPING THE OIL DRUM
It is good to start unwrapping with something simple like the oil drum, because unwrapping can be confusing the first several times you do it. Working through these
examples will prepare you for the more challenging process of unwrapping a character, which will be addressed in Chapter 8, “Character Unwrapping.”
Deciding Between Material Color and Object Color
In Figure 3.1, the Display panel is active. In the Display Color rollout on the Display
panel, Shaded is set to Material Color. It is recommended that you keep Shaded set
to Material Color at all times; setting Shaded to Object Color can sometimes lead to
confusion when you have forgotten about this setting, and cannot figure out why
your materials are not showing up on the model.
Some materials are so detailed that it can be difficult to see the polygons and
their edges. If you want to create a material that is easy to work with for the unwrapping phase, select a new sample slot from the Material Editor, and click the
color box next to Diffuse in the Blinn Basic Parameters rollout. Select a light color
and apply it to the model. If you work with lighter colors, it is easier to see faces and
edges when working in the viewports.
Also notice in this figure that you can use the Display panel to turn off helpers.
(This includes dummy objects, which the Torque Exporter uses as markers.) You will
want to revisit this panel when it’s time to turn the display of dummy objects on or off.
Turning Off Smoothing
Unwrapping a model while smoothing is applied can distort the unwrap process.
The cylinder on the left in Figure 3.2 has smoothing applied to all the polygons. 3ds
Max is trying to make the facets look like they blend smoothly, which looks strange
particularly | https://b-ok.org/book/974299/00d7d7 | CC-MAIN-2019-43 | refinedweb | 18,363 | 67.89 |
In this example, we will compare the F# and C# code for downloading a web page, with a callback to process the text stream.
We’ll start with a straightforward F# implementation.
// "open" brings a .NET namespace into visibility open System.Net open System open System.IO // Fetch the contents of a web page let fetchUrl callback url = let req = WebRequest.Create(Uri(url)) use resp = req.GetResponse() use stream = resp.GetResponseStream() use reader = new IO.StreamReader(stream) callback reader url
Let’s go through this code:
using System.Net” header in C#.
fetchUrlfunction, which takes two arguments, a callback to process the stream, and the url to fetch.
let req = WebRequest.Create(url)the compiler would have complained that it didn’t know which version of
WebRequest.Createto use.
response,
streamand
readervalues, the “
use” keyword is used instead of “
let”. This can only be used in conjunction with classes that implement
IDisposable. It tells the compiler to automatically dispose of the resource when it goes out of scope. This is equivalent to the C# “
using” keyword.
Now here is the equivalent C# implementation.
class WebPageDownloader { public TResult FetchUrl<TResult>( string url, Func<string, StreamReader, TResult> callback) { var req = WebRequest.Create(url); using (var resp = req.GetResponse()) { using (var stream = resp.GetResponseStream()) { using (var reader = new StreamReader(stream)) { return callback(url, reader); } } } } }
As usual, the C# version has more ‘noise’.
TResulttype has to be repeated three times.
* It’s true that in this particular example, when all the
using statements are adjacent, the extra braces and indenting can be removed,
but in the more general case they are needed.
Back in F# land, we can now test the code interactively:
let myCallback (reader:IO.StreamReader) url = let html = reader.ReadToEnd() let html1000 = html.Substring(0,1000) printfn "Downloaded %s. First 1000 is %s" url html1000 html // return all the html //test let google = fetchUrl myCallback ""
Finally, we have to resort to a type declaration for the reader parameter (
reader:IO.StreamReader). This is required because the F# compiler cannot determine the type of the “reader” parameter automatically.
A very useful feature of F# is that you can “bake in” parameters in a function so that they don’t have to be passed in every time. This is why the
url parameter was placed last rather than first, as in the C# version.
The callback can be setup once, while the url varies from call to call.
// build a function with the callback "baked in" let fetchUrl2 = fetchUrl myCallback // test let google = fetchUrl2 "" let bbc = fetchUrl2 "" // test with a list of sites let sites = [""; ""; ""] // process each site in the list sites |> List.map fetchUrl2
The last line (using
List.map) shows how the new function can be easily used in conjunction with list processing functions to download a whole list at once.
Here is the equivalent C# test code:
[Test] public void TestFetchUrlWithCallback() { Func<string, StreamReader, string> myCallback = (url, reader) => { var html = reader.ReadToEnd(); var html1000 = html.Substring(0, 1000); Console.WriteLine( "Downloaded {0}. First 1000 is {1}", url, html1000); return html; }; var downloader = new WebPageDownloader(); var google = downloader.FetchUrl("", myCallback); // test with a list of sites var sites = new List<string> { "", "", ""}; // process each site in the list sites.ForEach(site => downloader.FetchUrl(site, myCallback)); }
Again, the code is a bit noisier than the F# code, with many explicit type references. More importantly, the C# code doesn’t easily allow you to bake in some of the parameters in a function, so the callback must be explicitly referenced every time. | https://fsharpforfunandprofit.com/posts/fvsc-download/ | CC-MAIN-2018-13 | refinedweb | 589 | 59.3 |
openCV3: Not getting the expected output on morphologically transforming an image in opencv
I am trying to do top hat morphological transformation to an image but not getting the expected output for some reason.
# Top Hat: difference between input image and opening kernel = np.ones((5,5),np.float32)/25 tophat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel) plt.subplot(121),plt.imshow(img, cmap='gray'),plt.title('Original') plt.xticks([]), plt.yticks([]) plt.subplot(122),plt.imshow(tophat, cmap='gray'),plt.title('Top Hat') plt.xticks([]), plt.yticks([]) plt.show()
What is expected
What I am getting
EDIT: Added the kernel.
2 answers
- answered 2017-11-15 01:37 yapws87
Do you need to normalize your kernel? Try removing the division by 25 from the kernel.
Morphological kernels are supposed to be consist of "ones" and "zeros". Therefore, no normalization is required. It will work fine with type CV_8UC1 as well.
- answered 2017-11-15 01:43 zindarod
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, ksize=(9,9)) tophat = cv2.morphologyEx(image, cv2.MORPH_TOPHAT, kernel)
- Draw line between two given points (OpenCV, Python)
I am struggling with this problem for an hour by now...
I have an image with a rectangle inside:
This is the code I wrote to find the points for the corners:
import cv2 import numpy as np img = cv2.imread('rect.png') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gray = np.float32(gray) points = cv2.goodFeaturesToTrack(gray, 100, 0.01, 10) points = np.int0(points) for point in points: x, y = point.ravel() cv2.circle(img, (x, y), 3, (0, 255, 0), -1) print(points[0]) print(points[1]) print(points[2]) print(points[3]) cv2.imshow('img', img) cv2.waitKey(0) cv2.imwrite('rect.png', img)
This is the result:
As you can see, it works perfect. What I want is to draw a line along the upper/lower points (x1,x2 - x3,x4).
What I produced since now is this...
cv2.line(img, (points[0]), (points[1]), (0, 255, 0), thickness=3, lineType=8) cv2.imshow('img', img) cv2.waitKey(0)
But it doesn't work.
Any idea ?
The result should be like this:
The two lines must pass along the coordinates of the points.
print(points[0])above give the next output, as example:
[[561 168]] [[155 168]] [[561 53]] [[155 53]]
Thanks
- How to convert video from avi to mkv via python
I am engaged in video processing and faced the problem of converting the avi format to mkv. I try to solve this problem,with opencv library, but not one codec was able to record video in mkv format. Example
fourcc = cv2.VideoWriter_fourcc(*'DIB ') out = cv2.VideoWriter('output.mkv', fourcc, 20.0, (frames[0].shape[1], frames[0].shape[0])) for frame in frames: out.write(frame) out.release() enter code here
After that I found the library ffmpy it can convert from any format to any. I decided that I will save the result of my processing in avi format, and then convert to mkv using this code
def convertVideo(): ff = ffmpy.FFmpeg( inputs={'output.avi': None}, outputs={'output.mkv': None} ) ff.run()
This fragment really converts avi to mkv, but if the avi file is created with opencv, then the conversion does not work.
How to write a file in mkv format on WindowsOS using opencv and python?
Can I convert a file received by opencv in avi format to mkv format using ffmpy?
- Error in Running Docker image. Showing no module named cv2,request,boto3
#!/usr/bin/env python from time import sleep import datetime import os import shutil import cv2 import io import numpy as np import glob from threading import Thread import urllib2 import requests import json import boto3 import datetime
I am not able to run my script on docker as I am not able to run modules like
cv2,
numpy,
requestsand
boto3. It works perfectly when I run it on terminal but when I run it as docker image it is showing error that no modules named ... How can i make it run on my docker?
Dockerfile:
FROM resin/raspberry-pi-python:latest RUN mkdir /myscript WORKDIR /myscript COPY capturing.py . CMD ["/myscript/capturing.py", "-flag"]
- 3D plotting with Python 3
I am looking to plot a 3D graph using something like?
- Why am I getting this huge error in Python 3.6.2?
I am writing a chatbot for discord and it has been running perfectly up until today. When I tried to run it today, I got a HUGE error that looks like this:
Can someone help me figure out what is going on here because I have never gotten an error this big before and I don't get what stuff like "[[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)]]" mean.
I am using Python 3.6.2 with the discord.py, asyncio modules.
Also if it makes any difference, I am running this program on Sublime Text 3 with SublimeREPL.
Any help is greatly appreciated.
Code:
import discord import asyncio import random import smtplib client = discord.Client() # When the bot is ready and online. @client.event async def on_ready(): print("logged in as:", client.user.name) print("ID:", client.user.id) print("Ready to go!") # When a message is sent. @client.event async def on_message(message): if message.author == client.user: return elif message.content.startswith("!invite"): # The !invite command emails the invite code to a specified email (ex. !invite example12@gmail.com) split = str(message.content).split() recievingEmail = split[1] content = ("email content goes here") mail = smtplib.SMTP("smtp.gmail.com", 587) mail.ehlo() mail.starttls() mail.login("sender email goes here", "sender email password goes here") mail.sendmail("sender email goes here", recievingEmail, content) mail.close() await client.send_message(message.channel, "Invite code sent!") elif message.content.startswith("!rand"): # The "!rand" command generates a random number between 1 and 100 randomNumber = str(random.randint(0, 100)) response = ("Your random number is", randomNumber) print(response) await client.send_message(message.channel, response) elif message.content.startswith("!help"): #send a direct message with a list of commands for things that the bot can do. client.send_message(message.channel, "Here is a list of things that I can do: \n\n" "!invite - Type '!invite insert email here' in the chat to send an email with an invite link to someone so that they can join the server.\n" "!rand - Type '!rand' into the chat to generate a random number between 1 and 100.\n\n" "Hope this helps!") #When a new user joins the server. @client.event async def on_member_join(member): # When a new member joins the server, the bot will send a direct message with some rules to them. await client.send_message(member, "message content goes here") client.run("Discord Application Token goes here")
Error:
Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/aiohttp/connector.py", line 601, in _create_direct_connection local_addr=self._local_addr) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/base_events.py", line 803, in create_connection sock, protocol_factory, ssl, server_hostname) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/base_events.py", line 829, in _create_connection_transport yield from waiter File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/sslproto.py", line 503, in data_received ssldata, appdata = self._sslpipe.feed_ssldata(data) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/sslproto.py", line 201, in feed_ssldata self._sslobj.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 689, in do_handshake self._sslobj.do_handshake() ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/aiohttp/connector.py", line 304, in connect yield from self._create_connection(req) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/aiohttp/connector.py", line 578, in _create_connection transport, proto = yield from self._create_direct_connection(req) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/aiohttp/connector.py", line 624, in _create_direct_connection (req.host, req.port, exc.strerror)) from exc aiohttp.errors.ClientOSError: [Errno 1] Can not connect to discordapp.com:443 [[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)] The above exception was the direct cause of the following exception: Traceback (most recent call last): File "bot-1025.py", line 70, in <module> client.run("Discord Application Token goes here") File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/client.py", line 519, in run self.loop.run_until_complete(self.start(*args, **kwargs)) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/base_events.py", line 467, in run_until_complete return future.result() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/client.py", line 490, in start yield from self.login(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/client.py", line 416, in login yield from getattr(self, '_login_' + str(n))(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/client.py", line 346, in _login_1 data = yield from self.http.static_login(token, bot=is_bot) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/http.py", line 258, in static_login data = yield from self.request(Route('GET', '/users/@me')) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/http.py", line 137, in request r = yield from self.session.request(method, url, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/aiohttp/client.py", line 555, in __iter__ resp = yield from self._coro File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/aiohttp/client.py", line 198, in _request conn = yield from self._connector.connect(req) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/aiohttp/connector.py", line 314, in connect .format(key, exc.strerror)) from exc aiohttp.errors.ClientOSError: [Errno 1] Cannot connect to host discordapp.com:443 ssl:True [Can not connect to discordapp.com:443 [[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)]]
- Strange inheritance of namedtuple methods in custom class
My goal is to create a class that behaves like a tuple except for the equality/inequality method(s), because I don't want
MyTuple(1, 2, 3) == (1, 2, 3)to be
Trueand I want to use it for dictionary keys that are distinct from its
tuplecounterparts. I finally did it, but I came across some strange behavior that is unexplainable to me.
I thought the most convenient way to reach this goal, was to inherit from a
namedtuple. To prove a point, at first without the special (in)equality methods:
from collections import namedtuple class MyTuple(namedtuple('MyTuple', 'a b c')): pass print({MyTuple(1, 2, 3): 'my-tuple', (1, 2, 3): 'just-tuple'})
Out:
{MyTuple(a=1, b=2, c=3): 'just-tuple'}
It is a bit strange that python3.6 keeps the first key for the second value, but they are equal, so that's fine I guess.
Now I implemented the (in)equality method(s) and something unexpected happened:
class MyTuple(namedtuple('MyTuple', 'a b c')): def __eq__(self, other): return isinstance(other, MyTuple) and tuple(self) == tuple(other) # No, it is not __ne__ that is missing... print({MyTuple(1, 2, 3): 'my-tuple', (1, 2, 3): 'just-tuple'})
Out:
Traceback (most recent call last) ----> 7 print({MyTuple(1, 2, 3): 'my-tuple', (1, 2, 3): 'just-tuple'}) TypeError: unhashable type: 'MyTuple'
I did not remove the
__hash__method, so how can it disappear?
It does work with an additional reimplemented hash function, though:
class MyTuple(namedtuple('MyTuple', 'a b c')): def __eq__(self, other): return isinstance(other, MyTuple) and tuple(self) == tuple(other) def __hash__(self): return hash(tuple(self)) # (adding some kind of salt may reduce the probability of # hash collsions, but it works this way)
Out:
{MyTuple(a=1, b=2, c=3): 'my-tuple', (1, 2, 3): 'just-tuple'}
Question(s):
- Why do I have to implement the hash method myself?
- How was it deleted in the first place?
- Is there something like an "DistinctTuple" in some Python library or some other shortcut that I have been missing?
Thanks for your efforts.
- Why are two identical windows created? OpenCV 3.3
i have the code and he work. But when I start it creates two windows. One gray is completely, and the second with the image from the camera. Tell me how to remove a gray window and why it is generally created?
int main() { VideoCapture cap(0); if (!cap.isOpened()) return -1; double dWidth = cap.get(CV_CAP_PROP_FRAME_WIDTH); double dHeight = cap.get(CV_CAP_PROP_FRAME_HEIGHT); cout << "Frame size : " << dWidth << " x " << dHeight << endl; namedWindow("MyVideo"); Mat frame; while (1) { cap >> frame; imshow("MyVideo", frame); if (waitKey(1) == 27) break; } cap.release(); return 0; }
- OpenCV Returning error message when webcam is not connected
I am using OpenCV 3.3 with Python 2.7 on a Windows 10 PC. In one of my projects, I am connecting an external webcam to do some tracking. Everything works well as long as the webcam is connected. If the webcam is disconnected before the program runs/during the program, the program crashes. When I tried a dummy program to check what's going wrong, I noticed that the program crashes in the line where i call cv2.VideoCapture(0) itself.
Code Snippet:
cap=cv2.VideoCapture(0) -- this line is in the main program and if camera is not connected, the program crashes at this point
--The below lines are inside a function and is called by the main program based on some other input
r, a = cap.read()
while not r:
print 'Reconnect Camera'
r , a = cap.read()
print 'All Okay!'
I put the while loop in there to prevent problems if the camera is disconnected after the cap=cv2.VideoCapture(0) but before cap.read() inside the function. This also does not do the work as 'r' value becomes true in the second iteration even after the camera disconnects. I have put a graph below to represent the behavior of 'r' with camera's connection.
a -> Camera is disconnected and 'r' goes to false;b -> Camera is still disconnected but 'r' is true now;c-> Camera is re-connected and 'r' goes to false;d -> Camera is connected, 'r' goes back to true but
I might be doing something wrong! How do I fix this?! Thanks in advance guys! | http://quabr.com/47297146/opencv3-not-getting-the-expected-output-on-morphologically-transforming-an-imag | CC-MAIN-2017-47 | refinedweb | 2,449 | 51.85 |
There are some cases when you have a dataset that is mostly unlabeled. The problems start when you want to structure the datasets and make it valuable by labeling it. In machine learning, there are various methods for labeling these datasets. Clustering is one of them. In this tutorial of “How to“, you will learn to do K Means Clustering in Python.
What is K Means Clustering Algorithm?
It is a clustering algorithm that is a simple Unsupervised algorithm used to predict groups from an unlabeled dataset. In Unsupervised machine learning, you don’t need to supervise the model. Here the model does its own work to find the patterns in the dataset. And then it automatically labels the unlabeled data.
In the K Means clustering predictions are dependent or based on the two values.
1.The number of cluster centers ( Centroid k)
2. Nearest Mean value between the observations.
There are many popular use cases of the K Means Clustering and some of them are Price and cost Modeling of a Specific Market, Fraud Detection, Portfolio or Hedge Fund Management.
Before going into details and coding part of the K Mean Clustering in Python, you should keep in mind that Clustering is always done on Scaled Variable (Normalized). It means the Mean should be zero and the sum of the covariance should be equal to one. And the other things to remember is the use of a scatter plot or the data table for taking the estimated number of the centroids or the cluster centers (k).
Step 1: Import the necessary Library required for K means Clustering model
import pandas as pd import numpy as np import matplotlib.pyplot as plt from pylab import rcParams #sklearn import sklearn from sklearn.cluster import KMeans from sklearn.preprocessing import scale # for scaling the data import sklearn.metrics as sm # for evaluating the model from sklearn import datasets from sklearn.metrics import confusion_matrix,classification_report
Step 2: Define the Parameters for the Visualization
%matplotlib inline rcParams["figure.figsize"] =20,10
I am using the Jupyter notebook there for showing the figure inline, I am calling the statement %matplotlib inline.
Step 3: Load and scale the Dataset.
I am loading the default sklearn Iris dataset. You can also use your own dataset. But for the demonstration, I am using the default dataset.
iris = datasets.load_iris() #scale the data data = scale(iris.data) # scale the iris data target = pd.DataFrame(iris.target) # define the target variable_names = iris.feature_names data[0:10]
Here the data is the scaled data and the target is the species of the data.
Please note that the data[0:10] will return the np array only.
Step 4: Build the Cluster Model and model the output
In this step, you will build the K means cluster model and will call the fit() method for the dataset. After that, you will mode the output for the data visualization.
clustering = KMeans(n_clusters=3,random_state=5) #fit the dataset clustering.fit(data) iris_df = pd.DataFrame(iris.data) iris_df.columns = ["sepal_length","sepal_width","petal_length","petal_width" ] target.columns =["Target"]
The above output defines the KMeans() cluster method has been called. You can see there are various arguments are defined inside the method. The type of the algorithm, the number of clusters (n_clusters). e.t.c. You can know about it here. K-Means clustering
Step 5: Plot the Model Output using Matplotlib[clustering.labels_],s=50) plt.title("K means Classifcation")
Both figures suggest that the model has accurately predicted clusters. The only thing you are seeing is the clusters are mislabelled. To reassign the Label it uses we use the np.choose() method. To do so you change the label position from [0,1,2] to [2,0,1]. The full code is given below.
relabel = np.choose(clustering.labels_,[2,0,1]).astype(np.int64)[relabel],s=50) plt.title("K means Classifcation")
d
Step 6: Evaluate the Accuracy of the Cluster Results
At the last step, you will verify the results for the accuracy of the model. In order to do so, you use sklearn classification reports.
print(classification_report(target,relabel))
Before verifying the results know the following term.
Precision: It measures the relevancy of the model.
Recall: Measures the completeness of the model.
Highly Accurate Model Results = High Precision + High Recall
In our case, the average Precision is 83% and the average Recall is 83% of the entire dataset. From these results, you can say our model is giving highly accurate results.
Conclusion
K means clustering model is a popular way of clustering the datasets that are unlabelled. But In the real world, you will get large datasets that are mostly unstructured. Thus to make it a structured dataset. You will use machine learning algorithms. There are also other types of clustering methods. The type of Clustering algorithms you will choose will completely depend upon the dataset.
I think you must have easily understood the K Mean Clustering algorithm. In order to get any help from our side, you can directly message us on the Data Science Learn Page. We are always ready to help you.
Thanks
Data Science Learner Team
Source:
K Means Clustering Documentation
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox. | https://www.datasciencelearner.com/k-means-clustering-in-python-label-dataset/ | CC-MAIN-2021-39 | refinedweb | 881 | 58.79 |
QtQuick.qtquick-visualcanvas-scenegraph-renderer
This document explains how the scene graph renderer populates a tree of QSGNode instances. Once created, this tree is a complete description of how a certain frame should be rendered. It does not contain any references back to the Qt Quick items at all and will on most platforms be processed and rendered in a separate thread. The renderer is a self contained part of the scene graph which traverses the QSGNode tree and uses geometry defined in QSGGeometryNode and shader state defined in QSGMaterial to schedule OpenGL state change and draw calls.
If needed, the renderer can be completely replaced using the internal scene graph back-end API. This is mostly interesting for platform vendors who wish to take advantage of non-standard hardware features. For majority of use cases, the default renderer will be sufficient.
The default renderer focuses on two primary strategies to optimize the rendering. Batching of draw calls and retention of geometry on the GPU.
Batch. Consider the following use case:
The simplest way of drawing this list is on a cell-by-cell basis. First the background is drawn. This is a rectangle of a specific color. In OpenGL terms this means selecting a shader program to do solid color fills, setting up the fill color, setting the transformation matrix containing the x and y offsets and then using for instance
glDrawArrays draw the two triangles making up the bounding rectangle of the icon. The text and separator line between cells follow a similar pattern. And this process is repeated for every cell in the list, so for a longer list, the overhead imposed by OpenGL state changes and draw calls completely outweighs the benefit that using a hardware accelerated API could provide.
When each primitive is large, this overhead is negligible, but in the case of a typical UI, there are many small items which add up to a considerable overhead.
The default scene graph renderer works within these limitations and will try to merge individual primitives together into batches while preserving the exact same visual result. The result is fewer OpenGL state changes and a minimal amount of draw calls, resulting in optimal performance.
Opaque Primitives
The renderer separates between opaque primitives and primitives which require alpha blending. By using OpenGL's Z-buffer and giving each primitive a unique z position, the renderer can freely reorder opaque primitives without any regard for their location on screen and which other elements they overlap with. By looking at each primitive's material state, the renderer will create opaque batches. From Qt Quick core item set, this includes Rectangle items with opaque colors and fully opaque images, such as JPEGs or BMPs.
Another benefit of using opaque primitives, is that opaque primitives does not require
GL_BLEND to be enabled which can be quite costly, especially on mobile and embedded GPUs.
Opaque primitives are rendered in a front-to-back manner with
glDepthMask and
GL_DEPTH_TEST enabled. On GPUs that internally do early-z checks, this means that the fragment shader does not need to run for pixels or blocks of pixels that are obscured. Beware that the renderer still needs to take these nodes into account and the vertex shader is still run for every vertex in these primitives, so if the application knows that something is fully obscured, the best thing to do is to explicitly hide it using Item::visible or Item::opacity.
Note: The Item::z is used to control an Item's stacking order relative to its siblings. It has no direct relation to the renderer and OpenGL's Z-buffer.
Alpha Blended Primitives
Once opaque primitives have been drawn, the renderer will disable
glDepthMask, enable
GL_BLEND and render all alpha blended primitives in a back-to-front manner.
Batching of alpha blended primitives requires a bit more effort in the renderer as elements that are overlapping need to be rendered in the correct order for alpha blending to look correct. Relying on the Z-buffer alone is not enough. The renderer does a pass over all alpha blended primitives and will look at their bounding rect in addition to their material state to figure out which elements can be batched and which can not.
In the left-most case, the blue backgrounds can be drawn in one call and the two text elements in another call, as the texts only overlap a background which they are stacked in front of. In the right-most case, the background of "Item 4" overlaps the text of "Item 3" so in this case, each of backgrounds and texts need to be drawn using separate calls.
Z-wise, the alpha primitives are interleaved with the opaque nodes and may trigger early-z when available, but again, setting Item::visible to false is always faster.
Mixing with 3D primitives::vertexShader() and compresses the z values of the vertex after the model-view and projection matrices has been applied and then adds a small translation on the z to position it the correct z position.
The compression assumes that the z values are in the range of 0 to 1.
Texture Atlas.
Note: Large textures do not go into the texture atlas.
Atlas based textures are created by passing QQuickWindow::TextureCanUseAtlas to the QQuickWindow::createTextureFromImage().
Note: Atlas based textures do not have texture coordinates ranging from 0 to 1. Use QSGTexture::normalizedTextureSubRect() to get the atlas texture coordinates.
The scene graph uses heuristics to figure out how large the atlas should be and what the size threshold for being entered into the atlas is. If different values are needed, it is possible to override them using the environment variables
QSG_ATLAS_WIDTH=[width],
QSG_ATLAS_HEIGHT=[height] and
QSG_ATLAS_SIZE_LIMIT=[size]. Changing these values will mostly be interesting for platform vendors.
Batch Roots
In addition to mergin compatible primitives into batches, the default renderer also tries to minimize the amount of data that needs to be sent to the GPU for every frame. The default renderer identifies subtrees which belong together and tries to put these into separate batches. Once batches are identified, they are merged, uploaded and stored in GPU memory, using Vertex Buffer Objects.
Transform Nodes
Each Qt Quick Item inserts a QSGTransformNode into the scene graph tree to manage its x, y, scale or rotation. Child items will be populated under this transform node. The default renderer tracks the state of transform nodes between frames, and will look at subtrees to decide if a transform node is a good candidate to become a root for a set of batches. A transform node which changes between frames and which has a fairly complex subtree, can become a batch root.
QSGGeometryNodes in the subtree of a batch root are pre-transformed relative to the root on the CPU. They are then uploaded and retained on the GPU. When the transform changes, the renderer only needs to update the matrix of the root, not each individual item, making list and grid scrolling very fast. For successive frames, as long as nodes are not being added or removed, rendering the list is effectively for free. When new content enters the subtree, the batch that gets it is rebuilt, but this is still relatively fast. There are usually several unchanging frames for every frame with added or removed nodes when panning through a grid or list.
Another benefit of identifying transform nodes as batch roots is that it allows the renderer to retain the parts of the tree that has not changed. For instance, say a UI consists of a list and a button row. When the list is being scrolled and delegates are being added and removed, the rest of the UI, the button row, is unchanged and can be drawn using the geometry already stored on the GPU.
The node and vertex threshold for a transform node to become a batch root can be overridden using the environment variables
QSG_RENDERER_BATCH_NODE_THRESHOLD=[count] and
QSG_RENDERER_BATCH_VERTEX_THRESHOLD=[count]. Overriding these flags will be mostly useful for platform vendors.
Note: Beneath a batch root, one batch is created for each unique set of material state and geometry type.
Clipping
When setting Item::clip to true, it will create a QSGClipNode with a rectangle in its geometry. The default renderer will apply this clip by using scissoring in OpenGL. If the item is rotated by a non-90-degree angle, the OpenGL's stencil buffer is used. Qt Quick Item only supports setting a rectangle as clip through QML, but the scene graph API and the default renderer can use any shape for clipping.
When applying a clip to a subtree, that subtree needs to be rendered with a unique OpenGL state. This means that when Item::clip is true, batching of that item is limited to its children. When there are many children, like a ListView or GridView, or complex children, like a TextArea, this is fine. One should, however, use clip on smaller items with caution as it prevents batching. This includes button label, text field or list delegate and table cells.
Vertex Buffers
Each batch uses a vertex buffer object (VBO) to store its data on the GPU. This vertex buffer is retained between frames and updated when the part of the scene graph that it represents changes.
By default, the renderer will upload data into the VBO using
GL_STATIC_DRAW. It is possible to select different upload strategy by setting the environment variable
QSG_RENDERER_BUFFER_STRATEGY=[strategy]. Valid values are
stream and
dynamic. Changing this value is mostly useful for platform vendors.
Antialiasing
The scene graph supports two types of antialiasing. By default, primitives such as rectangles and images will be antialiased by adding more vertices along the edge of the primitives so that the edges fade to transparent. We call this method vertex antialiasing. If the user requests a multisampled OpenGL context, by setting a QSurfaceFormat with samples greater than
0 using QQuickWindow::setFormat(), the scene graph will prefer multisample based antialiasing (MSAA). The two techniques will affect how the rendering happens internally and have different limitations.
It is also possible to override the antialiasing method used by setting the environment variable
QSG_ANTIALIASING_METHOD to either
vertex or
msaa.
Vertex antialiasing can produce seams between edges of adjacent primitives, even when the two edges are mathmatically the same. Multisample antialiasing does not.
Vertex Antialiasing
Vertex antialiasing can be enabled and disabled on a per-item basis using the Item::antialiasing property. It will work regardless of what the underlying hardware supports and produces higher quality antialiasing, both for normally rendered primitives and also for primitives captured into framebuffer objects, for instance using the ShaderEffectSource type.
The downside to using vertex antialiasing is that each primitive with antialiasing enabled will have to be blended. In terms of batching, this means that the renderer needs to do more work to figure out if the primitive can be batched or not and due to overlaps with other elements in the scene, it may also result in less batching, which could impact performance.
On low-end hardware blending can also be quite expensive so for an image or rounded rectangle that covers most of the screen, the amount of blending needed for the interior of these primitives can result in significant performance loss as the entire primitive must be blended.
Multisample Antialiasing
Multisample antialiasing is a hardware feature where the hardware calculates a coverage value per pixel in the primitive. Some hardware can multisample at a very low cost, while other hardware may need both more memory and more GPU cycles to render a frame.
Using multisample antialiasing, many primitives, such as rounded rectangles and image elements can be antialiased and still be opaque in the scene graph. This means the renderer has an easier job when creating batches and can rely on early-z to avoid overdraw.
When multisample antialiasing is used, content rendered into framebuffer objects, need additional extensions to support multisampling of framebuffers. Typically
GL_EXT_framebuffer_multisample and
GL_EXT_framebuffer_blit. Most desktop chips have these extensions present, but they are less common in embedded chips. When framebuffer multisampling is not available in the hardware, content rendered into framebuffer objects will not be antialiased, including the content of a ShaderEffectSource.
Performance
As stated in the beginning, understanding the finer details of the renderer is not required to get good performance. It is written to optimize for common use cases and will perform quite well under almost any circumstance.
- Good performance comes from effective batching, with as little as possible of the geometry being uploaded again and again. By setting the environment variable
QSG_RENDERER_DEBUG=render, the renderer will output statistics on how well the batching goes, how many batches, which batches are retained and which are opaque and not. When striving for optimal performance, uploads should happen only when really needed, batches should be fewer than 10 and at least 3-4 of them should be opaque.
- QQuickWindow::TextureCanUseAtlas when an QQuickImageProvider or creating images with QQuickWindow::createTextureFromImage(), let the image have QImage::Format_RGB32, when possible.
- Be aware of that overlapping compond items, like in the illustration above, can not be batched.
- Clipping breaks batching. Never use on a per-item basis, inside tables cells, item delegates or similar. Instead of clipping text, use eliding. Instead of clipping an image, create a QQuickImageProvider that returns a cropped image.
- Batching only works for 16-bit indices. All built-in items use 16-bit indices, but custom geometry is free to also use 32-bit indices.
- Some material flags prevent batching, the most limiting one being QSGMaterial::RequiresFullMatrix which prevents all batching.
- Applications with a monochrome background should set it using QQuickWindow::setColor() rather than using a top-level Rectangle item. QQuickWindow::setColor() will be used in a call to
glClear(), which is potentially faster.
- Mipmapped Image items are not placed in global atlas and will not be batched.
If an application performs poorly, make sure that rendering is actually the bottleneck. Use a profiler! The environment variable
QSG_RENDER_TIMING=1 will output a number of useful timing parameters which can be useful in pinpointing where a problem lies.
Visualizing
To visualize the various aspects of the scene graph's default renderer, the
QSG_VISUALIZE environment variable can be set to one of the values detailed in each section below. We provide examples of the output of some of the variables using the following QML code:
import QtQuick 2.2 Rectangle { width: 200 height: 140 ListView { id: clippedList x: 20 y: 20 width: 70 height: 100 clip: true model: ["Item A", "Item B", "Item C", "Item D"] delegate: Rectangle { color: "lightblue" width: parent.width height: 25 Text { text: modelData anchors.fill: parent horizontalAlignment: Text.AlignHCenter verticalAlignment: Text.AlignVCenter } } } ListView { id: clippedDelegateList x: clippedList.x + clippedList.width + 20 y: 20 width: 70 height: 100 clip: true model: ["Item A", "Item B", "Item C", "Item D"] delegate: Rectangle { color: "lightblue" width: parent.width height: 25 clip: true Text { text: modelData anchors.fill: parent horizontalAlignment: Text.AlignHCenter verticalAlignment: Text.AlignVCenter } } } }
For the ListView on the left, we set its clip property to
true. For the ListView on right, we also set each delegate's clip property to
true to illustrate the effects of clipping on batching.
Original
Note: The visualized elements do not respect clipping, and rendering order is arbitrary.
Visualizing Batches
Setting
Setting
QSG_VISUALIZE to
clip draws red areas on top of the scene to indicate clipping. As Qt Quick Items do not clip by default, no clipping is usually visualized.
QSG_VISUALIZE=clip
Visualizing Changes
Setting
QSG_VISUALIZE to
changes visualizes changes in the renderer. Changes in the scenegraph are visualized with a flashing overlay of a random color. Changes on a primitive are visualized with a solid color, while changes in an ancestor, such as matrix or opacity changes, are visualized with a pattern.
Visualizing Overdraw
Setting
QSG_VISUALIZE to
overdraw visualizes overdraw in the renderer. Visualize all items in 3D to highlight overdraws. This mode can also be used to detect geometry outside the viewport to some extent. Opaque items are rendered with a green tint, while translucent items are rendered with a red tint. The bounding box for the viewport is rendered in blue. Opaque content is easier for the scenegraph to process and is usually faster to render.
Note that the root rectangle in the code above is superfluous as the window is also white, so drawing the rectangle is a waste of resources in this case. Changing it to an Item can give a slight performance boost.
QSG_VISUALIZE=overdraw | https://phone.docs.ubuntu.com/en/apps/api-qml-current/QtQuick.qtquick-visualcanvas-scenegraph-renderer | CC-MAIN-2020-45 | refinedweb | 2,749 | 52.9 |
The Web Animations API lets us construct animations and control their playback with JavaScript. The API opens the browser’s animation engine to developers and was designed to underlie implementations of both CSS animations and transitions, leaving the door open to future animation effects. It is one of the most performant ways to animate on the Web, letting the browser make its own internal optimizations without hacks, coercion, or
window.requestAnimationFrame().
With the Web Animations API, we can move interactive animations from stylesheets to JavaScript, separating presentation from behavior. We no longer need to rely on DOM-heavy techniques such as!
For the rest of this article, I will sometimes refer to the Web Animation API as WAAPI. When searching for resources on the Web Animation API, you might be led astray by searching “Web Animation API” so, to make it easy to find resources, I feel we should adopt the term WAAPI; tell me what you think in the comments below.
This is the library I made with the WAAPIThis is the library I made with the WAAPI
@okikio/animate is an animation library for the modern web. It was inspired by animateplus, and animejs; it is focused on performance and developer experience, and utilizes the Web Animation API to deliver butter-smooth animations at a small size, weighing in at ~5.79 KB (minified and gzipped).
The story behind @okikio/animateThe story behind @okikio/animate
In 2020, I decided to make a more efficient PJAX library, similar to Rezo Zero’s – Starting Blocks project, but with the ease of use of barbajs. I felt starting blocks was easier to extend with custom functionality, and could be made smoother, faster, and easier to use.
Note: if you don’t know what a PJAX library is I suggest checking out MoOx/pjax; in short, PJAX allows for smooth transitions between pages using fetch requests and switching out DOM Elements.
Over time my intent shifted, and I started noticing how often sites from awwwards.com used PJAX, but often butchered the natural experience of the site and browser . Many of the sites looked cool at first glance, but the actual usage often told a different story — scrollbars were often overridden, prefetching was often too eager, and a lack of preparation for people without powerful internet connections, CPUs and/or GPUs. So, I decided to progressively enhance the library I was going to build. I started what I call the “native initiative” stored in the GitHub repo okikio/native; a means of introducing all the cool and modern features in a highly performant, compliant, and lightweight way.
For the native initiative I designed the PJAX library @okikio/native; while testing on an actual project, I ran into the Web Animation API, and realized there were no libraries that took advantage of it, so, I developed @okikio/animate, to create a browser compliant animation library. (Note: this was in 2020, around the same time use-web-animations by wellyshen was being developed. If you are using react and need some quick animate.css like effects, use-web-animations is a good fit.) At first, it was supposed to be simple wrapper but, little by little, I built on it and it’s now at 80% feature parity with more mature animation libraries.
Note: you can read more on the native initiative as well as the @okikio/native library on the Github repo okikio/native. Also, okikio/native, is a monorepo with @okikio/native and @okikio/animate being sub-packages within it.
Where @okikio/animate fits into this articleWhere @okikio/animate fits into this article
The Web Animation API is very open in design. It is functional on its own but it’s not the most developer-friendly or intuitive API, so I developed @okikio/animate to act as a wrapper around the WAAPI and introduce the features you know and love from other more mature animation libraries (with some new features included) to the high-performance nature of the Web Animation API. Give the project’s README a read for much more context.
Now, let’s get startedNow, let’s get started
@okikio/animate creates animations by creating new instances of Animate (a class that acts as a wrapper around the Web Animation API).
import { Animate } from"@okikio/animate"; new Animate({ target: [/* ... */], duration: 2000, // ... });
The
Animate class receives a set of targets to animate, it then creates a list of WAAPI Animation instances, alongside a main animation (the main animation is a small Animation instance that is set to animate over a non-visible element, it exists as a way of tracking the progress of the animations of the various target elements), the
Animate class then plays each target elements Animation instance, including the main animation, to create smooth animations.
The main animation is there to ensure accuracy in different browser vendor implementations of WAAPI. The main animation is stored in
Animate.prototype.mainAnimation, while the target element’s Animation instances are stored in a
WeakMap, with the key being its
KeyframeEffect. You can access the animation for a specific target using the
Animate.prototype.getAnimation(el).
You don‘t need to fully understand the prior sentences, but they will aid your understanding of what @okikio/animate does. If you want to learn more about how WAAPI works, check out MDN, or if you would like to learn more about the @okikio/animate library, I’d suggest checking out the okikio/native project on GitHub.
Usage, examples and demosUsage, examples and demos
By default, creating a new instance of Animate is very annoying, so, I created the
animate function, which creates new Animate instances every time it’s called.
import animate from "@okikio/animate"; // or import { animate } from "@okikio/animate"; animate({ target: [/* ... */], duration: 2000, // ... });
When using the @okikio/animate library to create animations you can do this:
import animate from "@okikio/animate"; // Do this if you installed it via the script tag: const { animate } = window.animate; (async () => { let [options] = await animate({ target: ".div", // Units are added automatically for transform CSS properties translateX: [0, 300], duration: 2000, // In milliseconds speed: 2, }); console.log("The Animation is done..."); })();
You can also play with a demo with playback controls:
Try out Motion Path:
Try different types of Motion by changing the Animation Options:
I also created a complex demo page with polyfills:
You can find the source code for this demo in the
animate.ts and
animate.pug files in the GitHub repo. And, yes, the demo uses Pug, and is a fairly complex setup. I highly suggest looking at the README as a primer for getting started.
The native initiative uses Gitpod, so if you want to play with the demo, I recommend clicking the “Open in Gitpod” link since the entire environment is already set up for you — there’s nothing to configure.
You can also check out some more examples in this CodePen collection I put together. For the most part, you can port your code from animejs to @okikio/animate with few-to-no issues.
I should probably mention that @okikio/animate supports both the
target and
targets keywords for settings animation targets. @okikio/animate will merge both list of targets into one list and use
Sets to remove any repeated targets. @okikio/animate supports functions as animation options, so you can use staggering similar to animejs. (Note: the order of arguments are different, read more in the “Animation Options & CSS Properties as Methods” section of the README file.)
Restrictions and limitationsRestrictions and limitations
@okikio/animate isn’t perfect; nothing really is, and seeing as the Web Animation API is a living standard constantly being improved, @okikio/animate itself still has lots of space to grow. That said, I am constantly trying to improve it and would love your input so please open a new issue, create a pull request or we can have a discussion over at the GitHub project.
The first limitation is that it doesn’t really have a built-in timeline. There are a few reasons for this:
- I ran out of time. I am still only a student and don’t have lots of time to develop all the projects I want to.
- I didn’t think a formal timeline was needed, as async/await programming was supported. Also, I added
timelineOffsetas an animation option, should anyone ever need to create something similar to the timeline in animejs.
- I wanted to make @okikio/animate as small as possible.
- With group effects and sequence effects coming soon, I thought it would be best to leave the package small until an actual need comes up. On that note, I highly suggest reading Daniel C. Wilson’s series on the WAAPI, particularly the fourth installment that covers group effects and sequence effects.
Another limitation of @okikio/animate is that it lacks support for custom easings, like spring, elastic, etc. But check out Jake Archibald’s proposal for an easing worklet. He discusses multiple standards that are currently in discussion. I prefer his proposal, as it’s the easiest to implement, not to mention the most elegant of the bunch. In the meanwhile, I’m taking inspiration from Kirill Vasiltsov article on Spring animations with WAAPI and I am planning to build something similar into the library.
The last limitation is that @okikio/animate only supports automatic units on transform functions e.g. This is no longer the case as of @okikio/[email protected], but there are still some limitations on CSS properties that support color. Check the GitHub release for more detail.
translateX,
translate,
scale,
skew, etc.
For example:
animate({ targets: [".div", document.querySelectorAll(".el")], // By default "px", will be applied translateX: 300, left: 500, margin: "56 70 8em 70%", // "deg" will be applied to rotate instead of px rotate: 120, // No units will be auto applied color: "rgb(25, 25, 25)", "text-shadow": "25px 5px 15px rgb(25, 25, 25)" });
Looking to the futureLooking to the future
Some future features, like ScrollTimeline, are right around the corner. I don’t think anyone actually knows when it will release but since the ScrollTimeline in Chrome Canary 92, I think it’s safe to say the chances of a release in the near future look pretty good.
I built the timeline animation option into @okikio/animate to future-proof it. Here’s an example:
Thanks to Bramus for the demo inspiration! Also, you may need the Canary version of Chrome or need to turn on Experimental Web Platform features in Chrome Flags to view this demo. It seems to work just fine on Firefox, though, so… 🤣.
If you want to read more on the ScrollTimeline, Bramus wrote an excellent article on it. I would also suggest reading the Google Developers article on Animation Worklets.
My hope is to make the library smaller. It’s currently ~5.79 KB which seems high, at least to me. Normally, I would use a bundlephobia embed but that has trouble bundling the project, so if you want to verify the size, I suggest using bundle.js.org because it actually bundles the code locally on your browser. I specifically built it for checking the bundle size of @okikio/animate, but note it’s not as accurate as bundlephobia.
PolyfillsPolyfills
One of the earlier demos shows polyfills in action. You are going to need
web-animations-next.min.js from web-animations-js to support timelines. Other modern features the
KeyframeEffect constructor is required.
The polyfill uses JavaScript to test if the
KeyframeEffect is supported and, if it isn’t, the polyfill loads and does its thing. Just avoid adding async/defer to the polyfill, or it will not work the way you expect. You’ll also want to polyfill
Map,
Set, and
Promise.
<html> <head> <!-- Async --> <script src="" async></script> <!-- NO Async/Defer --> <script src="./js/webanimation-polyfill.min.js"></script> </head> <body> <!-- Content --> </body> </html>
And if you’re building for ES6+, I highly recommend using esbuild for transpiling, bundling, and minifying. For ES5, I suggest using esbuild (with minify off), Typescript (with target of ES5), and terser; as of now, this is the fastest setup to transpile to ES5, it’s faster and more reliable than babel. See the Gulpfile from the demo for more details.
ConclusionConclusion
@okikio/animate is a wrapper around the Web Animation API (WAAPI) that allows you to use all the features you love from animejs and other animation libraries, in a small and concise package. So, what are your thoughts after reading about it? Is it something you think you’ll reach for when you need to craft complex animations? Or, even more important, is there something that would hold you back from using it? Leave a comment below or join the discussion on Github Discussions.
This article originally appeared on dev.to, it also appeared on hackernoon.com and my blog blog.okikio.dev.
Photo by Pankaj Patel on Unsplash.
How is this impacted by the lack of support for
KeyframeEffect.compositeon iOS and does it offer a workaround if so?
The lack of
KeyframeEffect.compositemay limit the type of composite animations you can create but shouldn’t affect any other part of
@okikio/animateas long as the browser in question supports
KeyframeEffect.updateTiming()and
KeyframeEffect.setKeyframes(). | https://css-tricks.com/how-i-used-the-waapi-to-build-an-animation-library/ | CC-MAIN-2022-33 | refinedweb | 2,210 | 53.31 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.