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 |
|---|---|---|---|---|---|
Hello.
I was trying to figure out why my combination of two piece of code I found online wasn’t working. To test this I decided to run them both at the same time.
I noticed though that it seems that my one call back is preventing the other from running. Once the second callback is run the first callback begins to work.
The thing is they have nothing to do with each other. I even made sure that no local variables were being shared as well as the order in which the callbacks appeared in the code.
The code is as follows (combination of and)
import dash_html_components as html import dash_core_components as dcc import dash import plotly import dash_table_experiments as dte from dash.dependencies import Input, Output, State import pandas as pd import numpy as np import json import datetime import operator import os import base64 import io df1 = pd.read_csv( '' 'c78bf172206ce24f77d6363a2d754b59/raw/' 'c353e8ef842413cae56ae3920b8fd78468aa4cb2/' 'usa-agricultural-exports-2011.csv') def generate_table(dataframe, max_rows=10): return html.Table( # Header [html.Tr([html.Th(col) for col in dataframe.columns])] + # Body [html.Tr([ html.Td(dataframe.iloc[i][col]) for col in dataframe.columns ]) for i in range(min(len(dataframe), max_rows))] ) def parse_contents(contents, filename): None return df app = dash.Dash() app.layout = html.Div(children=[ html.H5("Upload Files"), dcc.Upload( id='upload-data', children=html.Div([ 'Drag and Drop or ', html.A('Select Files') ]), multiple=False), html.Br(), html.H5("Updated Table"), html.Div(dte.DataTable(rows=[{}], id='table2')), html.H4(children='US Agriculture Exports (2011)'), html.Button( id='Make_Graph1', n_clicks = 0, children='Launch' ), html.Div( id = "BLARG" ), ]) @app.callback(Output('table2', 'rows'), [Input('upload-data', 'contents'), Input('upload-data', 'filename')]) def update_output(contents, filename): if contents is not None: df2 = parse_contents(contents, filename) if df2 is not None: return df2.to_dict('records') else: return [{}] else: return [{}] @app.callback(Output('BLARG', 'children'), [Input('Make_Graph1', 'n_clicks')]) def Make_Table(Click): if Click <1: return [{}] else: return generate_table(df1) if __name__ == '__main__': app.run_server(debug=True)
If the button is clicked then Make_Table launches correctly. If then a file is uploaded then update_output is generated correctly.
However if a file is uploaded then update_output fails to launch. If however one then runs Make_Table then update_output starts to work.
The two call backs share nothing as far as I can tell so I see no reason why there is a conflict.
I was wondering if this is a bug or if I’m missing something.
Any help or work arounds would be much appreciated. | https://community.plotly.com/t/unrelated-call-backs-preventing-other-call-backs-from-running/12726 | CC-MAIN-2020-45 | refinedweb | 422 | 61.22 |
Currently the definition of Greatest Common Divisor (GDC) can be formalized as well:
Let a, b and c nonzero integers, we say that c is a common divisor of a and b to c divides (write c | a) and c divides b (c | b). We call D (a, b) the set of all common divisors of a and b.
The code snippet below shows how to calculate the GDC two reported numbers:
import java.util. *;
public class ProgGCD {
public static void main (String [] args) {
Scanner scan = new Scanner (System.in);
System.out.print ("Calculate the Greatest Common Divisor (GCD)\n");
System.out.print ("Enter the first number :");
int First_No = scan.nextInt();
System.out.print ("Enter the second number :");
int Second_No = scan.nextInt();
System.out.println ("The GCD of " + First_No + " and " + Second_No + " and " + GDC (First_No, Second_No));
}
public static int GDC (int x, int y) {
int result;
while (y != 0) {
result = x% y;
x = y;
y = result;
}
return | http://ecomputernotes.com/java/control-structures-in-java/greatest-common-divisor | CC-MAIN-2020-16 | refinedweb | 156 | 63.8 |
post will show you the steps for creating your own fully customizable login page.
LightSwitch doesn’t have not have built-in support for customizing this UI. However, since LightSwitch is an ASP-NET based application you can use the features in ASP.NET to workaround this. What I’m going to demonstrate here is how to create an ASPX page that will authenticate the user when they open the app. Since you write the content of the ASPX page, you get to control exactly how it looks to the user. But I’ll make it easy for you by providing some sample markup that you can use and customize.
NOTE:
These instructions are for creating a custom login page for Web-based LightSwitch applications (meaning, the application is hosted within the browser). There isn’t a way to create a custom login page for a Desktop LightSwitch application. In addition, these instructions assume that you have Visual Studio Professional or higher installed in addition to LightSwitch. This isn’t necessarily required, but it makes the task of adding ASPX files to the project simpler; otherwise, you’d have to do this by hand which I won’t be describing in this post.
First, let’s start with a brand new LightSwitch project and open up the application properties window:
In the application properties window, select the Access Control tab and enable Forms authentication:
Select the Application Type tab and change the client type to Web:
Now switch Solution Explorer into File View in order to manage the physical files that make up a LightSwitch application:
Next, click the “Show All Files” toolbar button. This shows all the hidden files within the project.
This is what the resulting project looks like now:
Add a new ASPX page to the ServerGenerated project by selecting the ServerGenerated project and hit Ctrl+Shift+A. Then select “Web Form” from the Web node and change the filename to “Home.aspx”. Click the Add button.
Follow the same steps again to add another ASPX file but name this one “Login.aspx”. You should now have two ASPX files in your ServerGenerated project:
Open Login.aspx and paste over the existing markup with the following:
C#:
<%@ Page Title="Log In" Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="LightSwitchApplication>
VB:
<%@ Page
For more details on how to customize the Login control to suit your needs, see the following MSDN article: Customizing the Appearance of ASP.NET Login Controls.
For the Home.aspx page, you can leave the default markup code since this page will never be visible by the user. We’re only going to use it as a redirection mechanism.
NOTE:
This redirection logic is only needed to workaround an issue in LightSwitch V1 where it will remove from the web.config file at publish-time a configuration setting that will deny anonymous users access. If you have the ability to modify your web.config file after the app has been published, you can configure it to deny anonymous users by adding the following to the system.web section of the web.config file:<authorization> <deny users="?"/> </authorization>
If you end up doing this, the Home page described in this blog post would not be necessary within your site.
To setup the redirection logic, open up the code-behind for the Home page, Home.aspx.cs, and replace its contents with the following code:
C#:
using System; using System.Web.Security; namespace LightSwitchApplication { public partial class Home : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!this.User.Identity.IsAuthenticated) { FormsAuthentication.RedirectToLoginPage(); } else { this.Response.Redirect(FormsAuthentication.DefaultUrl); } } } }
VB:
Imports System.Web.Security Public Class Home Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles Me.Load If Not Me.User.Identity.IsAuthenticated Then FormsAuthentication.RedirectToLoginPage() Else Me.Response.Redirect(FormsAuthentication.DefaultUrl) End If End Sub
End Class
Next, we need to configure the default page for the site to use this new Home page. Open the web.config file contained in the ServerGenerated folder. It will have a section that looks like this:
<defaultDocument> <files> <clear /> <add value="default.htm" /> </files> </defaultDocument>
To configure the new default page, change “default.htm” to “Home.aspx”.
In addition, we need to configure default.htm to be the page that is redirected to after a successful login. To do this, find the forms element in the web.config file and add the bolded text:
<authentication mode="Forms"> <forms name="CustomLoginApp" defaultUrl="default.htm" /> </authentication>
The last step is to configure the main LightSwitch project to be aware of the new ASPX files that were added so that they will be published along with the app. To do this, unload the main LightSwitch project:
With the project unloaded, open the physical .LSPROJ file in the IDE:
Do a search for “_BuildFile” and append the following text within that section of the file:
<_BuildFile Include="ServerGenerated\Login.aspx"> <SubFolder> </SubFolder> <PublishType> </PublishType> </_BuildFile>
<_BuildFile Include="ServerGenerated\Home.aspx"> <SubFolder> </SubFolder> <PublishType> </PublishType> </_BuildFile>
Reload the LightSwitch project:
Your LightSwitch app is now configured to use your new custom Login page. When you publish your app and connect to it, you’ll be redirected to your login page. After successfully logging in, you’ll be redirected to the LightSwitch app.
You Rock!. I am at the Visual Studio Live Conference in Orlando right now, and this has come up multiple times.
Thanks very much for this! This is a much needed feature that you've made easy.
My only worry is what will happen when v2 is released and this breaks! Still, we'll wait until that happens eh?
Thanks again.
Will you be so kind to post this workaround to the Desktop Apps too, please?
@AlexFormoso:
As I mentioned, this ASP.NET-based solution is not possible with desktop apps. Although not a recommended approach, there is a way to modify the Silverlight controls of the built-in Login page at runtime. This approach is described in this thread: social.msdn.microsoft.com/…/6dde7955-6a18-41d8-a4fd-78610a37bdad. This is not a recommended approach because it relies on the internal implementation of how LightSwitch defines the Silverlight login page. It may change in the future which could potentially break this solution.
Thank you for sharing but if users want to reset their password??
@hatipoglu79:
To implement a password reset mechanism in your custom login page, ASP.NET provides a PasswordRecovery control. See msdn.microsoft.com/…/ms178335.aspx for more information.
Wow, thanks for sharing this!!!!!!!!!
Thanks Matt
This is functionallity that is asked many times on forum.
Best regards
Cool, just need this at the moment. Thanks a lot.
Hi,
Great post! But i have a question. When they are logged in they need to get a role. Something like read only account and an account that can edit data. Is this posible?
Thanks you for your response!
@Robin:
Assignments of users to roles can be managed via the built-in administration screens within the LightSwitch application. See the Roles and Users section of msdn.microsoft.com/…/ff851957.aspx.
I know that part of LightSwitch, but when the use login the application doesnt know my user. It says that it is a test user. What am i doing wrong?
This is my code for Login:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Xml;
using System.IO;
using System.Net;
namespace LightSwitchApplication
{
public partial class Login : System.Web.UI.Page
{
// Local specific CAS hostprivate const
string CASHOST = "login.hro.nl/…/";
// After the page has been loaded, this routine is called.protected void
protected void Page_Load(object sender, EventArgs e)
{
// Look for the "ticket=" after the "?" in the URL
string tkt = Request.QueryString["ticket"]; //[CAS:"ticket"];
// This page is the CAS service=, but discard any query string residue
string service = Request.Url.GetLeftPart(UriPartial.Path);
// First time through there is no ticket=, so redirect to CAS login
if (tkt == null || tkt.Length == 0)
{
string redir = CASHOST + "login?" + "service=" + service;
//string redir = CASHOST + "login?" + "service=" + service + "&rcl=63";
Response.Redirect(redir);
return;
}
// Second time (back from CAS) there is a ticket= to validate
string validateurl = CASHOST + "serviceValidate?" + "ticket=" + tkt + "&" + "service=" + service;
StreamReader Reader = new StreamReader(new WebClient().OpenRead(validateurl));
string resp = Reader.ReadToEnd();
// I like to have the text in memory for debugging rather than parsing the stream
// Some boilerplate to set up the parse.
NameTable nt = new NameTable();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);
XmlTextReader reader = new XmlTextReader(resp, XmlNodeType.Element, context);
string netid = null;
while (reader.Read())
{
if (reader.IsStartElement())
{
string tag = reader.LocalName;
if (tag == "user")
netid = reader.ReadString();
}
}
if (netid == null)
{
Label1.Text = "CAS returned to this application, but then refused to validate your identity.";
}
else
{
FormsAuthentication.RedirectFromLoginPage(netid, false);
// set netid in ASP.NET blocks
}
}
}
}
I need to know my user and give him a role.
Great post! Cheers!!!
@Robin:
I assume you are running your application from the IDE? During development, LightSwitch bypasses the normal user login and makes use of its own "Test User" account. You'll need to publish your application somewhere to actually see LightSwitch make use of your user account.
Really a great post, but is it also posible to change the AspNetProfileProvider property FullName?
I want change it too the name of the login person.
Cheers!
@Robin:
Sure, you can write code like the following:
ProfileBase profile = System.Web.Profile.ProfileBase.Create("username");
profile.SetPropertyValue("FullName", "Robin Lutteke");
profile.Save();
Hi!
Is this applicable to Windows Authentication? I mean, can you create a custom login page for LightSwitch when it is set to use Windows Authentication? Or is there a way to use Forms Authentication against Active Directory ie. domain login?
Thanks. | https://blogs.msdn.microsoft.com/mthalman/2011/12/08/creating-a-custom-login-page-for-a-lightswitch-application/ | CC-MAIN-2016-30 | refinedweb | 1,653 | 60.21 |
February 2012
PIP STS02465
Augered Cast-in-Place Piles Installation Specification
Process Industry Practices (PIP), Construction Industry Institute, The University of Texas
at Austin, 3925 West Braker Lane (R4500), Austin, Texas 78759. PIP Member Companies
and Subscribers may copy this Practice for their internal use. Changes
Users client. PIPs copyright notices must be clearly indicated and unequivocally
incorporated in documents where an Authorized User desires to provide any third party with
copies of the Practice.
PRINTING HISTORY
April 1999
Issued
February 2012 Complete Revision
Not printed with State funds
COMPLETE REVISION
February 2012
PIP STS02465
Augered Cast-in-Place Piles Installation Specification
Table of Contents
1. Introduction .................................2
1.1 Purpose ..............................................2
1.2 Scope .................................................2
2. References ..................................2
2.1 Industry Codes and Standards ..........2
2.2 Government Regulations and
Documents .........................................3
Data Forms
STS02465-D Augered Cast-in-Place Pile
Installation Record (U.S. Customary
Units)
STS02465-DM Augered Cast-in-Place Pile
Installation Record (Metric Units)
3. Definitions ...................................3
4. Requirements ..............................4
4.1 General ..............................................4
4.2 Meetings .............................................5
4.3 Design of ACIP Piles ..........................6
4.4 Submittals ..........................................7
4.5 Materials ...........................................10
4.6 Equipment ........................................12
4.7 Execution .........................................15
Page 1 of 21
1.
Introduction
1.1
Purpose
This Practice provides the constructor with requirements for the installation of augered
cast-in-place (ACIP) piles.
1.2
Scope
This Practice describes the requirements for furnishing and installing ACIP piles. Probe
piles and pile load tests are included and shall be executed in accordance with this
specification when required.
2.
References
Applicable parts of the following industry codes and standards and government regulations shall be
considered an integral part of this Practice. The edition in effect on the date of contract award shall be
used, except as otherwise noted. Short titles will be used herein where appropriate.
2.1
Page 2 of 21
PIP STS02465
Augered Cast-in-Place Piles Installation Guide
COMPLETE REVISION
February 2012
ASTM C942 - Standard Test Method for Compressive Strength of Grouts for
Preplaced-Aggregate Concrete in the Laboratory
ASTM D1143/D1143M - Standard Test Methods for Deep Foundations Under
Static Axial Compressive Load
ASTM D3689 - Standard Test Methods for Deep Foundations Under Static Axial
Tensile Load
ASTM D3966 - Standard Test Method for Piles under Lateral Loads
ASTM D4945 - Standard Test Method for High-Strain Dynamic Testing of Deep
Foundations
ASTM D5882 - Standard Test Method for Low Strain Impact Integrity Testing of
Deep Foundations
ASTM D6760 - Standard Test Method for Integrity Testing of Concrete Deep
Foundations by Ultrasonic Crosshole Testing
Deep Foundations Institute (DFI)
TM-ACIP-1 - Augered Cast-In-Place Piles Manual (Second Ed. 2003)
TM-ACIP-2 - Augered Cast-In-Place Piles Inspectors Guide (Second Ed. 2010)
2.2
3.
Definitions
constructor: The party responsible for supplying the materials, equipment, tools, supervision, and
labor for the installation of the ACIP piles in accordance with the contract documents. The term
constructor shall apply also to the constructors subcontractor(s) and vendor(s).
contract documents: Any and all documents, including codes, studies, design drawings,
specifications, sketches, practices, and data sheets, that the purchaser or engineer of record has
transmitted or otherwise communicated, either by incorporation or reference, and made part of
the legal contract agreement or purchase order between the purchaser and the constructor
engineer of record: Purchasers authorized representative with overall authority and
responsibility for the engineering design, quality, and performance of the civil works, structure,
foundations, materials, and appurtenances described in the contract documents. The engineer of
record shall be licensed as defined by the laws of the locality in which the work is to be
constructed, and be qualified to practice in the specialty discipline required for the work
described in the contract documents.
geotechnical engineer: The professional engineer responsible for performing the geotechnical
investigation and/or geotechnical consulting during foundation design, construction of civil
works, installation of foundations, or other services as required by the owner, purchaser or
engineer of record
Page 3 of 21
inspector: Third party inspector retained by the constructor, responsible for observation and
recording of material verification, pile installation, and other quality control documentation.
(This is not the qualified geotechnical representative.)
owner: The party who has authority through ownership, lease, or other legal agreement over the
site, facility, structure or project wherein the ACIP piles will be installed
professional engineer: An engineer, other than the engineer of record licensed as defined by the
laws of the locality in which the project is to be constructed and qualified to practice in the
specialty discipline required for the work described in the contract documents
purchaser: The party who awards the contract to the constructor. The purchaser may be the owner
or the owners authorized agent.
qualified geotechnical representative: The qualified geotechnical representative shall be a graduate
geotechnical engineer, graduate geologist, or geotechnical technician provided the technician has at
least ten years of relevant field exploration and logging experience. The qualified geotechnical
representative shall work under the supervision of the geotechnical engineer.
4.
Requirements
4.1
General
4.1.1
4.1.2
Constructor shall review the data from subsurface investigations. The purchaser
shall be provided data from any additional investigations performed by the
constructor.
4.1.3
4.1.4
4.1.5
4.1.6
Engineer of record shall be notified no less than three working days before
installation or testing of piles.
4.1.7
4.1.8
4.1.9
Page 4 of 21
PIP STS02465
Augered Cast-in-Place Piles Installation Guide
COMPLETE REVISION
February 2012
4.1.10 Constructor shall visit the site before equipment mobilization to identify
overhead and horizontal obstructions and to verify that pile installation
equipment can access pile locations at the site.
4.1.11 Piles shall be installed in accordance with published recommended practices as
approved by the geotechnical engineer, or in accordance with the procedure
established and proven by a successful pile load test as determined by the
geotechnical engineer.
4.2
Meetings
4.2.1
Pre-award Meeting
A pre-award meeting, attended by the constructor, purchaser, engineer of record,
geotechnical engineer, qualified geotechnical representative, and inspector, shall
be held to discuss topics such as the following:
a. Safety requirements including safety inspection of cranes to be used for pile
installation
b. Site entry procedures
c. Available subsurface information
d. Underground utility identification and location
e. Survey for elevation and location of piles
f. Grout submittal, delivery and placement requirements
g. Excavated materials disposal
h. Action required if potentially contaminated soil is encountered
i. Planning for integrity testing, load testing, and inspection
j. Test pile installation and procedures. Qualification and experience of the
operator(s) to be assigned on the job for installation of production piles
k. Project pile specification review
l. Grout pump calibration and computation of minimum required pump strokes
m. Procedures for drilling the piles
n. Procedures for grout placement
o. Procedures for re-drilling and re-grouting piles
p. Procedures for finishing pile tops to final grade (topping off or bailing grout
below ground surface)
q. Chain of communication for piles not meeting specification requirements
r. Responsibility for required reports
4.2.2
Pre-construction Meeting
4.2.2.1 Pre-construction meeting shall be held immediately before start of work.
This meeting shall be attended by the people assigned to the work who
are ultimately responsible for the actual field pile installation work.
These include the constructor, inspector, field superintendent, foremen,
Page 5 of 21
Page 6 of 21
PIP STS02465
Augered Cast-in-Place Piles Installation Guide
4.4
COMPLETE REVISION
February 2012
Submittals
4.4.1
Pre-construction Submittals
The following items shall be submitted to the engineer of record for approval.
Work shall not proceed without approval. Submittals are due at least fourteen
calendar days before mobilization begins:
a. Description of the pile drilling and pumping equipment to be used on the
project, including the hollow stem auger, drill bit, leads/torque arm, drive
box (horsepower, weight, and torque), hydraulic power unit, torque
converter, grout pump, and safety inspection report of crane(s) to be utilized
at site for pile installation
b. Description of anticipated production in linear feet (meter) of completed
piling per rig, per day
c. Proposed grout mix, admixtures, and descriptions of grout components.
Grout mix proportioning and compliance verification shall be in accordance
with ACI 301/ACI 301M.
d. Drawings indicating the arrangement of the pile static load test and all design
calculations, if applicable. A professional engineer shall seal the drawings
and calculations. Calibrations of load-cell and jack/jack manometer shall
also be included. Calibrations shall be current for the project under this
contract only and shall be performed immediately before equipment is
brought to the site.
e. Descriptions and calibrations of the dynamic loading equipment and
qualifications of the testing technicians, when applicable
f.
j.
m. Drawing and written description of teeth design and material, and picture of
the rock-cutting bit to be used if applicable
n. Descriptions of automated installation-monitoring equipment
Page 7 of 21
o. Descriptions of low strain pulse echo (LPSE) integrity testing equipment and
procedures and qualifications of testing technician if specified as a
responsibility of the constructor
4.4.2
Construction Submittals
4.4.2.1 Inspector shall prepare a pile installation record using the attached data
form PIP STS02465-D or PIP STS02465-DM (as applicable) for each
pile and provide to the qualified geotechnical representative for
immediate review. Inspector shall distribute one copy each to: the
constructor, the purchaser, the engineer of record, and the geotechnical
engineer within two working days of installation. The inspector shall
record the following information at a minimum:
a.
Pile number
b.
c.
Name of constructor
d.
e.
f.
g.
Grout supplier, grout truck number, grout ticket number, time grout
was batched, grout truck arrival time on-site, batch volume (Load)
h.
i.
j.
k.
l.
Grout cube /cylinder sets made by the inspector with time and
identification
m.
n.
o.
p.
Auger pitch (note actual pitch each time measured in field; average
the measured length between a minimum of six auger flights)
q.
r.
s.
t.
u.
v.
w.
Page 8 of 21
PIP STS02465
Augered Cast-in-Place Piles Installation Guide
COMPLETE REVISION
x.
y.
z.
Depth of pile
February 2012
aa. Pile tip elevation (subtract depth from ground surface elevation)
bb. Theoretical volume (calculate from auger diameter and depth of pile)
cc. Time grout pumping began
dd. Grout pump strokes for each 5-ft (1.5-m) increment of pile grout
[2-ft (0.6-m) increment if automated monitoring equipment is used]
ee. Grout factor per increment (calculate actual/theoretical volume)
(Convert pump strokes into quantity of grout placed for each 5-ft
(1.5-m) increment of pile versus theoretical quantity of grout [2-ft
(0.6-m) increment if automated monitoring equipment is used]
ff.
jj.
Grout return (grout head when the grout is first observed at the
ground surface)
kk. Overall grout factor (actual grout volume pumped into the pile
divided by theoretical grout volume; the grout factor shall not
include the grout required to fill the lines or auger, nor any excess
grout pumped at the ground surface.)
ll.
ss.
4.4.2.2 Grout compression test results shall be submitted to the purchaser within
five days of performing test. Engineer of record shall be notified immediately
if any test indicates that the grout is below the specified strength.
4.4.2.3 Constructor shall submit an electronic QA/QC spreadsheet that links the
pile installation records with cube strength values and other test results.
Page 9 of 21
4.5
Materials
All furnished materials and proprietary items shall be subject to engineer of records
approval and shall be installed in accordance with the contract documents.
4.5.1
Portland Cement
Portland cement shall be in accordance with ASTM C150/C150M with type of
cement as specified in the contract documents.
4.5.2
Mineral Admixtures
Mineral admixtures, if specified shall be in accordance with ASTM C618, Class C
or Class F as specified in the contract documents.
4.5.3
Chemical Admixtures
4.5.3.1 Chemical admixtures shall be in accordance with ASTM C494/C494M
and ACI 212.3R, and shall be approved by the engineer of record.
4.5.3.2 Air entraining admixtures shall not be used.
4.5.3.3 Chemical admixtures that contain chloride shall not be permitted.
Page 10 of 21
PIP STS02465
Augered Cast-in-Place Piles Installation Guide
4.5.4
COMPLETE REVISION
February 2012
Fluidifier
Fluidifier shall be in accordance with ASTM C937.
4.5.5
Water
Water shall be in accordance with ASTM C94/C94M.
4.5.6
Fine Aggregates
Fine aggregates shall be in accordance with ASTM C33/C33M.
4.5.7
Grout Mixes
4.5.7.1 Grout shall be in accordance with ASTM C94/C94M. The grout shall be
a mixture of portland cement, fine aggregates, mineral admixtures (if
specified), chemical admixtures, fluidifier, and water, proportioned and
mixed to produce a grout capable of being pumped.
4.5.7.2 Grout shall be capable of maintaining the solids in suspension.
4.5.7.3 Grout shall have a minimum 28-day compressive strength of 4,000 psi
(28 MPa).
4.5.7.4 Grout materials shall be accurately measured to meet design proportions.
The total water in the grout mix shall not exceed the design quantity in
the approved grout mix submittal.
4.5.7.5 Constructor shall submit to the purchaser a proposed procedure for the
addition of water or admixtures on site for approval by the engineer of record.
4.5.7.6 Grout shall be mixed at the site for a minimum of two minutes at
maximum revolution rate unless site-added admixtures require a longer
mixing time. The maximum holding time from the batch plant shall be
two hours, and the maximum temperature of the grout at time of
placement shall be 100F (32C).
4.5.7.7 Grout shall be protected from low temperatures in accordance with
ACI 306R and from high temperatures in accordance with ACI 305R.
4.5.7.8 Grout mix shall be assigned a mix number to be included on the grout
delivery tickets for identification purposes.
4.5.7.9 Testing
Page 11 of 21
days, two cubes on the same day the pile load test is conducted and
four cubes held in reserve.
d. Each set of six cubes made during production installation shall be
tested as follows: two cubes at seven days, two cubes at twenty-eight
days, and two cubes held in reserve.
e. Flow rate of grout shall be tested each time cubes are made to
measure workability/consistency. Time inconsistencies shall be
noted on the installation record. Flow cones shall be in accordance
with ASTM C939, except that the cone shall be modified to provide
a 3/4-in (20-mm) opening.
f. Grout flow rates shall be between ten and twenty-five seconds.
g. Flow cone shall be provided by the inspector.
h. The inspector shall inform the constructor if the grout does not meet
the time, temperature, and consistency requirements for placement.
It is the constructors responsibility to accept or reject the delivered
grout.
4.5.8
Reinforcing Bars
4.5.8.1 Reinforcing bars shall be in accordance with ASTM A615 /A615M
Grade 60 or ASTM A706/A706M Grade 60.
4.5.8.2 High-strength reinforcing bars shall be in accordance with
ASTM A722/A722M Grade 150.
4.5.8.3 Methods to facilitate proper centering of steel cages or tension reinforcing
installed in the piles shall be approved by the engineer of record.
4.5.8.4 Reinforcing cages shall be tied in a manner that the cage shall remain the
specified shape and all reinforcing elements shall maintain the specified
positions throughout installation of the cage. Ties shall be of compatible
materials.
4.5.8.5 Centralizer devices shall be spaced no more than 20 ft (6 m) apart on
vertical cages or bars and no more than 10 ft (3 m) apart on battered
cages or bars.
4.5.8.6 Field bar bends shall be limited to 90-degree bends and limited to #7 bars
(#20 metric bars) or less.
4.6
Equipment
4.6.1
Page 12 of 21
PIP STS02465
Augered Cast-in-Place Piles Installation Guide
COMPLETE REVISION
February 2012
4.6.1.4 Minimum specified grout ratio or volume per unit pile length
measurement shall be clearly displayed to guide the constructor and
purchaser during pile installation.
4.6.1.5 Monitoring equipment shall also record auger rotation and hydraulic
torque drive pressures.
4.6.1.6 Automated instrumentation and monitoring equipment shall be calibrated
to ensure recording data within +/-3% tolerance of the unit measured
whether volume, length, pressure or torque at the start of work and every
month thereafter.
4.6.1.7 Display device(s) shall be supplied for data monitoring by constructor
and purchaser during installation of each pile for depth increments not to
exceed 2 ft (0.6 m). Alternatively, the operator can provide an
immediate printout of the pile details for field evaluation to determine if
re-drilling is necessary.
4.6.1.8 Printed results shall be provided to the inspector and purchaser
immediately following completion of each pile. The electronic data shall
be furnished in spreadsheet, raw data, and in plot formats.
4.6.1.9 Automated instrumentation and monitoring equipment shall be provided
in accordance with the requirements of this specification for all pile
installations except those installed using limited access/low-overhead
equipment.
4.6.1.10 Measurements made by the automated measuring and recording
equipment shall include as a minimum:
a. Auger rotation vs. depth for every 2-ft (0.6-m) increment, or less, of
pile advancement during the drilling process, and during placement
of grout or concrete (if auger is rotated during this placement)
b. Volume of grout or concrete placed versus depth of outlet orifice for
every 2-ft (0.6-m) increment, or less, of pile placed
c. Average maximum and minimum pump stroke pressures at ground
level for every 2-ft (0.6-m) increment, or less, of pile placed
d. Average maximum and minimum pump stroke pressure at or near
the auger head for every 2-ft (0.6-m) increment, or less, of pile
placed, if directed by the engineer of record
e. Additionally, the engineer of record may also specify that the torque
and crowd force (downward thrust on auger) measurements be
made at every 2-ft (0.6-m) increment, or less, of pile advancement
during the drilling process.
4.6.2
Page 13 of 21
Augering Equipment
4.6.3.1 Augers shall be continuous flight, hollow stem with an opening at the
bottom of the auger head below the part of the head containing the teeth.
4.6.3.2 Auger flighting shall be continuous without gaps or breaks and shall be
uniform in diameter within a tolerance of 3% of that specified in the
contract documents.
4.6.3.3 Pitch of the auger flighting shall not exceed 9 in (225 mm).
4.6.3.4 Intermediate stabilizing guide(s) shall be provided for augers longer than
40 ft (12 m).
4.6.3.5 For hanging lead rigs, the piling leads shall be prevented from rotating by
a stabilizing arm or by firmly placing the bottom of the leads into the
ground or by other means approved by the engineer of record.
4.6.3.6 Leads or mast shall be clearly marked on both sides at 1-ft (0.3-m)
intervals to facilitate measurement of auger penetration. The marks on
the leads shall be labeled with numerals every 5 ft (1.5 m) such that the
inspector can easily determine the final drill depth and the grout return
depth. The constructor shall position the leads such that the inspector
can clearly see the marks while standing on the grout line near the grout
pump.
4.6.3.7 Rig shall be equipped so that the auger withdrawal can be accomplished
at a slow, continuous rate.
4.6.3.8 Equipment furnished shall be capable of installing piles at least 10 ft
(3 m) longer than that required for specified length piles.
4.6.3.9 If logs of soil borings indicate that timber logs, cobbles, or other minor
obstructions will be encountered before reaching required pile depth,
then a rock-cutting bit shall be supplied and used.
4.6.4
Pumping Equipment
4.6.4.1 Pumping equipment used in pumping and handling the grout shall be
adequate to meet the requirements of this Practice and the contract
documents and shall allow placement of a homogeneous grout of the
required consistency through the auger to the depth required.
4.6.4.2 Pump hoppers shall be provided with a 3/4-in (20-mm) screen to exclude
oversize lumps from creating a blockage.
4.6.4.3 Positive displacement pump capable of at least 350-psi (2,400-kPa)
displacement pressure at the pump shall be provided.
Page 14 of 21
PIP STS02465
Augered Cast-in-Place Piles Installation Guide
COMPLETE REVISION
February 2012
4.6.4.4 Pump pressure gauge shall be provided and in clear view of the operator.
4.6.4.5 Pump shall be calibrated on site prior to installation of the first pile and
after modifications are made to pumps or other equipment or after a
significant change in grout return depth. Onsite pump calibration shall
be completed by recording the number of pump strokes required to fill at
least 75% of a 55-gallon (200-liter) barrel or other accurately known
volume container of similar size with grout. The container shall be
measured and the actual grout volume shall be computed when the
container is not completely filled at an even number of grout pump
strokes. The inspector shall observe the calibration and provide
documentation to the engineer of record.
4.6.4.6 Digital or mechanical grout pump stroke counter shall be provided. The
constructor shall have at least one spare pump counter available onsite and
shall maintain the pump stroke counter in operating condition at all times.
4.6.5
4.7
Execution
4.7.1
General
4.7.1.1 Piling materials, labor, tools, supervision, equipment, and supplies
necessary for installing ACIP piles shall be furnished in accordance with
the contract documents and this Practice.
4.7.1.2 Construction shall be in accordance with federal standards and
instructions of the Occupational Safety and Health Administration
(OSHA) and with any additional requirements of state or local agencies
that have jurisdiction where piles are to be installed.
4.7.1.3 Sufficient quantity of grout to complete a pile shall be available at the site
or in transit before pile installation begins. No open holes are permitted.
4.7.2
Construction Tolerances
4.7.2.1 Pile centers shall be located within a tolerance of +/- 3 in (75 mm) of the
locations shown in the contract documents.
4.7.2.2 Vertical piles shall be plumb within 2%.
4.7.2.3 Battered piles shall be installed to within 4% of the specified batter.
4.7.2.4 Reinforcing cages or center bars shall have a minimum of 3 in (75 mm)
clearance from the wall of the augered hole.
Page 15 of 21
4.7.3
Adjacent Piles
4.7.3.1 Piles shall not be placed within six pile diameters, center to center, of
adjacent piles containing grout that has set for less than twelve hours.
4.7.3.2 The approximate time of initial set shall be determined by the inspector
using a simple cup test in the field. . The inspector shall fill a number
of Styrofoam drink cups with grout and place them in a shaded and cool
place. At intervals, the inspector shall turn a single cup over and note the
time and behavior of the grout. At the time the grout comes out as a cupshaped block and only slightly plastic, that is the time of initial set. Initial
set is the minimum time between which adjacent piles can be placed.
4.7.4
Installation Procedures
4.7.4.1 Pile length, drilling criteria, and installation procedures of production
piles may be modified by the engineer of record from information
obtained during the installation of the probe piles, reaction piles, test
piles, and the pile load tests.
4.7.4.2 Production piles shall be installed with the same equipment and identical
procedures used for installation of probe piles and test piles.
4.7.4.3 Drilling shall advance at a continuous rate appropriate for the soil
conditions until the required depth or refusal is reached.
4.7.4.4 Oversight shall be provided by an experienced inspector to prevent excessive
rotation of the auger, which can cause loss of ground in running sands.
4.7.4.5 If refusal is reached before the required depth, the engineer of record
shall be notified immediately.
4.7.4.6 Auger refusal is defined as a rate of auger penetration of less than 1 ft
(0.3 m) per minute of drilling with maximum torque and weight applied
to the auger using equipment approved by the engineer of record.
4.7.4.7 Plug shall be provided in the bottom of the auger during drilling to
prevent entry of soil or water into the hollow stem of the auger.
4.7.4.8 When drilling with pressurized air flow through the hollow stem a plug is
unnecessary. If the auger tip plugs with soil when drilling with air
prevents the placement of grout, the auger shall withdrawn from the hole
to unplug the auger tip and the augered hole is temporarily left open. The
auger is then re-drilled to the final pile tip elevation and the pile is
grouted during auger withdrawal. Leaving the excavated pile shaft open
and then re-drilling, the auger tends to over excavate the soil. Pile
constructor shall compensate for this over excavation by increasing the
number of grout strokes (volume of grout) pumped over each 5-ft
(1.5-m) interval. Grout return depth shall be very closely monitored in
this instance.
4.7.4.9 When the auger reaches the specified depth, the auger may be raised 6 to
12 in (150 to 300 mm), and grout pumping shall begin.
4.7.4.10 After the grout pressure builds up as calculated by the required volume to
fill the pump line, auger tube and provide a minimum of 5 ft (1.5m) of
grout above the auger tip, the auger shall be re-drilled to the previously
established tip elevation before auger withdrawal begins.
Page 16 of 21
PIP STS02465
Augered Cast-in-Place Piles Installation Guide
COMPLETE REVISION
February 2012
Page 17 of 21
4.7.4.26 Grout subsidence shall be handled by topping off the piles with
additional grout provided the pile grout has not achieved initial set.
4.7.4.27 Grout subsidence greater than 1 ft (0.3 m) shall be avoided by increasing the
distance between the installations of adjacent piles, or alternating pile locations
used and/or the grout allowed to set for a longer time.
4.7.4.28 Additional grout shall only be placed prior to initial set of grout in the
pile to avoid formation of a cold joint at the pile top.
4.7.4.29 Grout mix design, delivery ticket, grout density tests and installation notes
shall be reviewed to determine if there are problems with the grout.
4.7.5
Spoils Handling
4.7.5.1 Spoils including excess grout and soil returned to the surface by the
augers shall be kept clear of the pile location by prompt removal.
4.7.5.2 Spoil shall be minimized by controlling speed of auger withdrawal and
rate and volume of grout pumped during auger withdrawal.
4.7.5.3 Constructor shall remove and dispose of spoils as directed by the
purchaser or the engineer of record.
4.7.5.4 Constructor shall comply with any restrictions on the disposal, and
transport spoils to the disposal area provided.
4.7.5.5 Constructor shall promptly inform the geotechnical representative,
engineer of record, and purchaser, if contaminated soil is encountered.
4.7.6
Obstructions
4.7.6.1 If obstructions causing auger refusal are encountered above the desired
tip elevation, the pile shall be completed to the refusal depth in
accordance with the contract documents.
4.7.6.2 Pile installation records shall be immediately sent to the geotechnical
engineer for evaluation.
4.7.6.3 Additional adjacent piles shall be installed as directed by the
geotechnical engineer.
4.7.7
Cutting Off
4.7.7.1 Piles shall be cut off by removing fresh grout from the top of the pile or
by cutting off hardened grout down to the final cut-off point.
4.7.7.2 Adding grout to raise the pile cut-off elevation after the pile has reached
its initial set shall not be permitted.
4.7.7.3 Sleeves or casings shall be placed around the pile top if the pile cut-off
elevation is above the surrounding ground surface elevation.
4.7.7.4 Reinforcing steel cages or central bar shall be supported to prevent
settling below the planned elevation.
4.7.8
Page 18 of 21
PIP STS02465
Augered Cast-in-Place Piles Installation Guide
COMPLETE REVISION
February 2012
5.
Quality Requirements
5.1
Inspection
5.1.1
Constructors inspector shall prepare the pile installation record required in Section
4.4.2 above and detailed in data form PIP STS02465-D or PIP STS02465-DM (as
applicable) for all piles installed.
Page 19 of 21
5.2
5.3
5.1.2
During ACIP pile installation, inspector shall be alert for any problems which can
reduce the load carrying capacity of an ACIP pile and note on the pile installation
record.
5.1.3
Inspector shall conduct grout tests described above and note on the pile installation
record.
5.1.4
5.1.5
Inspector shall observe that drilling advances at a continuous rate appropriate for the
soil conditions until the required depth or refusal is reached. If refusal is reached
before the required depth, the engineer of record should be notified immediately.
Auger refusal is defined as a rate of auger penetration of less than 1 ft (0.3 m) per
minute of drilling with maximum torque and weight applied to the auger.
5.1.6
Inspector should verify that all items on the inspection sheet shown in data form
PIP STS02465-D or PIP STS02465-DM (as applicable), or similar form are
completed in detail for each ACIP pile.
Piles shall be tested by either low strain impact integrity testing as specified in
ASTM D5882 or by single or cross-hole logging as specified in ASTM D6760 or
by both, as specified in the contract documents.
5.2.2
Constructor shall grind two or more smooth flat spots on top of each ACIP pile
selected for low strain testing as designated by the qualified geotechnical
representative.
5.2.3
Constructor shall provide and install tubes suitable for single or cross-hole logging
as directed by the engineer of record. Tubes shall be filled with clean water
immediately after placement and kept full until after completion of testing. Tube
may also be used for pile toe tell-tale access during load test.
5.2.4
All probe, test and reaction piles shall be tested using one of the integrity
verification methods listed above.
5.2.5
Constructor shall provide access and assistance to the testing agency technician
conducting the integrity testing.
Test piles shall be installed at the locations shown in the contract documents.
5.3.2
5.3.3
All materials and equipment required for performing and monitoring the static or
dynamic load test in accordance with the appropriate specification shall be provided.
5.3.4
Test and reaction piles shall be installed, and the load tests shall be performed,
only in the presence of the qualified geotechnical representative.
Page 20 of 21
PIP STS02465
Augered Cast-in-Place Piles Installation Guide
COMPLETE REVISION
February 2012
5.3.5
Compression test piles and tension test piles shall be equipped with a telltale or strain
gauges approved by the geotechnical engineer or as shown in the contract documents.
5.3.6
A load cell and jack system designed for use in field conditions shall be provided.
Jack and pressure measurement device shall be calibrated together as a system.
5.3.7
The pressure measuring system measuring the jack pressure and load cell shall
have a minimum range of 300% of the specified pile design capacity.
5.3.8
A single jack shall be used to apply the required load unless the engineer of
record authorizes use of a pair of jacks.
5.3.9
5.3.10 Suitable enclosure of the test arrangement shall be provided to ensure complete
weather protection for reference beams and for personnel conducting the test.
Necessary power source, lights, and heating shall be provided.
5.3.11 Load testing shall begin after grout has achieved its specified strength as
determined by the grout cube tests, unless a longer time is specified to allow soil
set-up on the completed pile.
5.3.12 Compression and Tension tests shall be performed in accordance with specified
in ASTM D1143/D1143M and ASTM D3689 using the Quick Load Test
Method, with the following modifications:
1. Test load shall be to the lesser of three times design load or failure
2. Each load increment shall be 10% to 15% of design load
3. Each load increment shall be held for ten minutes
4. Loading shall be continuous without intermediate unload/reload cycle
5. Unloading increments shall be a minimum of four approximately equal steps
5.3.13 Dynamic load testing procedures must be submitted by the constructor to the
purchaser for review and approval by the engineer of record. The engineer of
record will determine the ratio of dynamic tests to conventional compression or
tension tests.
Page 21 of 21
ASSOC. PIP
DATA SHEET
STS02465
STS02465-D
PAGE 1 OF 1
FEBRUARY 2012
PILE NO.:
MEETS SPEC.?
PROJECT:
DATE:
AREA:
CONTRACTOR:
INSPECTOR:
RIG:
WEATHER:
OPERATOR:
GROUT SUPPLIER:
____________
TICKET NO.
BATCH TIME
TRUCK NO.
ARRIVAL
TIME
LOAD (YD3)
FLUIDIFIER
UNITS:
_______
PILE DATA
RE-GROUT
TEMP (DEG)
DEPTH (FT)
AUGER
ROTATIONS
START:
FINISH:
GROUT CUBE/CYLINDERS
FLOWCONE
(SEC)
TIME MADE
SET NO.
RE-GROUTING SUMMARY
AUGERING (TIME)
TIME
SAMPLED
INSTALLATION SUMMARY
INITIAL
INSTALLATIO
N
GROUT SAMPLING/TESTING
MIX NO.:_______________
WATER
ADDED ON
SITE (GAL)
DEPTH (FT)
ROTATIONS
INITIAL:
INITIAL:
SPILL:
SPILL:
NET:
NET:
PILE:
TIME:
TIME:
PUMP PRIMED?
VOLUME (FT3/FT):
PUMP CALIBRATION:
AUGER ID:
NO.
PILE:
Weather Protection?
Steel Placement Problem?
Other Problems?
FT3/STROKE
Y
Y
/
/
N
N
REVISION DESCRIPTION
STROKES/5 FT (100%)
STROKES/5 FT (130%)
BY
APVD.
ASSOC. PIP
DATA SHEET
STS02465
STS02465-DM
PAGE 1 OF 1
(SI UNITS)
FEBRUARY 2012
PILE NO.:
MEETS SPEC.?
PROJECT:
DATE:
AREA:
CONTRACTOR:
INSPECTOR:
RIG:
WEATHER:
OPERATOR:
GROUT SUPPLIER:
____________
TICKET NO.
BATCH TIME
TRUCK NO.
ARRIVAL
TIME
LOAD (M3)
FLUIDIFIER
UNITS:
_______
PILE DATA
RE-GROUT
TEMP (DEG)
DEPTH (M)
AUGER
ROTATIONS
START:
FINISH:
GROUT CUBE/CYLINDERS
FLOWCONE
(SEC)
TIME MADE
SET NO.
RE-GROUTING SUMMARY
AUGERING (TIME)
TIME
SAMPLED
INSTALLATION SUMMARY
INITIAL
INSTALLATIO
N
GROUT SAMPLING/TESTING
MIX NO.:_______________
WATER
ADDED ON
SITE (GAL)
DEPTH (M)
ROTATIONS
INITIAL:
INITIAL:
SPILL:
SPILL:
NET:
NET:
PILE:
PILE:
TIME:
TIME:
WEATHER PROTECTION?
PUMP PRIMED?
OTHER PROBLEMS?
VOLUME (M3/M):
PUMP CALIBRATION:
AUGER ID:
NO.
M3/STROKE
REVISION DESCRIPTION
STROKES/1.5 M (100%)
STROKES/1.5 M (130%)
BY
APVD. | https://www.scribd.com/document/268816330/Sample-Sts02465 | CC-MAIN-2019-35 | refinedweb | 5,984 | 53.71 |
Things to Love About Ducktype
2019-05-06
I spent a lot of time making Ducktype into a lightweight syntax that I would really enjoy using. I had a list of design goals, and I feel like I hit them pretty well. In this post, I want to outline some of the things I hope you’ll love about the syntax.
1. Ducktype has a spec
I know not everybody nerds out over reading a spec the way I do. But whether or not you like reading them, specs are important for setting expectations and ensuring interoperable implementations. Probably my biggest gripe with Markdown is that there are just so many different flavors. Couple that with the multiple wiki flavors I regularly deal with, and my days become a game of guess-and-check.
Even in languages that haven’t seen flavor proliferation, you can still run into issues with new versions of the language. In a sense, every version of a parser that adds features creates a new flavor. Without a way to specify the version or do any sort of introspection or conditionals, you can run into situations where what you type is silently formatted very differently on different systems.
In Ducktype, you can declare the language version and any extensions (more on those later) right at the top of the file.
@ducktype/1.0 = Header This is a paragraph.
2. Ducktype keeps semantics
I’ve been a strong proponent of semantic markup for a long time, since I started working with LaTeX over 20 years ago. Presentational markup has short-term gains in ease-of-use, but the long-term benefits of semantic markup are clear. Not only can you more easily adapt presentation over time, but you can do a lot with semantic markup other than display it. Semantic markup is real data.
Different lightweight languages support semantic markup to different degrees. Markdown is entirely presentational, and if you want to do anything even remotely sophisticated, you have to break out to HTML+CSS. AsciiDoc and reStructuredText both give you some semantic markup at the block level, and give you the tools to create inline semantic markup, but out of the box they still encourage doing semantic-free bold, italic, and monospace.
My goal was to completely capture the semantics of Mallard with less markup, not to just create yet another syntax. Ducktype does that. What I found along the way is that it can fairly nicely capture the semantics of other formats like DocBook too, but that’s a story for another day.
Ducktype uses a square bracket syntax to introduce semantic block elements, inspired by the group syntax in key files. So if you want a note, you type:
[note] This text is an implicit paragraph in the note.
If you want a plain old bullet list, you type it just like in any other lightweight syntax:
* First item * Second item * Third item
But if you want a semantic steps list, you add the block declaration:
[steps] * First step * Second step * Third step
Ducktype keeps the semantics in inline markup too. Rather than try to introduce special characters for each semantic inline element, Ducktype just lets you use the element name, but with a syntax that’s much less verbose than XML. For example:
Click $gui(File). Call the $code(frobnicate) function. Name the file $file(index.duck).
Both AsciiDoc and reStructuredText let you do something similar, although sometimes you have to cook up the elements yourself. With Ducktype, you just automatically get everything Mallard can do. You can even include attributes:
Press the $key[xref=superkey](Super) key. Call the $code[style=function](frobnicate) function.
3. Ducktype keeps metadata
In designing Ducktype, it was absolutely critical that we have a consistent way to provide all metadata. Not only is metadata important for the maintenance of large document sets, but linking metadata is how documents get structure in Mallard. Without metadata, you can’t really write more than a single page.
You can do very good page-level metadata in both AsciiDoc and reStructuredText, but for Mallard we need to do metadata at the section and even block levels as well. Markdown, once again, is the poor format here with no support for any metadata at all. Some tools support a YAML header in Markdown, which would be pretty great if it were any sort of standard.
Ducktype uses a single, consistent syntax for metadata, always referencing the element name, and coming after the page header, section header, or block declaration that it’s providing info for.
= My First Topic @link[type=guide xref=index] @desc This is the first topic page I ever wrote. == My First Section @keywords first section, initial section Do you like my first topic page with a section?
We can even do this with block elements:
[listing] @credit @name Shaun McCance . A code listing by Shaun [code] here_is_some_code()
There’s a lot going on in that little example, from nesting to shorthand block titles. The important part is that we can provide metadata for the code listing.
(Side note: I thought a lot about a shorthand for credits, and I have ideas on an extension to provide one. But in the end, I decided that the core syntax should have less magic. Explicit is better than implicit.)
4. Ducktype allows nesting
I do quite a bit of semi-manual format conversion fairly frequently. It’s not something I enjoy, and it’s not the best use of my time, but it just keep having to be done, and I’m kind of good at it. If you do that a lot, you’ll often run into cases where something just can’t be represented in another format, and that usually comes down to nesting. Can you put lists inside table cells? Can you put tables inside list items? Can lists nest? Can list items have multiple paragraphs?
Both reStructuredText and (shockingly) most flavors of Markdown allow some amount of nesting using indentation. This sometimes breaks down when tables or code blocks are involved, but it’s not terrible. This is the one place where AsciiDoc is my least favorite. In fact, this is my single least favorite thing about AsciiDoc. It uses a plus on its own line to indicate a continuation. It’s hard to visualize, and it has severely limited functionality.
Ducktype very explicitly allows nesting with indentation, whether you’re nesting lists, tables, code blocks, notes, or anything else. It allows you to skip some indentation in some common cases, but you can always add indentation to stay in a block. Ducktype specifies the exact nesting behavior.
[note style=important] This is very important note about these three things: * The first thing is hard to explain. It takes two paragraphs. * The second thing can really be broken in two: * First subthing * Second subthing * The third thing involves some code: [code] here_is_some_code()
You can use any number of spaces you like. I prefer two, in part because it fits in with the shorthand syntax for things like lists. Using indentation and block declarations, there is absolutely no limit on what or how deeply you can nest.
5. Ducktype tables are sane
I have never met a lightweight table syntax I liked. Trying to represent real tables with some sort of pseudo-ascii-art works ok for very simple tables, but it falls apart real fast with anything remotely non-trivial. Add to this the extra syntax required for for all the non-trivial stuff, and a substantial portion of your parser is devoted to tables. As a user, I have a hard time keeping all those workarounds in my head.
As I said above, the ability to nest things was very important, so most of these tables syntaxes were just a non-starter. How do you add extra blocks in a table cell when the whole table row is expected to fit on one line? In the end, I decided not to have a table syntax. Or more accurately, to treat tables as a sort of list.
Without any special treatment, tables, rows, and columns can already be written in Ducktype using the block declarations you’ve already seen:
[table] [tr] [td] One [td] Two [tr] [td] Three [td] Four
There’s no magic happening here. This is just standard block nesting. But it’s pretty verbose, not as verbose as XML, but still. Can’t we make it a bit easier, like we do for lists? Well yes, we make it easier exactly like we do for lists.
[table] [tr] * One * Two [tr] * Three * Four
There are a few things going on here. Most importantly, the asterisk is shorthand for a table cell, not a list item. What that shorthand does depends on context. But also, we’ve removed quite a lot of indentation. Earlier I wrote that there are some special rules that allow you to trim indentation in certain common cases. This is one of them.
Using a vertical table syntax means that you can do the same kind of nesting you can do with other elements. Here’s a list in a table cell:
[table] [tr] * Here's a list: * First * Second * Another table cell
Ducktype isn’t the first format to allow a vertical table syntax. MediaWiki allows tables to be written vertically, and it works really well. But Ducktype is the only one to my knowledge not to introduce any new syntactical constructs at all. I have a hard time keeping all those dots and dashes in my head. Using a single, consistent syntax makes it easier to remember, and it reduces the number of special rules you need.
6. Ducktype supports extensions
I’ve mentioned extensions a couple of times already in this post, but I haven’t elaborated on them. In addition to being able to use Mallard extensions (which you can do without any extra syntax), I wanted a way to add and experiment with syntax without shoving everything in the core. And, importantly, I wanted pages to have to declare what extensions they use, so we don’t have a guess-and-check mess of incompatible flavors. I live in a world where files are frequently cherry-picked and pushed through different tool chains. Being explicit is important to me.
So in Ducktype, you declare your extensions at the top, just like you do with the version of Ducktype you’re using:
@ducktype/1.0 if/experimental = Page with Experimental Extension
What kinds of things can an extension do? Well, according to the spec, extensions can do literally anything. Realistically, what extensions can do depends on the extension points in the implementation. The reference implementation has two rough classes of extensions. There are the methods in the ParserExtension class, which let you plug in at the line level to affect how things are parsed. And there’s the NodeFactory, which lets you affect how parsed things are interpreted.
All of the ParserExtension methods are implemented and pretty well commented in the _test extension. One interesting use of this is the experimental csv extension. Remember how tables are always written vertically with a list-like syntax. That’s very powerful, but sometimes you really do just want something super simple. The csv extension lets you do simple comma-separated tables, like this:
@ducktype/1.0 csv/experimental = CSV Table Example [csv:table] one,two,three four,five,six seven,eight,nine
That’s in about 40 lines of extension code. Another example of line parser extensions is a special syntax for conditionals, which I blogged about before.
The NodeFactory extension point, on the other hand, lets you control what the various bits of special syntax do. If you want to want to use Ducktype to write DocBook, you would use DocBook element names in explicit block declarations and inline notation, but what about the elements that get implicitly created for paragraphs, headers, list items, etc? That’s what NodeFactory does.
Et cetera
That’s six things to love about Ducktype. I’ve been really happy with Mallard’s unique approach to structuring docs. I hope Ducktype can make the power of Mallard available without all the extra typing that comes along with XML. If you want to learn more, get in touch.
Ducktype 1.0
2019-04-13.
It took a long time to reach 1.0, because I take compatibility and correctness very seriously. Syntax is API. I work with multiple documentation formats on an almost daily basis. It is frustrating to constantly run into language quirks, especially quirks that vary between implementations. I realize quirks tend to accumulate over time, but I think we’ve prevented a lot of them by writing an actual specification, developing a regression test suite, and focusing on the cohesiveness of the language.
I’m really happy with how it’s turned out so far. I hope you enjoy it too.
What’s New in Mallard 1.1, Part 3
2019-02-04
We’ve just released Mallard 1.1. Let’s take a look at what’s new. All of these features are already supported in tools like Yelp and Pintail.
This is part 3 in a 3-part series. Read part 1 and part 2.
Keywords
MEP-0014: Informational keywords element
One of the most visible additions in Mallard 1.1 is the introduction of the keywords element. If you look through a lot of real-world documents, you’ll find some that stuff synonyms into the desc element just to match things that users search for. This is not ideal.
In Mallard 1.1, we’ve introduced the keywords element to aid search systems built into tools like Yelp and Pintail. We decided to keep the element simple, using just a comma-separated list of terms instead of any nested keyword elements.
External info links
MEP-0007: External Info Links
Mallard features a number of types of automatic links, like seealso links. These links tend to automatically link in both directions, hence why we call them automatic links. The exact way they automatically link back depends on the link type. They all use informational link elements with an xref attribute, and the link text for these links is taken from informational elements like title and desc of the target node.
Since automatic links use the xref attribute, they were only able to link to pages within the same document, not to anything on the web. This makes some sense. After all, we can’t very well make random web pages automatically link back to our page. But sometimes you really do just want to have a seealso link to an external web page, even if it can’t automatically link back.
In Mallard 1.1, you can use the href attribute on informational links. Exactly how this works depends on the link type, but in general for things like seealso links, the link will appear in the list with your internal links. Because we can’t reliably fetch external resources for the link text every time we build a document, the informational link element can now have a title and desc element to specify the title and desc of the target.
Inline highlights
MEP-0009: Inline Highlight Element
Another highly visible change is the new hi element. This element can be used to highlight text that you’ve added or changed when progressively building up code examples. You can see it in action in the Mallard Ten Minute Tour.
In fact, we’ve been using this element (in the experimental namespace) in the Ten Minute Tour and other places since before Mallard 1.0 was even released. It was (I think) the first thing we added to the experimental namespace, and certainly the longest element in continual use without being in an actual spec. I wasn’t sure back then if we really wanted to add it, because it was unlike any inline element in any other semantic format. Years and years of usage have proven it’s worth having.
You can also use the ins and del style hints when including a diff in a Mallard page. These will do what you expect: green background, and red background with a strikethrough, respectively. Also, the yelp-xsl stylesheets let you use any of red, orange, yellow, green, blue, or purple as style hints to set the background color. Have fun.
Linkable sequences
Mallard features ubiquitous linking, meaning that any of the three linking attribute can be used on any inline element, so you don’t have to use two separate element to make a function name be both code and a link. Well, almost any inline element. In Mallard 1.0, you couldn’t put linking attributes on the guiseq and keyseq elements. I have completely forgotten whatever reason I might have had for doing that, and multiple people have since convinced me that was a mistake. Mallard 1.1 fixes this. You can now do ubiquitous linking on guiseq and keyseq.
Speaking of guiseq and keyseq, we’re considering creating a shorthand syntax for them so you can easily write simple GUI paths and key sequences without nested gui and key elements. Comment on the issue to let us know your thoughts.
And more
That’s it for part 3 of 3. If you haven’t already, read part 1 and part 2. 2
2019-02-02
We’ve just released Mallard 1.1. Let’s take a look at what’s new. All of these features are already supported in tools like Yelp and Pintail.
This is part 2 in a 3-part series. Read part 1.
Table header cells
MEP-0012: Table Header Cells
Mallard mostly follows the HTML table model, with some simplifications of how things are styled. One element that was notably absent from Mallard tables, however, was the th element. The th element allows you to mark a cell as being a header for a row or column, even if it’s not in a thead element (as row headers wouldn’t be).
This was a pretty obvious and easy addition. I was so confident Mallard 1.1 would get a th element that I added a Ducktype shorthand for it well before Mallard 1.1 was released.
Custom roles for links
MEP-0003: The role Attribute on the links Element
This one’s pretty exciting, though a bit advanced. In Mallard, links can have roles which affect things like link text. These work with the multiple informational titles you can provide for a page or section. So, for example, if your language needs to do declensions for different parts of speech, you could write your links like this:
<link role="subject" xref="useful"/> is really useful. For useful info, check out <link role="object" xref="useful"/>.
Then in useful.page, you would have something like this:
<info> <title type="link" role="subject">Subject Title</title> <title type="link" role="object">Object Title</title> </info> <title>Normal Title</title>
Mallard will pick up the right title. More often, however, you don’t write your links inline, but instead you do automatic linking with informational links and possibly the links element. What happens then?
In Mallard 1.0, different types of automatic links have implicit roles. So the topic links on a guide page will automatically use the "topic" role to select link text from titles, for example. There are implicit roles for topic, guide, seealso, and series links.
So far, so good. But what if you want to use different titles for link text when coming from different guide pages with different topic link styles? This is where the new Mallard 1.1 feature comes in. In Mallard 1.1, you can add a role attribute to a links element to set the primary role to use for all the links it generates. The implicit role for that links type will still be used as a secondary role.
<links type="topic" role="fancyrole"/>
Boring schema changes
In Mallard 1.0, sections were required to have id. There were a couple of reasons I made that decision, but in the end it turned out to annoy more people than it helped. So in Mallard 1.1, section IDs are optional.
We also made a perfectly boring schema change to make it easier for the Cache Files schema to extend the Mallard schema. (There’s also a new Cache Files 1.1 release.) Although RELAX NG is a mostly great schema language for extensible schema design, it does take some effort to design schemas that can be extended. Mallard got a lot of things right, but sometimes we find something to improve.
And more
That’s it for part 2. If you haven’t already, go read part 1, and keep your eye out for part 1
2019-01-31
We’ve just released Mallard 1.1. Let’s take a look at what’s new. All of these features are already supported in tools like Yelp and Pintail.
This is part 1 in a (probably) 3-part series.
New type attribute for code blocks
MEP-0010: The type Attribute on the code Element
In Mallard 1.0, we used the mime attribute to specify the content type of elements like code and screen. The mime attribute took a MIME type, of course, which seemed like a good idea at the time. Unfortunately, there are very few registered MIME types for the types of content we put in code blocks. So you had to memorize arbitrary long strings.
<code mime="text/x-python">
In Mallard 1.1, we’ve deprecated the mime attribute in favor of the new type attribute. The type attribute takes simple strings, like "xml", "py", and "c". It can also take a space-separated list, so you can provide specific types as well as more generic types to catch different syntax highlighters, like "xml mallard".
<code type="py">
As an added bonus, the type attribute has a shorthand syntax in Ducktype. So instead of typing this:
[code type="py"]
You can just type this:
[code py]
New div element
MEP-0005: Generic div Element
Mallard gives you a handful of semantic block elements, but sometimes you just need to group some block elements together without semantics. This is useful for extensions like Conditionals that operate on block elements. It can make it easier to control things like translatability with ITS. And it can help with transclusions using XInclude.
Mallard 1.1 introduces the new div element as a generic block element. The div element is a formal element, accepting optional title and desc elements. One extra bonus of this addition is that it provides better fallback behavior for extensions that have formal block elements.
Making example formal
Speaking of formal block elements, we made the example element formal, accepting optional title and desc elements. The example element was the only block container element that didn’t allow any sort of title, and that just seemed silly.
Giving blocks info
MEP-0002: Block info Element
All formal block elements now take an optional info element. This can be used, for example, to provide credits and license information for people who drew figures or wrote code listings. Or you can use it to provide alternate titles for UI expanders.
More importantly, this is a crucial first step in making block elements participate in both inline and automatic links, tentatively slated for Mallard 1.2
And more
That’s it for part 1. Keep your eye out for parts 2 and.
Easier.
Ducktype parser extensions
2018-09-15:
@ducktype/1.0 if/1.0
This declares that we’re using version 1.0 of the Ducktype syntax,that we want an extension called if, and that we want version 1.0 of that extension.
Up until last week, extensions were just theoretical. I’ve now added two extension points to the Ducktype parser, and I plan to add three or four more. Both of these are exercised in the _test extension, which is fairly well commented so you can learn from it.
Let’s look at the extensions we have, plus the ones I plan to add.
Block line parser
This extension is implemented. It allows extensions to handle really any sort of line in block context, adding any sort of new syntax. Extensions only get to access to lines after headings, comments, fences, and a few other things are handled. This is a limitation, but it’s one that makes writing extensions much easier.
Let’s look at an actual example that uses this extension: Mallard Conditionals. You can use Mallard Conditionals in Ducktype just fine without any syntax extension. Just declare the namespace and use the elements like any other block element:
Ducktype files can have parser directives at the top. We’ve just seen the @namespace parser directive to declare a namespace. There is an implemented extension point for extensions to handle parser directives, but not yet a real-world extension that uses it.
Extensions only get to handle directives with a prefix matching the extension name. For example, the _test extension only gets to see directives that look like @_test:foo.
Block element handler
This extension is not yet implemented. I want extensions to be able to handle standard-looking block declarations with a prefix. For example, I want the _test extension to be able to do something with a block declaration that looks like this:
[_test:foo]
In principle, you could handle this with the current block line parser extension point, but you’d have to handle parsing the block declaration by yourself, and it might span multiple lines. That’s not ideal.
Importantly, I want both block line parsers and block element handlers to be able to register themselves to handle future lines, so they can have special syntax in following lines. Here is how an extension for CSV-formatted tables might look:
regular Ducktype markup. This is what you would need to create Markdown-like inline markup like *emphasis* and `monospace`.
This extension might have to come in two flavors: before standard parsing and after. And it may be tricky because you want each extension to get a crack at whatever text content was output by other extensions, except you probably also want extensions to be able to block further parsing in some cases.
All in all, I’m really happy with the Ducktype syntax and parser, and how easy it’s been to write extension points so far.
Math.
Restricted Funds in Non-Profit Accounting
2016-09-05
I. | https://blogs.gnome.org/shaunm/category/general/ | CC-MAIN-2019-35 | refinedweb | 4,444 | 64.41 |
torch.fx¶
Overview¶
This feature is under a Beta release and its API may change.
FX is a toolkit for developers to use to transform
nn.Module
instances. FX consists of three main components: a symbolic tracer,
an intermediate representation, and Python code generation. A
demonstration of these components in action:
import torch # Simple module for demonstration class MyModule(torch.nn.Module): def __init__(self): super().__init__() self.param = torch.nn.Parameter(torch.rand(3, 4)) self.linear = torch.nn.Linear(4, 5) def forward(self, x): return self.linear(x + self.param).clamp(min=0.0, max=1.0) module = MyModule() from torch.fx import symbolic_trace # Symbolic tracing frontend - captures the semantics of the module symbolic_traced : torch.fx.GraphModule = symbolic_trace(module) # High-level intermediate representation (IR) - Graph representation print(symbolic_traced.graph) """ graph(x): %param : [#users=1] = self.param %add_1 : [#users=1] = call_function[target=<built-in function add>](args = (%x, %param), kwargs = {}) %linear_1 : [#users=1] = call_module[target=linear](args = (%add_1,), kwargs = {}) %clamp_1 : [#users=1] = call_method[target=clamp](args = (%linear_1,), kwargs = {min: 0.0, max: 1.0}) return clamp_1 """ # Code generation - valid Python code print(symbolic_traced.code) """ def forward(self, x): param = self.param add_1 = x + param; x = param = None linear_1 = self.linear(add_1); add_1 = None clamp_1 = linear_1.clamp(min = 0.0, max = 1.0); linear_1 = None return clamp_1 """
The symbolic tracer performs “symbolic execution” of the Python
code. It feeds fake values, called Proxies, through the code. Operations
on theses Proxies are recorded. More information about symbolic tracing
can be found in the
symbolic_trace() and
Tracer
documentation.
The intermediate representation is the container for the operations
that were recorded during symbolic tracing. It consists of a list of
Nodes that represent function inputs, callsites (to functions, methods,
or
torch.nn.Module instances), and return values. More information
about the IR can be found in the documentation for
Graph. The
IR is the format on which transformations are applied.
Python code generation is what makes FX a Python-to-Python (or
Module-to-Module) transformation toolkit. For each Graph IR, we can
create valid Python code matching the Graph’s semantics. This
functionality is wrapped up in
GraphModule, which is a
torch.nn.Module instance that holds a
Graph as well as a
forward method generated from the Graph.
Taken together, this pipeline of components (symbolic tracing → intermediate representation → transforms → Python code generation) constitutes the Python-to-Python transformation pipeline of FX. In addition, these components can be used separately. For example, symbolic tracing can be used in isolation to capture a form of the code for analysis (and not transformation) purposes. Code generation can be used for programmatically generating models, for example from a config file. There are many uses for FX!
Several example transformations can be found at the examples repository.
Writing Transformations¶
What is an FX transform? Essentially, it’s a function that looks like this.
import torch import torch.fx def transform(m: nn.Module, tracer_class : type = torch.fx.Tracer) -> torch.nn.Module: # Step 1: Acquire a Graph representing the code in `m` # NOTE: torch.fx.symbolic_trace is a wrapper around a call to # fx.Tracer.trace and constructing a GraphModule. We'll # split that out in our transform to allow the caller to # customize tracing behavior. graph : torch.fx.Graph = tracer_class().trace(m) # Step 2: Modify this Graph or create a new one graph = ... # Step 3: Construct a Module to return return torch.fx.GraphModule(m, graph)
Your transform will take in an
torch.nn.Module, acquire a
Graph
from it, do some modifications, and return a new
torch.nn.Module. You should think of the
torch.nn.Module that your FX
transform returns as identical to a regular
torch.nn.Module – you can pass it to another
FX transform, you can pass it to TorchScript, or you can
run it. Ensuring that the inputs and outputs of your FX transform are a
torch.nn.Module will allow for composability.
Note
It is also possible to modify an existing
GraphModule instead of
creating a new one, like so:
import torch import torch.fx def transform(m : nn.Module) -> nn.Module): gm : torch.fx.GraphModule = torch.fx.symbolic_trace(m) # Modify gm.graph # <...> # Recompile the forward() method of `gm` from its Graph gm.recompile() return gm
Note that you MUST call
GraphModule.recompile() to bring the generated
forward() method on the
GraphModule in sync with the modified
Graph.
Given that you’ve passed in a
torch.nn.Module that has been traced into a
Graph, there are now two primary approaches you can take to building a new
Graph.
A Quick Primer on Graphs¶
Full treatment of the semantics of graphs can be found in the
Graph
documentation, but we are going to cover the basics here. A
Graph is
a data structure that represents a method on a
GraphModule. The
information that this requires is:
What are the inputs to the method?
What are the operations that run inside the method?
What is the output (i.e. return) value from the method?
All three of these concepts are represented with
Node instances.
Let’s see what we mean by that with a short example:) gm.graph.print_tabular()
Here we define a module
MyModule for demonstration purposes, instantiate it,
symbolically trace it, then call the
Graph.print_tabular() method to print
out a table showing the nodes of this
Graph:
We can use this information to answer the questions we posed above.
What are the inputs to the method? In FX, method inputs are specified via special
placeholdernodes. In this case, we have a single
placeholdernode with a
targetof
x, meaning we have a single (non-self) argument named x.
What are the operations within the method? The
get_attr,
call_function,
call_module, and
call_methodnodes represent the operations in the method. A full treatment of the semantics of all of these can be found in the
Nodedocumentation.
What is the return value of the method? The return value in a
Graphis specified by a special
outputnode.
Given that we now know the basics of how code is represented in
FX, we can now explore how we would edit a
Graph.
Graph Manipulation¶
Direct Graph Manipulation¶
One approach to building this new
Graph is to directly manipulate your old
one. To aid in this, we can simply take the
Graph we obtain from symbolic
tracing and modify it. For example, let’s say we desire to replace
torch.add() calls with
torch.mul() calls.
import torch import torch.fx # Sample module class M(torch.nn.Module): def forward(self, x, y): return torch.add(x, y) def transform(m: torch.nn.Module, tracer_class : type = fx.Tracer) -> torch.nn.Module: graph : fx.Graph = tracer_class().trace(m) # FX represents its Graph as an ordered list of # nodes, so we can iterate through them. for node in graph.nodes: # Checks if we're calling a function (i.e: # torch.add) if node.op == 'call_function': # The target attribute is the function # that call_function calls. if node.target == torch.add: node.target = torch.mul graph.lint() # Does some checks to make sure the # Graph is well-formed. return fx.GraphModule(m, graph)
We can also do more involved
Graph rewrites, such as
deleting or appending nodes. To aid in these transformations,
FX has utility functions for transforming the graph that can
be found in the
Graph documentation. An
example of using these APIs to append a
torch.relu() call
can be found below.
# Specifies the insertion point. Any nodes added to the # Graph within this scope will be inserted after `node` with traced.graph.inserting_after(node): # Insert a new `call_function` node calling `torch.relu` new_node = traced.graph.call_function( torch.relu, args=(node,)) # We want all places that used the value of `node` to # now use that value after the `relu` call we've added. # We use the `replace_all_uses_with` API to do this. node.replace_all_uses_with(new_node)
For simple transformations that only consist of substitutions, you can also make use of the subgraph rewriter.
Subgraph Rewriting With replace_pattern()¶
FX also provides another level of automation on top of direct graph manipulation.
The
replace_pattern() API is essentially a “find/replace” tool for editing
Graphs. It allows you to specify a
pattern and
replacement function
and it will trace through those functions, find instances of the group of operations
in the
pattern graph, and replace those instances with copies of the
replacement
graph. This can help to greatly automate tedious graph manipulation code, which can
get unwieldy as the transformations get more complex.
Graph Manipulation Examples¶
Proxy/Retracing¶
Another way of manipulating
Graphs is by reusing the
Proxy
machinery used in symbolic tracing. For example, let’s
imagine that we wanted to write a transformation that decomposed
PyTorch functions into smaller operations. It would transform every
F.relu(x) call into
(x > 0) * x. One possibility would be to
perform the requisite graph rewriting to insert the comparison and
multiplication after the
F.relu, and then clean up the original
F.relu. However, we can automate this process by using
Proxy
objects to automatically record operations into the
Graph.
To use this method, we write the operations that we want inserted as regular
PyTorch code and invoke that code with
Proxy objects as arugments.
These
Proxy objects will capture the operations that are performed
on them and append them to the
Graph.
# Note that this decomposition rule can be read as regular Python def relu_decomposition(x): return (x > 0) * x decomposition_rules = {} decomposition_rules[F.relu] = relu_decomposition def decompose(model: torch.nn.Module, tracer_class : type = fx.Tracer) -> torch.nn.Module: """ Decompose `model` into smaller constituent operations. Currently,this only supports decomposing ReLU into its mathematical definition: (x > 0) * x """ graph : fx.Graph = tracer_class().trace(model) new_graph = fx.Graph() env = {} for node in graph.nodes: if node.op == 'call_function' and node.target in decomposition_rules: # By wrapping the arguments with proxies, # we can dispatch to the appropriate # decomposition rule and implicitly add it # to the Graph by symbolically tracing it. proxy_args = [ fx.Proxy(env[x.name]) if isinstance(x, fx.Node) else x for x in node.args] output_proxy = decomposition_rules[node.target](*proxy_args) # Operations on `Proxy` always yield new `Proxy`s, and the # return value of our decomposition rule is no exception. # We need to extract the underlying `Node` from the `Proxy` # to use it in subsequent iterations of this transform. new_node = output_proxy.node env[node.name] = new_node else: # Default case: we don't have a decomposition rule for this # node, so just copy the node over into the new graph. new_node = new_graph.node_copy(node, lambda x: env[x.name]) env[node.name] = new_node return fx.GraphModule(model, new_graph)
In addition to avoiding explicit graph manipulation, using
Proxys
also allows you to specify your rewrite rules as native Python code.
For transformations that require a large amount of rewrite rules
(such as vmap or grad), this can often improve readability and
maintainability of the rules.
A worked example of using
Proxys for
Graph manipulation
can be found
here.
The Interpreter Pattern¶
A useful code organizational pattern in FX is to loop over all the
Nodes
in a
Graph and execute them. This can be used for several things including
runtime analysis of values flowing through the graph or transformation of the code
via retracing with
Proxys. For example, suppose we want to run a
GraphModule and record the
torch.Tensor shape and dtype
properties on the nodes as we see them at runtime. That might look like:
import torch import torch.fx from torch.fx.node import Node from typing import Dict class ShapeProp: """ Shape propagation. This class takes a `GraphModule`. Then, its `propagate` method executes the `GraphModule` node-by-node with the given arguments. As each operation executes, the ShapeProp class stores away the shape and element type for the output values of each operation on the `shape` and `dtype` attributes of the operation's `Node`. """ def __init__(self, mod): self.mod = mod self.graph = mod.graph self.modules = dict(self.mod.named_modules()) def propagate(self, *args): args_iter = iter(args) env : Dict[str, Node] = {} def load_arg(a): return torch.fx.graph.map_arg(a, lambda n: env[n.name]) def fetch_attr(target : str): target_atoms = target.split('.') attr_itr = self.mod for i, atom in enumerate(target_atoms): if not hasattr(attr_itr, atom): raise RuntimeError(f"Node referenced nonexistant target {'.'.join(target_atoms[:i])}") attr_itr = getattr(attr_itr, atom) return attr_itr for node in self.graph.nodes: if node.op == 'placeholder': result = next(args_iter) elif node.op == 'get_attr': result = fetch_attr(node.target) elif node.op == 'call_function': result = node.target(*load_arg(node.args), **load_arg(node.kwargs)) elif node.op == 'call_method': self_obj, *args = load_arg(node.args) kwargs = load_arg(node.kwargs) result = getattr(self_obj, node.target)(*args, **kwargs) elif node.op == 'call_module': result = self.modules[node.target](*load_arg(node.args), **load_arg(node.kwargs)) # This is the only code specific to shape propagation. # you can delete this `if` branch and this becomes # a generic GraphModule interpreter. if isinstance(result, torch.Tensor): node.shape = result.shape node.dtype = result.dtype env[node.name] = result return load_arg(self.graph.result)
As you can see, a full interpreter for FX is not that complicated
but it can be very useful. To ease using this pattern, we provide
the
Interpreter class, which encompasses the above logic
in a way that certain aspects of the interpreter’s execution can
be overridden via method overrides.
In addition to executing operations, we can also generate a new
Graph by feeding
Proxy values through an interpreter.
Similarly, we provide the
Transformer class to encompass
this pattern.
Transformer behaves similarly to
Interpreter, but instead of calling the
run method to
get a concrete output value from the Module, you would call the
Transformer.transform() method to return a new
GraphModule which was subject to any transformation rules
you installed as overridden methods.
Examples of the Interpreter Pattern¶
Debugging¶
Introduction¶
Often in the course of authoring transformations, our code will not be quite right. In this case, we may need to do some debugging. The key is to work backwards: first, check the results of invoking the generated module to prove or disprove correctness. Then, inspect and debug the generated code. Then, debug the process of transformations that led to the generated code.
If you’re not familiar with debuggers, please see the auxiliary section Available Debuggers.
Checking Correctness of Modules¶
Because the output of most deep learning modules consists of floating
point
torch.Tensor instances, checking for equivalence between
the results of two
torch.nn.Module is not as straightforward
as doing a simple equality check. To motivate this, let’s use an
example:
import torch import torch.fx import torchvision.models as models def transform(m : torch.nn.Module) -> torch.nn.Module: gm = torch.fx.symbolic_trace(m) # Imagine we're doing some transforms here # <...> gm.recompile() return gm resnet18 = models.resnet18() transformed_resnet18 = transform(resnet18) input_image = torch.randn(5, 3, 224, 224) assert resnet18(input_image) == transformed_resnet18(input_image) """ RuntimeError: Boolean value of Tensor with more than one value is ambiguous """
Here, we’ve tried to check equality of the values of two deep learning
models with the
== equality operator. However, this is not well-
defined both due to the issue of that operator returning a tensor
and not a bool, but also because comparison of floating point values
should use a margin of error (or epsilon) to account for the
non-commutativity of floating point operations (see
here for more
details). We can use
torch.allclose() instead, which will give
us an approximate comparison taking into account a relative and
absolute tolerance threshold:
assert torch.allclose(resnet18(input_image), transformed_resnet18(input_image))
This is the first tool in our toolbox to check if transformed modules are behaving as we expect compared to a reference implementation.
Debugging the Generated Code¶
Because FX generates the
forward() function on
GraphModules, using
traditional debugging techniques like
pdb is
not as straightfoward. Luckily, we have several techniques we can use
for debugging the generated code.
Use
pdb¶
Invoke
pdb to step into the running program. Although the code that
represents the
Graph is not in any source file, we can still step
into it manually using
pdb when the forward pass is invoked.
import torch import torch.fx import torchvision.models as models def my_pass(inp: torch.nn.Module, tracer_class : type = fx.Tracer) -> torch.nn.Module: graph = tracer_class().trace(inp) # Transformation logic here # <...> # Return new Module return fx.GraphModule(inp, graph) my_module = models.resnet18() my_module_transformed = my_pass(my_module) input_value = torch.randn(5, 3, 224, 224) # When this line is executed at runtime, we will be dropped into an # interactive `pdb` prompt. We can use the `step` or `s` command to # step into the execution of the next line import pdb; pdb.set_trace() my_module_transformed(input_value)
Print the Generated Code¶
If you’d like to run the same code multiple times, then it can be
a bit tedious to step to the right code with
pdb. In that case, one
approach is to simply copy-paste the generated
forward pass into
your code and examine it from there.
# Assume that `traced` is a GraphModule that has undergone some # number of transforms # Copy this code for later print(traced) # Print the code generated from symbolic tracing. This outputs: """ def forward(self, y): x = self.x add_1 = x + y; x = y = None return add_1 """ # Subclass the original Module class SubclassM(M): def __init__(self): super().__init__() # Paste the generated `forward` function (the one we printed and # copied above) here def forward(self, y): x = self.x add_1 = x + y; x = y = None return add_1 # Create an instance of the original, untraced Module. Then, create an # instance of the Module with the copied `forward` function. We can # now compare the output of both the original and the traced version. pre_trace = M() post_trace = SubclassM()
Use the
to_folder Function From
GraphModule¶
GraphModule.to_folder() is a method in
GraphModule that allows
you to dump out the generated FX code to a folder. Although copying the
forward pass into the code often suffices as in Print the Generated Code,
it may be easier to examine modules and parameters using
to_folder.
m = symbolic_trace(M()) m.to_folder("foo", "Bar") from foo import Bar y = Bar()
After running the above example, we can then look at the code within
foo/module.py and modify it as desired (e.g. adding
pdb) to debug the generated code.
Debugging the Transformation¶
Now that we’ve identified that a transformation is creating incorrect
code, it’s time to debug the transformation itself. First, we’ll check
the Limitations of Symbolic Tracing section in the documentation.
Once we verify that tracing is working as expected, the goal
becomes figuring out what went wrong during our
GraphModule
transformation. There may be a quick answer in
Writing Transformations, but, if not, there are several ways to
examine our traced module:
# Sample Module class M(torch.nn.Module): def forward(self, x, y): return x + y # Create an instance of `M` m = M() # Symbolically trace an instance of `M` (returns a GraphModule). In # this example, we'll only be discussing how to inspect a # GraphModule, so we aren't showing any sample transforms for the # sake of brevity. traced = symbolic_trace(m) # Print the code produced by tracing the module. print(traced) # The generated `forward` function is: """ def forward(self, x, y): add_1 = x + y; x = y = None return add_1 """ # Print the internal Graph. print(traced.graph) # This print-out returns: """ graph(x, y): %add_1 : [#users=1] = call_function[target=<built-in function add>](args = (%x, %y), kwargs = {}) return add_1 """ # Print a tabular representation of the internal Graph. traced.graph.print_tabular() # This gives us: """ opcode name target args kwargs ------------- ------ ----------------------- -------- -------- placeholder x x () {} placeholder y y () {} call_function add_1 <built-in function add> (x, y) {} """
Using the utility functions above, we can compare our traced Module
before and after we’ve applied our transformations. Sometimes, a
simple visual comparison is enough to trace down a bug. If it’s still
not clear what’s going wrong, a debugger like
pdb can be a good
next step.
Going off of the example above, consider the following code:
# Sample user-defined function def transform_graph(module: torch.nn.Module, tracer_class : type = fx.Tracer) -> torch.nn.Module: # Get the Graph from our traced Module g = tracer_class().trace(module) """ Transformations on `g` go here """ return fx.GraphModule(module, g) # Transform the Graph transformed = transform_graph(traced) # Print the new code after our transforms. Check to see if it was # what we expected print(transformed)
Using the above example, let’s say that the call to
print(traced)
showed us that there was an error in our transforms. We want to find
what goes wrong using a debugger. We start a
pdb session. We can see
what’s happening during the transform by breaking on
transform_graph(traced), then pressing
s to “step into” the call
to
transform_graph(traced).
We may also have good luck by editing the
print_tabular method to print
different attributes of the Nodes in the Graph. (For example, we might
want to see the Node’s
input_nodes and
users.)
Available Debuggers¶
The most common Python debugger is
pdb. You can start
your program in “debug mode” with
pdb by typing
python -m pdb FILENAME.py into the command line, where
FILENAME
is the name of the file you want to debug. After that, you can use the
pdb debugger commands
to move through your running program stepwise. It’s common to set a
breakpoint (
b LINE-NUMBER) when you start
pdb, then call
c to
run the program until that point. This prevents you from having to step
through each line of execution (using
s or
n) to get to the part
of the code you want to examine. Alternatively, you can write
import pdb; pdb.set_trace() before the line you want to break at.
If you add
pdb.set_trace(), your program will automatically start
in debug mode when you run it. (In other words, you can just type
python FILENAME.py into the command line instead of
python -m pdb FILENAME.py.) Once you’re running your file in
debug mode, you can step through the code and examine your program’s
internal state using certain commands. There are many excellent
tutorials on
pdb online, including RealPython’s
“Python Debugging With Pdb”.
IDEs like PyCharm or VSCode usually have a debugger built in. In your
IDE, you can choose to either a) use
pdb by pulling up a terminal
window in your IDE (e.g. View → Terminal in VSCode), or b) use the
built-in debugger (usually a graphical wrapper around
pdb).
Limitations of Symbolic Tracing¶
FX uses a system of symbolic tracing (a.k.a symbolic
execution)
to capture the semantics of programs in a transformable/analyzable form.
The system is tracing in that it executes the program (really a
torch.nn.Module or function) to record operations. It is
symbolic in that the data flowing through the program during this
execution is not real data, but rather symbols (
Proxy in FX parlance).
Although symbolic tracing works for most neural net code, it has some limitations.
Dynamic Control Flow¶
The main limitation of symbolic tracing is it does not currently support
dynamic control flow. That is, loops or
if statements where the
condition may depend on the input values of the program.
For example, let’s examine the following program:
def func_to_trace(x): dim0 = x.size[0] if dim0 == 3: return torch.relu(x) else: return torch.neg(x) traced = torch.fx.symbolic_trace(func_to_trace) """ <...> File "dyn.py", line 6, in func_to_trace if dim0 == 3: File "pytorch/torch/fx/proxy.py", line 155, in __bool__ return self.tracer.to_bool(self) File "pytorch/torch/fx/proxy.py", line 85, in to_bool raise TraceError('symbolically traced variables cannot be used as inputs to control flow') torch.fx.proxy.TraceError: symbolically traced variables cannot be used as inputs to control flow """
The condition to the
if statement relies on the value of
dim0,
which eventually relies on the value of
x, a function input. Since
x can change (i.e. if you pass a new input tensor to the traced
function), this is dynamic control flow. The traceback walks back up
through your code to show you where this situation happens.
Static Control Flow¶
On the other hand, so-called static control flow is supported. Static
control flow is loops or
if statements whose value cannot change
across invocations. Typically, in PyTorch programs, this control flow
arises for code making decisions about a model’s architecture based on
hyper-parameters. As a concrete example:
import torch import torch.fx class MyModule(torch.nn.Module): def __init__(self, do_activation : bool = False): super().__init__() self.do_activation = do_activation self.linear = torch.nn.Linear(512, 512) def forward(self, x): x = self.linear(x) # This if-statement is so-called static control flow. # Its condition does not depend on any input values if self.do_activation: x = torch.relu(x) return x without_activation = MyModule(do_activation=False) with_activation = MyModule(do_activation=True) traced_without_activation = torch.fx.symbolic_trace(without_activation) print(traced_without_activation.code) """ def forward(self, x): linear_1 = self.linear(x); x = None return linear_1 """ traced_with_activation = torch.fx.symbolic_trace(with_activation) print(traced_with_activation.code) """ import torch def forward(self, x): linear_1 = self.linear(x); x = None relu_1 = torch.relu(linear_1); linear_1 = None return relu_1 """
The if-statement
if self.do_activation does not depend on any
function inputs, thus it is static.
do_activation can be considered
to be a hyper-parameter, and the traces of different instances of
MyModule with different values for that parameter have different
code. This is a valid pattern that is supported by symbolic tracing.
Many instances of dynamic control flow are semantically static control
flow. These instances can be made to support symbolic tracing by
removing the data dependencies on input values, for example by moving
values to
Module attributes or by passing constant values during
symbolic tracing:
def f(x, flag): if flag: return x else: return x*2 fx.symbolic_trace(f) # Fails! def wrapper(flag): return lambda x: f(x, flag) new_f = wrapper(flag=True) fx.symbolic_trace(new_f)
In the case of truly dynamic control flow, the sections of the program
that contain this code can be traced as calls to the Method (see
Customizing Tracing with the Tracer class) or function (see
wrap()) rather than tracing through them.
Non-
torch Functions¶
FX uses
__torch_function__ as the mechanism by which it intercepts
calls (see the technical
overview
for more information about this). Some functions, such as builtin Python
functions or those in the
math module, are things that are not
covered by
__torch_function__, but we would still like to capture
them in symbolic tracing. For example:
import torch import torch.fx from math import sqrt def normalize(x): """ Normalize `x` by the size of the batch dimension """ return x / sqrt(len(x)) # It's valid Python code normalize(torch.rand(3, 4)) traced = torch.fx.symbolic_trace(normalize) """ <...> File "sqrt.py", line 9, in normalize return x / sqrt(len(x)) File "pytorch/torch/fx/proxy.py", line 161, in __len__ raise RuntimeError("'len' is not supported in symbolic tracing by default. If you want " RuntimeError: 'len' is not supported in symbolic tracing by default. If you want this call to be recorded, please call torch.fx.wrap('len') at module scope """
The error tells us that the built-in function
len is not supported.
We can make it so that functions like this are recorded in the trace as
direct calls using the
wrap() API:
torch.fx.wrap('len') torch.fx.wrap('sqrt') traced = torch.fx.symbolic_trace(normalize) print(traced.code) """ import math def forward(self, x): len_1 = len(x) sqrt_1 = math.sqrt(len_1); len_1 = None truediv = x / sqrt_1; x = sqrt_1 = None return truediv """
Customizing Tracing with the
Tracer class¶
The
Tracer class is the class that underlies the
implementation of
symbolic_trace. The behavior of tracing can be
customized by subclassing Tracer, like so:
class MyCustomTracer(torch.fx.Tracer): # Inside here you can override various methods # to customize tracing. See the `Tracer` API # reference pass # Let's use this custom tracer to trace through this module class MyModule(torch.nn.Module): def forward(self, x): return torch.relu(x) + torch.ones(3, 4) mod = MyModule() traced_graph = MyCustomTracer().trace(mod) # trace() returns a Graph. Let's wrap it up in a # GraphModule to make it runnable traced = torch.fx.GraphModule(mod, traced_graph)
Leaf Modules¶
Leaf Modules are the modules that appear as calls in the symbolic trace
rather than being traced through. The default set of leaf modules is the
set of standard
torch.nn module instances. For example:
class MySpecialSubmodule(torch.nn.Module): def forward(self, x): return torch.neg(x) class MyModule(torch.nn.Module): def __init__(self): super().__init__() self.linear = torch.nn.Linear(3, 4) self.submod = MySpecialSubmodule() def forward(self, x): return self.submod(self.linear(x)) traced = torch.fx.symbolic_trace(MyModule()) print(traced.code) # `linear` is preserved as a call, yet `submod` is traced though. # This is because the default set of "Leaf Modules" includes all # standard `torch.nn` modules. """ import torch def forward(self, x): linear_1 = self.linear(x); x = None neg_1 = torch.neg(linear_1); linear_1 = None return neg_1 """
The set of leaf modules can be customized by overriding
Tracer.is_leaf_module().
Miscellanea¶
Tensor constructors (e.g.
torch.zeros,
torch.ones,
torch.rand,
torch.randn,
torch.sparse_coo_tensor) are currently not traceable.
The deterministic constructors (
zeros,
ones) can be used and the value they produce will be embedded in the trace as a constant. This is only problematic if the arguments to these constructors refers to dynamic input sizes. In this case,
ones_likeor
zeros_likemay be a viable substitute.
Nondeterministic constructors (
rand,
randn) will have a single random value embedded in the trace. This is likely not the intended behavior.
This behavior may be fixed in a future release.
Type annotations
Python 3-style type annotations (e.g.
func(x : torch.Tensor, y : int) -> torch.Tensor) are supported and will be preserved by symbolic tracing.
Python 2-style comment type annotations
# type: (torch.Tensor, int) -> torch.Tensorare not currently supported.
Annotations on local names within a function are not currently supported.
API Reference¶
torch.fx.
symbolic_trace(root, concrete_args=None)[source]¶
Symbolic tracing API
Given an
nn.Moduleor function instance
root, this function will return a
GraphModuleconstructed by recording operations seen while tracing through
root.
- Parameters
root (Union[torch.nn.Module, Callable]) – Module or function to be traced and converted into a Graph representation.
concrete_args (Optional[Dict[str, any]]) – Concrete arguments that should not be treated as Proxies.
- Returns
a Module created from the recorded operations from
root.
- Return type
-
torch.fx.
wrap(fn_or_name)[source]¶
This function can be called at module-level scope to register fn_or_name as a “leaf function”. A “leaf function” will be preserved as a CallFunction node in the FX trace instead of being traced through:
# foo/bar/baz.py def my_custom_function(x, y): return x * x + y * y torch.fx.wrap('my_custom_function') def fn_to_be_traced(x, y): # When symbolic tracing, the below call to my_custom_function will be inserted into # the graph rather than tracing it. return my_custom_function(x, y)
This function can also equivalently be used as a decorator:
# foo/bar/baz.py @torch.fx.wrap def my_custom_function(x, y): return x * x + y * y
A wrapped function can be thought of a “leaf function”, analogous to the concept of “leaf modules”, that is, they are functions that are left as calls in the FX trace rather than traced through.
- class
torch.fx.
GraphModule(root, graph, class_name='GraphModule')[source]¶
GraphModule is an nn.Module generated from an fx.Graph. Graphmodule has a
graphattribute, as well as
codeand
forwardattributes generated from that
graph.
Warning
When
graphis reassigned,
codeand
forwardwill be automatically regenerated. However, if you edit the contents of the
graphwithout reassigning the
graphattribute itself, you must call
recompile()to update the generated code.
__init__(root, graph, class_name='GraphModule')[source]¶
Construct a GraphModule.
- Parameters
root (Union[torch.nn.Module, Dict[str, Any]) –
rootcan either be an nn.Module instance or a Dict mapping strings to any attribute type. In the case that
rootis a Module, any references to Module-based objects (via qualified name) in the Graph’s Nodes’
targetfield will be copied over from the respective place within
root’s Module hierarchy into the GraphModule’s module hierarchy. In the case that
rootis a dict, the qualified name found in a Node’s
targetwill be looked up directly in the dict’s keys. The object mapped to by the Dict will be copied over into the appropriate place within the GraphModule’s module hierarchy.
graph (Graph) –
graphcontains the nodes this GraphModule should use for code generation
name (str) –
namedenotes the name of this GraphModule for debugging purposes. If it’s unset, all error messages will report as originating from
GraphModule. It may be helpful to set this to
root’s original name or a name that makes sense within the context of your transform.
recompile()[source]¶
Recompile this GraphModule from its
graphattribute. This should be called after editing the contained
graph, otherwise the generated code of this
GraphModulewill be out of date.
to_folder(folder, module_name='FxModule')[source]¶
Dumps out module to
folderwith
module_nameso that it can be imported with
from <folder> import <module_name>
- Parameters
folder (Union[str, os.PathLike]) – The folder to write the code out to
module_name (str) – Top-level name to use for the
Modulewhile writing out the code
- class
torch.fx.
Graph[source]¶
Graphis the main data structure used in the FX Intermediate Representation. It consists of a series of
Nodes, each representing callsites (or other syntactic constructs). The list of
Nodes, taken together, constitute a valid Python function.
For example, the following code)
Will produce the following Graph:
print(gm.graph)
graph(x): %linear_weight : [#users=1] = self.linear.weight %add_1 : [#users=1] = call_function[target=operator.add](args = (%x, %linear_weight), kwargs = {}) %linear_1 : [#users=1] = call_module[target=linear](args = (%add_1,), kwargs = {}) %relu_1 : [#users=1] = call_method[target=relu](args = (%linear_1,), kwargs = {}) %sum_1 : [#users=1] = call_function[target=torch.sum](args = (%relu_1,), kwargs = {dim: -1}) %topk_1 : [#users=1] = call_function[target=torch.topk](args = (%sum_1, 3), kwargs = {}) return topk_1
For the semantics of operations represented in the
Graph, please see
Node.
call_function(the_function, args=None, kwargs=None, type_expr=None)[source]¶
Insert a
call_function
Nodeinto the
Graph. A
call_functionnode represents a call to a Python callable, specified by
the_function.
the_functioncan be
- Parameters
the_function (Callable[.., Any]) – The function to be called. Can be any PyTorch operator, Python function, or member of the
builtinsor
operatornamespaces.
args (Optional[Tuple[Argument, ..]]) – The positional arguments to be passed to the called function.
kwargs (Optional[Dict[str, Argument]]) – The keyword arguments to be passed to the called function
type_expr (Optional[Any]) – an optional type annotation representing the Python type the output of this node will have.
Returns
The newly created and inserted
call_functionnode.
Note
The same insertion point and type expression rules apply for this method as
Graph.create_node().
call_method(method_name, args=None, kwargs=None, type_expr=None)[source]¶
Insert a
call_method
Nodeinto the
Graph. A
call_methodnode represents a call to a given method on the 0th element of
args.
- Parameters
method_name (str) – The name of the method to apply to the self argument. For example, if args[0] is a
Noderepresenting a
Tensor, then to call
relu()on that
Tensor, pass
reluto
method_name.
args (Optional[Tuple[Argument, ..]]) – The positional arguments to be passed to the called method. Note that this should include a
selfargument.
kwargs (Optional[Dict[str, Argument]]) – The keyword arguments to be passed to the called method
type_expr (Optional[Any]) – an optional type annotation representing the Python type the output of this node will have.
- Returns
The newly created and inserted
call_methodnode.
Note
The same insertion point and type expression rules apply for this method as
Graph.create_node().
call_module(module_name, args=None, kwargs=None, type_expr=None)[source]¶
Insert a
call_module
Nodeinto the
Graph. A
call_modulenode represents a call to the forward() function of a
Modulein the
Modulehierarchy.
- Parameters
module_name (str) – The qualified name of the
Modulein the
Modulehierarchy to be called. For example, if the traced
Modulehas a submodule named
foo, which has a submodule named
bar, the qualified name
foo.barshould be passed as
module_nameto call that module.
args (Optional[Tuple[Argument, ..]]) – The positional arguments to be passed to the called method. Note that this should not include a
selfargument.
kwargs (Optional[Dict[str, Argument]]) – The keyword arguments to be passed to the called method
type_expr (Optional[Any]) – an optional type annotation representing the Python type the output of this node will have.
- Returns
The newly-created and inserted
call_modulenode.
Note
The same insertion point and type expression rules apply for this method as
Graph.create_node().
create_node(op, target, args=None, kwargs=None, name=None, type_expr=None)[source]¶
Create a
Nodeand add it to the
Graphat the current insert-point. Note that the current insert-point can be set via
Graph.inserting_before()and
Graph.inserting_after().
- Parameters
op (str) – the opcode for this Node. One of ‘call_function’, ‘call_method’, ‘get_attr’, ‘call_module’, ‘placeholder’, or ‘output’. The semantics of these opcodes are described in the
Graphdocstring.
args (Optional[Tuple[Argument, ..]]) – is a tuple of arguments to this node.
kwargs (Optional[Dict[str, Argument]]) – the kwargs of this Node
name (Optional[str]) – an optional string name for the
Node. This will influence the name of the value assigned to in the Python generated code.
type_expr (Optional[Any]) – an optional type annotation representing the Python type the output of this node will have.
- Returns
The newly-created and inserted node.
erase_node(to_erase)[source]¶
Erases a
Nodefrom the
Graph. Throws an exception if there are still users of that node in the
Graph.
get_attr(qualified_name, type_expr=None)[source]¶
Insert a
get_attrnode into the Graph. A
get_attr
Noderepresents the fetch of an attribute from the
Modulehierarchy.
- Parameters
qualified_name (str) – the fully-qualified name of the attribute to be retrieved. For example, if the traced Module has a submodule named
foo, which has a submodule named
bar, which has an attribute named
baz, the qualified name
foo.bar.bazshould be passed as
qualified_name.
type_expr (Optional[Any]) – an optional type annotation representing the Python type the output of this node will have.
- Returns
The newly-created and inserted
get_attrnode.
Note
The same insertion point and type expression rules apply for this method as
Graph.create_node.
graph_copy(g, val_map)[source]¶
Copy all nodes from a given graph into
self.
- Parameters
-
- Returns
The value in
selfthat is now equivalent to the output value in
g, if
ghad an
outputnode.
Noneotherwise.
inserting_after(n=None)[source]¶
Set the point at which create_node and companion methods will insert into the graph. When used within a ‘with’ statement, this will temporary set the insert point and then restore it when the with statement exits:
with g.inserting_after(n): ... # inserting after node n ... # insert point restored to what it was previously g.inserting_after(n) # set the insert point permanently
inserting_before(n=None)[source]¶
Set the point at which create_node and companion methods will insert into the graph. When used within a ‘with’ statement, this will temporary set the insert point and then restore it when the with statement exits:
with g.inserting_before(n): ... # inserting before node n ... # insert point restored to what it was previously g.inserting_before(n) # set the insert point permanently
lint(root=None)[source]¶
Runs various checks on this Graph to make sure it is well-formed. In particular: - Checks Nodes have correct ownership (owned by this graph) - Checks Nodes appear in topological order - If
rootis provided, checks that targets exist in
root
- Parameters
root (Optional[torch.nn.Module]) – The root module with which to check for targets. This is equivalent to the
rootargument that is passed when constructing a
GraphModule.
node_copy(node, arg_transform=<function Graph.<lambda>>)[source]¶
Copy a node from one graph into another.
arg_transformneeds to transform arguments from the graph of node to the graph of self. Example:
# Copying all the nodes in `g` into `new_graph` g : torch.fx.Graph = ... new_graph = torch.fx.graph() value_remap = {} for node in g.nodes: value_remap[node] = new_graph.node_copy(node, lambda n : value_remap[n])
- Parameters
node (Node) – The node to copy into
self.
arg_transform (Callable[[Node], Argument]) – A function that transforms
Nodearguments in node’s
argsand
kwargsinto the equivalent argument in
self. In the simplest case, this should retrieve a value out of a table mapping Nodes in the original graph to
self.
- property
nodes¶
Get the list of Nodes that constitute this Graph.
Note that this
Nodelist representation is a doubly-linked list. Mutations during iteration (e.g. delete a Node, add a Node) are safe.
- Returns
A doubly-linked list of Nodes. Note that
reversedcan be called on this list to switch iteration order.
output(result, type_expr=None)[source]¶
Insert an
output
Nodeinto the
Graph. An
outputnode represents a
returnstatement in Python code.
resultis the value that should be returned.
- Parameters
result (Argument) – The value to be returned.
type_expr (Optional[Any]) – an optional type annotation representing the Python type the output of this node will have.
Note
The same insertion point and type expression rules apply for this method as
Graph.create_node.
placeholder(name, type_expr=None)[source]¶
Insert a
placeholdernode into the Graph. A
placeholderrepresents a function input.
- Parameters
name (str) – A name for the input value. This corresponds to the name of the positional argument to the function this
Graphrepresents.
type_expr (Optional[Any]) – an optional type annotation representing the Python type the output of this node will have. This is needed in some cases for proper code generation (e.g. when the function is used subsequently in TorchScript compilation).
Note
The same insertion point and type expression rules apply for this method as
Graph.create_node.
- class
torch.fx.
Node(graph, name, op, target, args, kwargs, type=None)[source]¶
Nodeis the data structure that represents individual operations within a
Graph. For the most part, Nodes represent callsites to various entities, such as operators, methods, and Modules (some exceptions include nodes that specify function inputs and outputs). Each
Nodehas a function specified by its
opproperty. The
Nodesemantics for each value of
opare as follows:
placeholderrepresents a function input. The
nameattribute specifies the name this value will take on.
targetis similarly the name of the argument.
argsholds either: 1) nothing, or 2) a single argument denoting the default parameter of the function input.
kwargsis don’t-care. Placeholders correspond to the function parameters (e.g.
x) in the graph printout.
get_attrretrieves a parameter from the module hierarchy.
nameis similarly the name the result of the fetch is assigned to.
targetis the fully-qualified name of the parameter’s position in the module hierarchy.
argsand
kwargsare don’t-care
call_functionapplies a free function to some values.
nameis similarly the name of the value to assign to.
targetis the function to be applied.
argsand
kwargsrepresent the arguments to the function, following the Python calling convention
call_moduleapplies a module in the module hierarchy’s
forward()method to given arguments.
nameis as previous.
targetis the fully-qualified name of the module in the module hierarchy to call.
argsand
kwargsrepresent the arguments to invoke the module on, including the self argument.
call_methodcalls a method on a value.
nameis as similar.
targetis the string name of the method to apply to the
selfargument.
argsand
kwargsrepresent the arguments to invoke the module on, including the self argument
outputcontains the output of the traced function in its
args[0]attribute. This corresponds to the “return” statement in the Graph printout.
- property
all_input_nodes¶
Return all Nodes that are inputs to this Node. This is equivalent to iterating over
argsand
kwargsand only collecting the values that are Nodes.
- Returns
List of
Nodesthat appear in the
argsand
kwargsof this
Node, in that order.
append(x)[source]¶
Insert x after this node in the list of nodes in the graph. Equvalent to
self.next.prepend(x)
- property
args¶
The tuple of arguments to this
Node. The interpretation of arguments depends on the node’s opcode. See the
Nodedocstring for more information.
Assignment to this property is allowed. All accounting of uses and users is updated automatically on assignment.
- property
kwargs¶
The dict of keyword arguments to this
Node. The interpretation of arguments depends on the node’s opcode. See the
Nodedocstring for more information.
Assignment to this property is allowed. All accounting of uses and users is updated automatically on assignment.
- property
Returns the next
Nodein the linked list of Nodes.
- Returns
The next
Nodein the linked list of Nodes.
prepend(x)[source]¶
Insert x before this node in the list of nodes in the graph. Example:
Before: p -> self bx -> x -> ax After: p -> x -> self bx -> ax
- property
prev¶
Returns the previous
Nodein the linked list of Nodes.
- Returns
The previous
Nodein the linked list of Nodes.
- class
torch.fx.
Tracer(autowrap_modules=(math, ))[source]¶
Traceris the class that implements the symbolic tracing functionality of
torch.fx.symbolic_trace. A call to
symbolic_trace(m)is equivalent to
Tracer().trace(m).
Tracer can be subclassed to override various behaviors of the tracing process. The different behaviors that can be overridden are described in the docstrings of the methods on this class.
call_module(m, forward, args, kwargs)[source]¶
Method that specifies the behavior of this
Tracerwhen it encounters a call to an
nn.Moduleinstance.
By default, the behavior is to check if the called module is a leaf module via
is_leaf_module. If it is, emit a
call_modulenode referring to
min the
Graph. Otherwise, call the
Modulenormally, tracing through the operations in its
forwardfunction.
This method can be overridden to–for example–create nested traced GraphModules, or any other behavior you would want while tracing across
Moduleboundaries.
Moduleboundaries.
- Parameters
-
- Returns
The return value from the Module call. In the case that a
call_modulenode was emitted, this is a
Proxyvalue. Otherwise, it is whatever value was returned from the
Moduleinvocation.
create_arg(a)[source]¶
A method to specify the behavior of tracing when preparing values to be used as arguments to nodes in the
Graph.
By default, the behavior includes:
Iterate through collection types (e.g. tuple, list, dict) and recursively call
create_argson the elements.
Given a Proxy object, return a reference to the underlying IR
Node
Given a non-Proxy Tensor object, emit IR for various cases:
For a Parameter, emit a
get_attrnode referring to that Parameter
For a non-Parameter Tensor, store the Tensor away in a special attribute referring to that attribute.
This method can be overridden to support more types.
- Parameters
a (Any) – The value to be emitted as an
Argumentin the
Graph.
- Returns
The value
aconverted into the appropriate
Argument
create_args_for_root(root_fn, is_module, concrete_args=None)[source]¶
Create
placeholdernodes corresponding to the signature of the
rootModule. This method introspects root’s signature and emits those nodes accordingly, also supporting
*argsand
**kwargs.
is_leaf_module(m, module_qualified_name)[source]¶
A method to specify whether a given
nn.Moduleis a “leaf” module.
Leaf modules are the atomic units that appear in the IR, referenced by
call_modulecalls. By default, Modules in the PyTorch standard library namespace (torch.nn) are leaf modules. All other modules are traced through and their constituent ops are recorded, unless specified otherwise via this parameter.
- Parameters
-
path_of_module(mod)[source]¶
Helper method to find the qualified name of
modin the Module hierarchy of
root. For example, if
roothas a submodule named
foo, which has a submodule named
bar, passing
barinto this function will return the string “foo.bar”.
trace(root, concrete_args=None)[source]¶
Trace
rootand return the corresponding FX
Graphrepresentation.
rootcan either be an
nn.Moduleinstance or a Python callable.
Note that after this call,
self.rootmay be different from the
rootpassed in here. For example, when a free function is passed to
trace(), we will create an
nn.Moduleinstance to use as the root and add embedded constants to.
- class
torch.fx.
Proxy(node, tracer=None)[source]¶
Proxyobjects are
Nodewrappers that flow through the program during symbolic tracing and record all the operations (
torchfunction calls, method calls, operators) that they touch into the growing FX Graph.
If you’re doing graph transforms, you can wrap your own
Proxymethod around a raw
Nodeso that you can use the overloaded operators to add additional things to a
Graph.
- class
torch.fx.
Interpreter(module)[source]¶
An Interpreter executes an FX graph Node-by-Node. This pattern can be useful for many things, including writing code transformations as well as analysis passes.
Methods in the Interpreter class can be overridden to customize the behavior of execution. The map of overrideable methods in terms of call hierarchy:
run() +-- run_node +-- placeholder() +-- get_attr() +-- call_function() +-- call_method() +-- call_module() +-- output()
Example
Suppose we want to swap all instances of
torch.negwith
torch.sigmoidand vice versa (including their
Tensormethod equivalents). We could subclass Interpreter like so:
class NegSigmSwapInterpreter(Interpreter): def call_function(self, target : Target, args : Tuple, kwargs : Dict) -> Any: if target == torch.sigmoid: return torch.neg(*args, **kwargs) return super().call_function(n) def call_method(self, target : Target, args : Tuple, kwargs : Dict) -> Any: if target == 'neg': call_self, *args_tail = args return call_self.sigmoid(*args_tail, **kwargs) return super().call_method(n) def fn(x): return torch.sigmoid(x).neg() gm = torch.fx.symbolic_trace(fn) input = torch.randn(3, 4) result = NegSigmSwapInterpreter(gm).run(input) torch.testing.assert_allclose(result, torch.neg(input).sigmoid())
- Parameters
module (GraphModule) – The module to be executed
call_function(target, args, kwargs)[source]¶
Execute a
call_functionnode and return the result.
- Parameters
-
- Return
Any: The value returned by the function invocation
call_method(target, args, kwargs)[source]¶
Execute a
call_methodnode and return the result.
- Parameters
-
- Return
Any: The value returned by the method invocation
call_module(target, args, kwargs)[source]¶
Execute a
call_modulenode and return the result.
- Parameters
-
- Return
Any: The value returned by the module invocation
fetch_args_kwargs_from_env(n)[source]¶
Fetch the concrete values of
argsand
kwargsof node
nfrom the current execution environment.
fetch_attr(target)[source]¶
Fetch an attribute from the
Modulehierarchy of
self.module.
get_attr(target, args, kwargs)[source]¶
Execute a
get_attrnode. Will retrieve an attribute value from the
Modulehierarchy of
self.module.
map_nodes_to_values(args, n)[source]¶
Recursively descend through
argsand look up the concrete value for each
Nodein the current execution environment.
output(target, args, kwargs)[source]¶
Execute an
outputnode. This really just retrieves the value referenced by the
outputnode and returns it.
placeholder(target, args, kwargs)[source]¶
Execute a
placeholdernode. Note that this is stateful:
Interpretermaintains an internal iterator over arguments passed to
runand this method returns next() on that iterator.
run(*args, initial_env=None)[source]¶
Run module via interpretation and return the result.
- Parameters
*args – The arguments to the Module to run, in positional order
initial_env (Optional[Dict[Node, Any]]) – An optional starting environment for execution. This is a dict mapping Node to any value. This can be used, for example, to pre-populate results for certain Nodes so as to do only partial evaluation within the interpreter.
- Returns
The value returned from executing the Module
- Return type
Any
- class
torch.fx.
Transformer(module)[source]¶
Transformeris a special type of interpreter that produces a new
Module. It exposes a
transform()method that returns the transformed
Module.
Transformerdoes not require arguments to run, as
Interpreterdoes.
Transformerworks entirely symbolically.
Example
Suppose we want to swap all instances of
torch.negwith
torch.sigmoidand vice versa (including their
Tensormethod equivalents). We could subclass
Transformerlike so:
class NegSigmSwapXformer(Transformer): def call_function(self, target : 'Target', args : Tuple[Argument, ...], kwargs : Dict[str, Any]) -> Any: if target == torch.sigmoid: return torch.neg(*args, **kwargs) return super().call_function(n) def call_method(self, target : 'Target', args : Tuple[Argument, ...], kwargs : Dict[str, Any]) -> Any: if target == 'neg': call_self, *args_tail = args return call_self.sigmoid(*args_tail, **kwargs) return super().call_method(n) def fn(x): return torch.sigmoid(x).neg() gm = torch.fx.symbolic_trace(fn) transformed : torch.nn.Module = NegSigmSwapXformer(gm).transform() input = torch.randn(3, 4) torch.testing.assert_allclose(transformed(input), torch.neg(input).sigmoid())
- Parameters
module (GraphModule) – The
Moduleto be transformed.
get_attr(target, args, kwargs)[source]¶
Execute a
get_attrnode. In
Transformer, this is overridden to insert a new
get_attrnode into the output graph.
placeholder(target, args, kwargs)[source]¶
Execute a
placeholdernode. In
Transformer, this is overridden to insert a new
placeholderinto the output graph.
torch.fx.
replace_pattern(gm, pattern, replacement)[source]¶
Matches all possible non-overlapping sets of operators and their data dependencies (
pattern) in the Graph of a GraphModule (
gm), then replaces each of these matched subgraphs with another subgraph (
replacement).
- Parameters
gm – The GraphModule that wraps the Graph to operate on
pattern – The subgraph to match in
gmfor replacement
replacement – The subgraph to replace
patternwith
- Returns
A list of
Matchobjects representing the places in the original graph that
patternwas matched to. The list is empty if there are no matches.
Matchis defined as:
class Match(NamedTuple): # Node from which the match was found anchor: Node # Maps nodes in the pattern subgraph to nodes in the larger graph nodes_map: Dict[Node, Node]
- Return type
List[Match]
Examples:
import torch from torch.fx import symbolic_trace, subgraph_rewriter class M(torch.nn.Module): def __init__(self): super().__init__() def forward(self, x, w1, w2): m1 = torch.cat([w1, w2]).sum() m2 = torch.cat([w1, w2]).sum() return x + torch.max(m1) + torch.max(m2) def pattern(w1, w2): return torch.cat([w1, w2]).sum() def replacement(w1, w2): return torch.stack([w1, w2]) traced_module = symbolic_trace(M()) subgraph_rewriter.replace_pattern(traced_module, pattern, replacement)
The above code will first match
patternin the
forwardmethod of
traced_module. Pattern-matching is done based on use-def relationships, not node names. For example, if you had
p = torch.cat([a, b])in
pattern, you could match
m = torch.cat([a, b])in the original
forwardfunction, despite the variable names being different (
pvs
m).
The
returnstatement in
patternis matched based on its value only; it may or may not match to the
returnstatement in the larger graph. In other words, the pattern doesn’t have to extend to the end of the larger graph.
When the pattern is matched, it will be removed from the larger function and replaced by
replacement. If there are multiple matches for
patternin the larger function, each non-overlapping match will be replaced. In the case of a match overlap, the first found match in the set of overlapping matches will be replaced. (“First” here being defined as the first in a topological ordering of the Nodes’ use-def relationships. In most cases, the first Node is the parameter that appears directly after
self, while the last Node is whatever the function returns.)
One important thing to note is that the parameters of the
patternCallable must be used in the Callable itself, and the parameters of the
replacementCallable must match the pattern. The first rule is why, in the above code block, the
forwardfunction has parameters
x, w1, w2, but the
patternfunction only has parameters
w1, w2.
patterndoesn’t use
x, so it shouldn’t specify
xas a parameter. As an example of the second rule, consider replacing
def pattern(x, y): return torch.neg(x) + torch.relu(y)
with
def replacement(x, y): return torch.relu(x)
In this case,
replacementneeds the same number of parameters as
pattern(both
xand
y), even though the parameter
yisn’t used in
replacement.
After calling
subgraph_rewriter.replace_pattern, the generated Python code looks like this:
def forward(self, x, w1, w2): stack_1 = torch.stack([w1, w2]) sum_1 = stack_1.sum() stack_2 = torch.stack([w1, w2]) sum_2 = stack_2.sum() max_1 = torch.max(sum_1) add_1 = x + max_1 max_2 = torch.max(sum_2) add_2 = add_1 + max_2 return add_2 | https://pytorch.org/docs/1.8.0/fx.html | CC-MAIN-2021-31 | refinedweb | 9,173 | 50.84 |
The K-nearest neighbors (KNN) algorithm is a type of supervised machine learning algorithms. KNN is extremely easy to implement in its most basic form, and yet performs quite complex classification tasks. It is a lazy learning algorithm since it doesn't have a specialized training phase. Rather, it uses all of the data for training while classifying a new data point or instance. KNN is a non-parametric learning algorithm, which means that it doesn't assume anything about the underlying data. This is an extremely useful feature since most of the real world data doesn't really follow any theoretical assumption e.g. linear-separability, uniform distribution, etc.
In this article, we will see how KNN can be implemented with Python's Scikit-Learn library. But before that let's first explore the theory behind KNN and see what are some of the pros and cons of the algorithm.
Theory
The intuition behind the KNN algorithm is one of the simplest of all the supervised machine learning algorithms. It simply calculates the distance of a new data point to all other training data points. The distance can be of any type e.g Euclidean or Manhattan etc. It then selects the K-nearest data points, where K can be any integer. Finally it assigns the data point to the class to which the majority of the K data points belong.
Let's see this algorithm in action with the help of a simple example. Suppose you have a dataset with two variables, which when plotted, looks like the one in the following figure.
Your task is to classify a new data point with 'X' into "Blue" class or "Red" class. The coordinate values of the data point are x=45 and y=50. Suppose the value of K is 3. The KNN algorithm starts by calculating the distance of point X from all the points. It then finds the 3 nearest points with least distance to point X. This is shown in the figure below. The three nearest points have been encircled.
The final step of the KNN algorithm is to assign new point to the class to which majority of the three nearest points belong. From the figure above we can see that the two of the three nearest points belong to the class "Red" while one belongs to the class "Blue". Therefore the new data point will be classified as "Red".
Pros and Cons of KNN
In this section we'll present some of the pros and cons of using the KNN algorithm.
Pros
- It is extremely easy to implement
- As said earlier, it is lazy learning algorithm and therefore requires no training prior to making real time predictions. This makes the KNN algorithm much faster than other algorithms that require training e.g SVM, linear regression, etc.
- Since the algorithm requires no training before making predictions, new data can be added seamlessly.
- There are only two parameters required to implement KNN i.e. the value of K and the distance function (e.g. Euclidean or Manhattan etc.)
Cons
- The KNN algorithm doesn't work well with high dimensional data because with large number of dimensions, it becomes difficult for the algorithm to calculate distance in each dimension.
- The KNN algorithm has a high prediction cost for large datasets. This is because in large datasets the cost of calculating distance between new point and each existing point becomes higher.
- Finally, the KNN algorithm doesn't work well with categorical features since it is difficult to find the distance between dimensions with categorical features.
Implementing KNN Algorithm with Scikit-Learn
In this section, we will see how Python's Scikit-Learn library can be used to implement the KNN algorithm in less than 20 lines of code. The download and installation instructions for Scikit learn library are available at here.
Note: The code provided in this tutorial has been executed and tested with Python Jupyter notebook.
The Dataset
We are going to use the famous iris data set for our KNN example. The dataset consists of four attributes: sepal-width, sepal-length, petal-width and petal-length. These are the attributes of specific types of iris plant. The task is to predict the class to which these plants belong. There are three classes in the dataset: Iris-setosa, Iris-versicolor and Iris-virginica. Further details of the dataset are available here.
Importing Libraries
import numpy as np import matplotlib.pyplot as plt import pandas as pd
Importing the Dataset
To import the dataset and load it into our pandas dataframe, execute the following code:
url = "" # Assign colum names to the dataset names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'Class'] # Read dataset to pandas dataframe dataset = pd.read_csv(url, names=names)
To see what the dataset actually looks like, execute the following command:
dataset.head()
Executing the above script will display the first five rows of our dataset as shown below:
Preprocessing
The next step is to split our dataset into its attributes and labels. To do so, use the following code:
X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 4].values
The
X variable contains the first four columns of the dataset (i.e. attributes) while
y contains the labels.
Train Test Split
To avoid over-fitting, we will divide our dataset into training and test splits, which gives us a better idea as to how our algorithm performed during the testing phase. This way our algorithm is tested on un-seen data, as it would be in a production application.
To create training and test splits, execute the following script:
from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20)
The above script splits the dataset into 80% train data and 20% test data. This means that out of total 150 records, the training set will contain 120 records and the test set contains 30 of those records.
Feature Scaling
Before making any actual predictions, it is always a good practice to scale the features so that all of them can be uniformly evaluated. Wikipedia explains the reasoning pretty well:.
The gradient descent algorithm (which is used in neural network training and other machine learning algorithms) also converges faster with normalized features.
The following script performs feature scaling:
from sklearn.preprocessing import StandardScaler scaler = StandardScaler() scaler.fit(X_train) X_train = scaler.transform(X_train) X_test = scaler.transform(X_test)
Training and Predictions
It is extremely straight forward to train the KNN algorithm and make predictions with it, especially when using Scikit-Learn.
from sklearn.neighbors import KNeighborsClassifier classifier = KNeighborsClassifier(n_neighbors=5) classifier.fit(X_train, y_train)
The first step is to import the
KNeighborsClassifier class from the
sklearn.neighbors library. In the second line, this class is initialized with one parameter, i.e.
n_neigbours. This is basically the value for the K. There is no ideal value for K and it is selected after testing and evaluation, however to start out, 5 seems to be the most commonly used value for KNN algorithm.
The final step is to make predictions on our test data. To do so, execute the following script:
y_pred = classifier.predict(X_test)
Evaluating the Algorithm
For evaluating an algorithm, confusion matrix, precision, recall and f1 score are the most commonly used metrics. The
confusion_matrix and
classification_report methods of the
sklearn.metrics can be used to calculate these metrics. Take a look at the following script:
from sklearn.metrics import classification_report, confusion_matrix print(confusion_matrix(y_test, y_pred)) print(classification_report(y_test, y_pred))
The output of the above script looks like this:
[[11 0 0] 0 13 0] 0 1
The results show that our KNN algorithm was able to classify all the 30 records in the test set with 100% accuracy, which is excellent. Although the algorithm performed very well with this dataset, don't expect the same results with all applications. As noted earlier, KNN doesn't always perform as well with high-dimensionality or categorical features.
Comparing Error Rate with the K Value
In the training and prediction section we said that there is no way to know beforehand which value of K that yields the best results in the first go. We randomly chose 5 as the K value and it just happen to result in 100% accuracy.
One way to help you find the best value of K is to plot the graph of K value and the corresponding error rate for the dataset.
In this section, we will plot the mean error for the predicted values of test set for all the K values between 1 and 40.
To do so, let's first calculate the mean of error for all the predicted values where K ranges from 1 and 40. Execute the following script:
error = [] # Calculating error for K values between 1 and 40 for i in range(1, 40): knn = KNeighborsClassifier(n_neighbors=i) knn.fit(X_train, y_train) pred_i = knn.predict(X_test) error.append(np.mean(pred_i != y_test))
The above script executes a loop from 1 to 40. In each iteration the mean error for predicted values of test set is calculated and the result is appended to the
error list.
The next step is to plot the
error values against K values. Execute the following script to create the plot:
plt.figure(figsize=(12, 6)) plt.plot(range(1, 40), zero when the value of the K is between 5 and 18. I would advise you to play around with the value of K to see how it impacts the accuracy of the predictions.
While reading blog posts like this is a great start, most people typically learn better with the visuals, resources, and explanations from courses like those linked above.
Conclusion
KNN is a simple yet powerful classification algorithm. It requires no training for making predictions, which is typically one of the most difficult parts of a machine learning algorithm. The KNN algorithm have been widely used to find document similarity and pattern recognition. It has also been employed for developing recommender systems and for dimensionality reduction and pre-processing steps for computer vision, particularly face recognition tasks.
From here, I would advise you to implement the KNN algorithm for a different classification dataset. Vary the test and training size along with the K value to see how your results differ and how can you improve the accuracy of your algorithm. A good collection of classification datasets is available here for you to play with.
What other applications have you applied the KNN algorithm to? How did it work out for you? Let us know in the comments! | https://stackabuse.com/k-nearest-neighbors-algorithm-in-python-and-scikit-learn/ | CC-MAIN-2019-35 | refinedweb | 1,763 | 55.95 |
Are you planning to learn core java? Or an interview is scheduled in coming days? Do not worry and read all questions given below to refresh your concepts and possibly have some new added in your best of java list.
How to create a immutable object in Java? Count all benefits? Is Java Pass by Reference or Pass by Value? What is the use of the finally block? Is finally block in Java guaranteed to be called? When finally block is NOT called? Why there are two Date classes; one in java.util package and another in java.sql? What is Marker interface? Why main() in java is declared as public static void main? What is the difference between creating String as new() and literal? How does substring() inside String works? Explain the working of HashMap. When do you override hashCode and equals() ?
How to create a immutable object in Java? Count all benefits?
An immutable class is one whose state can not be changed once created. Here, state of object essentially means the values stored in instance variable in class whether they are primitive types or reference types.
To make a class immutable, below steps needs to be followed:
- Don’t provide “setter” methods or methods that modify fields or objects referred to by fields. Setter methods are meant to change the state of object and this is what we want to prevent here.
- Make all fields final and private. Fields declared private will not be accessible outside the class and making them final will ensure the even accidentally you can not change them.
- Don’t allow subclasses to override methods. The simplest way to do this is to declare the class as final. Final classes in java can not be overridden.
- Always remember that your instance variables will be either mutable or immutable. Identify them and return new objects with copied content for all mutable objects (object references). Immutable variables (primitive types) can be returned safely without extra effort.
Also, you should memorize following benefits of immutable class. You might need them during interview. Immutable classes --
-.
Take a look an example written in this post.
Is Java Pass by Reference or Pass by Value?
The Java Spec says that everything in Java is pass-by-value. There is no such thing as “pass-by-reference” in Java. These terms are associated with method calling and passing variables as method parameters. Well, primitive types are always pass by value without any confusion. But, the concept should be understood in context of method parameter of complex types.
In java, when we pass a reference of complex types as any method parameters, always the memory address is copied to new reference variable bit by bit. See in below picture:
In above example, address bits of first instance are copied to another reference variable, thus resulting both references to point a single memory location where actual object is stored. Remember, making another reference to null will not make first reference also null. But, changing state from either reference variable have impact seen in other reference also.
Read in detail here:
What is the use of the finally block? Is finally block in Java guaranteed to be called? When finally block is NOT called?
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
Why there are two Date classes; one in java.util package and another in java.sql?.
Explain marker interfaces?
The marker interface pattern is a design pattern in computer science, used with languages that provide run-time type information about objects. It provides a means to associate metadata with a class where the language does not have explicit support for such metadata. In java, it is used as interfaces with no method specified.
A good example of use of marker interface in java is Serializable interface. A class implements this interface to indicate that its non-transient data members can be written to a byte steam or file system.
A major problem with marker interfaces is that an interface defines a contract for implementing classes, and that contract is inherited by all subclasses. This means that you cannot “un-implement” a marker. In the example given, if you create a subclass that you do not want to serialize (perhaps because it depends on transient state), you must resort to explicitly throwing NotSerializableException.
Why main() in java is declared as public static void?
Why public?.
Why static? Lets suppose we do not have main method as static. Now, to invoke any method you need an instance of it. Right? Java can have overloaded constructors, we all know. Now, which one should be used and from where the parameters for overloaded constructors will come.
Why void? Then there is no use of returning any value to JVM, who actually invokes this method. The only thing application would like to communicate to invoking process is: normal or abnormal termination. This is already possible using System.exit(int). A non-zero value means abnormal termination otherwise everything was fine.
What is the difference between creating String as new() and literal?
When we create string with new() it’s created in heap and also added into string pool, while String created using literal are created in String pool only which exists in Perm area of heap.
Well you really need to know the concept of string pool very deeply to answer this question or similar questions. My advise.. “Study Hard” about string class and string pool.
How does substring () inside String works?
String in java are like any other programming language, a sequence of characters. This is more like a utility class to work on that char sequence. This char sequence is maintained in following variable:
/** The value is used for character storage. */
private final char value[];
To access this array in different scenarios, following variables are used:
/** The offset is the first index of the storage that is used. */
private final int offset;
/** The count is the number of characters in the String. */
private final int count;
Whenever we create a substring from any existing string instance, substring() method only set’s the new values of offset and count variables. The internal char array is unchanged. This is a possible source of memory leak if substring() method is used without care. Read more here
Explain the working of HashMap. How duplicate collision is resolved?
Most of you will agree that HashMap is most favorite topic for discussion in interviews now-a-days. If anybody asks me to describe “How HashMap works?”, I simply answer: “On principles of Hashing”. As simple as it is.
Now, Hashing in its simplest form, is a way to assigning a unique code for any variable/object after applying any formula/ algorithm on its properties.
A map by definition is : “An object that maps keys to values”. Very easy.. right? So, HashMap has an inner class Entry, which looks like this:
static class Entry
{
final K key;
V value;
Entry
final int hash;
…//More code goes here
}
When, someone tries to store a key value pair in a HashMap, following things happen:
-- First of all, key object is checked for null. If key is null, value is stored in table[0] position. Because hash code for null is always 0.
-- Then on next step, a hash value is calculated using key’s hash code by calling its hashCode() method. This hash value is used to calculate index in array for storing Entry object. JDK designers well assumed that there might be some poorly written hashCode() functions that can return very high or low hash code value. To solve this issue, they introduced another hash() function, and passed the object’s hash code to this hash() function to bring hash value in range of array index size.
-- Now indexFor(hash, table.length) function is called to calculate exact index position for storing the Entry object.
-- Here comes the main part. Now, as we know that two unequal objects can have same hash code value, how two different objects will be stored in same array location [called bucket].
Answer is LinkedList. If you remember, Entry class had an attribute “next”. This attribute always points to next object in chain. This is exactly the behavior of LinkedList.
So, in case of collision, Entry objects are stored in LinkedList form. When an Entry object needs to be stored in particular index, HashMap checks whether there is already an entry?? If there is no entry already present, Entry object is stored in this location.
If there is.
Difference between interfaces and abstract classes?
This is very common question if you are appearing interview for junior level programmer. Well, most noticeable differences are as below:
- Variables declared in a Java interface is by default final. An abstract class may contain non-final variables.
- Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implements a default behavior.
- Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected.
- Java interface should be implemented using keyword “implements”; A Java abstract class should be extended using keyword “extends”.
- A Java class can implement multiple interfaces but it can extend only one abstract class.
- Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists.
- Abstract class are slightly faster than interface because interface involves a search before calling any overridden method in Java. This is not a significant difference in most of cases but if you are writing a time critical application than you may not want to leave any stone unturned.
When do you override hashCode() and equals()?
hashCode() and equals() methods have been defined in Object class which is parent class for java objects. For this reason, all java objects inherit a default implementation of these methods.
hashCode() method is used to get a unique integer for given object. This integer is used for determining the bucket location, when this object needs to be stored in some HashTable like data structure. By default, Object’s hashCode() method returns and integer representation of memory address where object is stored.
equals() method, as name suggest, is used to simply verify the equality of two objects. Default implementation simply check the object references of two objects to verify their equality.
Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.
equals() must define an equality relation (it must be reflexive, symmetric, and transitive). In addition, it must be consistent (if the objects are not modified, then it must keep returning the same value). Furthermore, o.equals(null) must always return false.
hashCode() must also be consistent (if the object is not modified in terms of equals(), it must keep returning the same value).
The relation between the two methods is:
Whenever a.equals(b), then a.hashCode() must be same as b.hashCode().
Happy Learning !!
14 thoughts on “Core java interview questions series : Part 1”
thanks this helped lot.
Hi Lokesh,
One of the interview, they asked me how to do sort in ascending order on String of characters after converting them into Ascii values and I answered in below mentioned way but he does not satisfied with my answer.Could you please tell me other way to do this.
I have coded like this.
public static String convert_String_To_Ascii(String numStr){
char ch[] = numStr.toCharArray();
int first=0;
int last=0;
StringBuffer asn=new StringBuffer();
for(int i=0;i<ch.length;i++)
{
first=(int) ch[i];
for(int j=i;jlast)
{
char temp=(char)first;
first=last;
ch[i]=(char)last;
ch[j]=temp;
}
}
}
return new String(ch);
}
What about below?
String s = “some-string-here”;
byte[] bytes = s.getBytes(“US-ASCII”);
Arrays.sort(bytes);
It’s sort and easy to read. Your’s is also correct.
In this page you mentioned:
When we create string with new () it’s created in heap and not added into string pool
and in you have mentioned:
==================================
2) Using new keyword
String str = new String(“abc”);
This version end up creating two objects in memory. One object in string pool having char sequence “abc” and second in heap memory referred by variable str and having same char sequence as “abc”.
==================================
Isn’t it contradictory to each other?
Hey Sumeet, Good catch. It was a typo (sometimes happen when you type so much text). Thanks for pointing out and I have corrected that.
To put more focus on topic, When you use new keyword and pass a String parameter then that parameter is actually a String literal and string literal in string pool gets created even before your String() constructor is called. So, on runtime when constructor is called, you get your second object in heap area.
“Compile-time constant expressions of type String are always “interned” so as to share unique instances, using the method String.intern”
Source:
Hi, thank you for your post, very nice!
At the question: “Why there are two Date classes; one in java.util package and another in java.sql?”
When you say : “So, what changed in java.sql.Date: [...] the getters and setter for hours, minutes and seconds are deprecated” I feel it’s a bit misleading, because in the original java.util.Date class, those methods are already deprecated, but it’s just not for the same reasons.
You caught me on wrong foot.-
OK, it can be misleading. So let’s me clarify again.
Methods in java.util.Date were gone deprecated because of Calendar class was considered recommended approach. So, util’s Date class’s multiple methods were marked as deprecated.
e.g. setMinutes(int minutes) :: Deprecated. As of JDK version 1.1, replaced by Calendar.set(Calendar.MINUTE, int minutes).
But, in java.sql.Date class it was deprecated because they are (though not enforced) conceptually discouraged.
e.g. setMinutes(int i) :: Deprecated. This method is deprecated and should not be used because SQL Date values do not have a time component.
I like this answer
Thx!
Great list dude. Keep it up the writing.
Thanks for sharing it.
public class FinallyReturnVariableAlter
{
public static void main(String[] args)
{
System.out.println(test());
}
public static int test()
{
int i=0;
try
{
return i;
}
finally
{
i+=100;
}
}
}
why the return value is 0 instead of 100?
Manohar, This is really good question and most fail to answer it correctly. Let me put my reasoning.
Every function call in java leads to creation of extra memory space created where return value is stored for reference after function execution completes and execution return to caller function back.
At that time, that special memory address where return value is stored, if referenced back as return value of function.
Here, trick is, the memory slot store the value of returned value, not its reference. So, once any return statement is encountered its value is copied in memory slot. That’s why if you change the value of “i” in finally, return value does not change because its already copied to memory slot.
We any other return statement is encountered (e.g. in finally block), its value will be overwritten again. So, it you want to return 100, use return statement in finally also.;
Hi Lokesh
certainly I will go thr’ questions but tell me java code to connect to
hsqldb .I am getting user lacks privilege or object not found: EMPLOYEEDETAILS exception
pl help me
Are you using hibernate.. match your properties..
Note:- In comment box, please put your code inside [java] ... [/java] OR [xml] ... [/xml] tags otherwise it may not appear as intended. | http://howtodoinjava.com/2013/03/01/core-java-interview-questions-series-part-1/ | CC-MAIN-2014-41 | refinedweb | 2,742 | 66.74 |
Computer Science Archive: Questions from February 16, 2013
- FlexibleBroccoli7753 askedAn online retailer has hired you to write a program to calculate the total cost of a customer's purc... More »3 answers
- GoldenRabbit131 asked1 answer
- starterkit123 asked4 answers
- ysfysf askedWhat is the critical implication for the security of the encryption key that differs between symmetr... More »4 answers
- MassiveStudent8775 askedSuppose you were writing a program that was designed to check both the grammar of English sentences ... More »1 answer
- ElegantCircle7547 askedCreate a function that determines and dislays if an integer is odd or even, call it in main by passi... Show more
Create a function that determines and dislays if an integer is odd or even, call it in main by passing the input integer from user.• Show less4 answers
- Devildog2413 asked1 answer
- ysfysf asked2 answers
- Devildog2413 asked1 answer
- ElegantCircle7547 askedCreate a function that determines the argument is a capital letter or a small letter or not a letter... Show more
Create a function that determines the argument is a capital letter or a small letter or not a letter. Call it in main to test an input character from user.• Show less1 answer
- NoisyJourney5498 asked, which returns a value that is half... Show more
The following pseudocode statement calls a function named half, which returns a value that is half that of the argument. (Assume both the result and number variables are Real.) Write pseudocode for the function.
Set result = half(number)• Show less3 answers
- NoisyJourney5498 askedargument. When the function is called, it s... Show more
Design a function named timesTen that accepts an Integerargument. When the function is called, it should return the value of its argument multiplied times 10.• Show less3 answers
- NoisyJourney5498 asked1. Find the error in the following code that is supposed to display three random numbers in the rang4 answers
- NoisyJourney5498 askedDesign a program that gives simple math quizzes. The program should display two random num... Show more
Math Quiz
Design mes-sage showing the correct answer should be displayed. Please place the pseudocode below.
• Show less3 answers
- NoisyJourney5498 askedDesign a function named max that accepts two integer values as arguments and r... Show more
Maximum of Two Values
Design a function named max that accepts two integer values as arguments and re-turns the value that is the greater of the two. For example, if 7 and 12 are passed as arguments to the function, the function should return 12. Use the function in a program that prompts the user to enter two integer values. The program should display the value that is the greater of the two. Please place the pseudocode below.• Show less3 answers
- PreciseToast2425 askedto determine a letter grade based on the following grade scale: A 90 and above... Show more
designRaptor flowchartto determine a letter grade based on the following grade scale: A 90 and above B 80 – 89 C 70 – 79 D 60 – 69 F less than 60
• Show less3 answers
- ElegantCircle7547 askedUse C language to create a function that compares two arguments and returns the larger one. Call it... Show more
Use C language to create a function that compares two arguments and returns the larger one. Call it in main by passing two input integers.• Show less4 answers
- BitterPony4634 asked5 answers
- GotWhatYouNeed askedTester that... Show more
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Tester that needs to be changed
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
public class InventoryTracker {
public static void main(String[] args) {
//create 7 new books/games
InventoryItem[] inventory = new InventoryItem[7];
inventory[0] = new ComicBook(2, 100., "Superman", 2);
inventory[1] = new BoardGame(3, 39.95, "AwfulGreenThings from Outer Space");
inventory[2] = new BoardGame(10, 29.95, "Monopoly");
inventory[3] = new ComicBook(10, 9.95, "Buffy the Vampire Slayer", 12);
inventory[4] = new ComicBook(12, 8.95, "X-men", 119);
inventory[5] = new BoardGame(9, 59.99, "Scrabble");
inventory[6] = new ComicBook(8, 21.98, "The Amazing Spiderman: Original Series,", 20);
for(int i = 0; i<inventory.length; i++) {
System.out.println(inventory[i]);
}
//calculations
InventoryItem maxvalue = inventory[0];
InventoryItem minvalue = inventory[0];
int inventoryQty = 0;
double inventoryValue = 0;
for(int i=0; i<inventory.length; i++)
{
inventoryQty += inventory[i].getQuantity();
double currentValue = inventory[i].getQuantity() * inventory[i].getRetailPrice();
if(currentValue < minvalue.getQuantity() * minvalue.getRetailPrice())
minvalue = inventory[i];
if(currentValue > maxvalue.getQuantity() * maxvalue.getRetailPrice())
maxvalue = inventory[i];
inventoryValue += currentValue;
}
//print results
System.out.println("\nTotal Inventory Quantity (num items):" + inventoryQty);
System.out.println("Total Inventory Value:" + inventoryValue);
System.out.println("Inventory Item with Max Value of " + (maxvalue.getQuantity() *maxvalue.getRetailPrice()) + " is: " + maxvalue);
System.out.println("Inventory Item with Min Value of " + (minvalue.getQuantity() *minvalue.getRetailPrice()) + " is: " + minvalue);
}
}
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||• Show less1 answer
- LuckyHippo301 askedWrite a C program that prompts the user to enter the number of quiz scores from 1-13. Check to see i... More »2 answers
- GoldenRabbit131 asked1 answer
- Lookingforhelp asked2 answers
- LuckyMouse3406 askedProve that F is not... Show more
Fk(x) is defined from n bits to n bits, with keys of n bits and
Fk(x) = k XOR x
Prove that F is not a pseudorandom function by describing a polynomial-time attack algorithm that wins the PRF game with more than negligible advantage. Show the advantage.• Show less1 answer
- BitterPony4634 askedI wanna provide the user a message to enter the element of the array list, but I do not know how man... More »1 answer
- totaaa askedWhat is the difference between disclosure and disruption on computer security? please give me a sma... More »1 answer
- GreedyCheese8015 asked1 answer
- CameronBarnes1993 asked2 answers
- SillySand232 askedEveryone- What is a copy constructor? When would you use a copy constructor? Can you give an exampl... More »2 answers
- babalu askedImplementing your program You are not expected to develop a graphical user interface as in the abov... More »1 answer
- CoffeeRustyNotSoMuch askedDetermine the minimum number and the maximum number of red nodes in a red-black tree with 10 keys (i... More »0 answers
- CoffeeRustyNotSoMuch askedAssume that within each node of a binary search tree we store also the height of the pending subtree... More »0 answers
- BraveAsteroid1024 askedWrite a program that dynamically allocates a vector large enough to hold any number of scores the us... More »1 answer
- ColossalPrince5365 askeda) (p --> q) ? (NOT p OR q) b) p --> (q --> (r OR NOT p) c) (p OR q) --> (p AND q) I am con... More »2 answers
- GreedyMarble6633 askedName and describe the only language that computers understand and explain how the instructions that ... More »2 answers
- PreciseToast2425 askedCreate a Raptor flowchart file called “ColorMixer.rap” that implements a solution to the assigne... More »0 answers
- BoomShakalaka asked1 answer
- BraveAsteroid1024 askedWrite a program that dynamically allocates a vector large enough to hold any number of scores the us... More »1 answer
- BoomShakalaka askedisPalindrome(w) { if (w is empty string or w is of length 1) return true; else if (w’s first... More »1 answer
- GreedyCheese8015 asked0 answers
- stelladog askedImplement a program that reads in a user password and verifies it meets the following criteria: •... More »1 answer
- ModernCloud4066 askedlet A= 445598 B=43561134 C= 567 D =0987 E=3456 write a java code that reads numbers from a text fi... More »1 answer
- SwiftLion4820 askedDesign and implement a class dayType that implements the day of the week in a program. The class da... Show more
Design and implement a class dayType that implements the day of the week in a program. The class dayType should store the day, such as Sun for Sunday. The program should be able to preform.
write the definitions of the functions to implement the operations for the class dayType as defined in programming exercise 2. also write a program to test various operations on this class.
this is what is have coded so far. i'm working on fixig the errors right now but i figure i'll ask anyways.
#include "stdafx.h"
#include<iostream>
#include<cmath>
using namespace std;
//class declaration
{
public: int presday;
int prevday;
int nextday;
dayType ()
{
Presday=0;
nextday=0;
prevday=0;
}
void set (int day); //function declarations
void print (int day);
int Next_day (int day);
int day();
int prev_day (int pres);
};
void dayType::set (int day) //member functions
{
presday=day;
}
int dayType::prev_day(int day)
{
prevday =abs(presday-day);
return prevday;
}
int dayType::day()
{
return presday;
}
int dayType::Next_day(int day)
{
nextday=presday+day;
if(nextday>7)
{
nextday=nextday%7;
}
return nextday;
}
void dayType::print(int d)
{
if(d==1)
cout<<"Monday"<<endl;
if(d==2)
cout<<"Tuesday"<<endl;
if(d==3)
cout<<"Wednesday"<<endl;
if(d==4)
cout<<"Thursday"<<endl;
if(d==5)
cout<<"Friday"<<endl;
if(d==6)
cout<<"Saturday"<<endl;
if(d==7)
cout<<"Sunday"<<endl;
}
void main()
{
int d,p,n;
dayType obj;
cout<"1-Mon"<<endl<<"2-Tue"<<endl"3-Wed"<<endl"4-Thur"<<endl"5-Fri"<<endl"6-Sat"<<endl"7-sun"<<endl;
cout<<"Enter Day";
cin>>d;
obj.set(d);
cout<<"Present day is";
obj.print(d);
cout<<"Enter number of days next";
cin>>d;
n=obj.Next_day(d);
cout<<"Next day is";
obj.print(n);
cout<<"Enter number of days previous";
cin>>d;
p=obj.prev_day(d);
cout<<"previous day is";
obj.print(P);
system("Pause");
}
Errors i'm getting: {' : missing function header (old-style formal list?)
error C2653: 'dayType' : is not a class or namespace name
error C2065: 'presday' : undeclared identifier
error C2653: 'dayType' : is not a class or namespace name
error C2065: 'prevday' : undeclared identifier
error C2065: 'presday' : undeclared identifier
error C2065: 'prevday' : undeclared identifier
error C2653: 'dayType' : is not a class or namespace name
error C2065: 'presday' : undeclared identifier
error C2653: 'dayType' : is not a class or namespace name
error C2065: 'nextday' : undeclared identifier
error C2065: 'presday' : undeclared identifier
error C2065: 'nextday' : undeclared identifier
error C2065: 'nextday' : undeclared identifier
error C2065: 'nextday' : undeclared identifier
error C2653: 'dayType' : is not a class or namespace name
error C2065: 'dayType' : undeclared identifier
error C2146: syntax error : missing ';' before identifier 'obj'
error C2065: 'obj' : undeclared identifier
error C2563: mismatch in formal parameter list
error C2568: '<<' : unable to resolve function overload //i have no idea what the heck this mean
1> c:\program files (x86)\microsoft visual studio 11.0\vc\include\ostream(1037): could be 'std::basic_ostream<_Elem,_Traits> &std::endl(std::basic_ostream<_Elem,_Traits> &)'
1> with
1> [
1> _Elem=unsigned short,
1> _Traits=std::char_traits<unsigned short>
1> ]
Thanks• Show less1 answer
- aSmith101 askedIn the class definition -Add private data member int Scores[100] -Add private data member int Leng... More »1 answer
- samici24 askedCreate an application in a JFrame window that decodes or encodes a message using your classes from P... More »0 answers
- mpg2013 askedIn this lab, you will create a resizeable array of 2D points and perform various operations on them.... More »0 answers
- Anonymous asked1) Suppose that intArray is an array of integers, and length specifies the number of elements in int0 answers
- Anonymous asked2 answers
- CarefulCamel6287 askedthis application displays the definitions of common visual basic terms. when the user chooses the vi... More »1 answer
- CarefulCamel6287 askedthis application displays the definitions of common visual basic terms. when the user chooses the vi... More »1 answer
- rediks askedPART I: (Shows the query only) Consider the following relations: Student(snum: integer, sname: s... More »0 answers
- rediks asked0 answers
- VoluminousCheese5978 askedAsk the user to input a height using th... Show more
3 answers
Ask the user to input a radius using the following text:
Ask the user to input a height using the following text:
Write code to calculate:
The surface area of a cylinder with the given radius and height
The volume of a cylinder with the given radius and height
The surface area of a cone with the given radius and height
The volume of a cone with the given radius and height
Print the calculated surface area of the cylinder using the following text:
Print the calculated volume of the cylinder using the following text:
Print the calculated surface area of the cone using the following text:
Print the calculated volume of the cone using the following text:
- Anonymous askedSuppose that two registers contain the following hexadecimal values: AB0890C2, 4598EE50. What is... More »0 answers
- AnimatedChicken4696 asked1 answer
- AnimatedChicken4696 askedBreakeven analysis determines the production volume at which the total production cost is equal to ... More »0 answers
- AnimatedChicken4696 askedThe perfect gas law relates the pressure p, absolute temperature T, mass m, and volume V of a gas. I... More »0 answers
- LazyPony520 asked2 answers
- LazyPony520 askedwhat is the average access time for a hard disk spinning at 360 revolutions per second with a seek t... More »1 answer
- LazyPony520 askedIf each sector on a magnetic disk contains 1024 bytes how many sectors are require to store? a sing... More »1 answer
- totaaa askedconsider usurpation - unauthorized control of service, xyz. which security components help deal with... More »2 answers
- SwankyMeteor3375 askedHow do I get 20 random integers from the following code stored into a... Show more
li $a1, 100
li $v0, 42
syscall
How do I get 20 random integers from the following code stored into an array where I can then use a sorting method?
This is what I am working for in the end:
Write a MIPS program to complete the following functions. You must write comments and follow the register convention. [30 points]
(1) Declare an integer array of 20 elements and other variables and labels; [5]
(2) Write a procedure to initialize the array. Use random numbers between 0 and 99, and use a loop to initialize the array. [10]
(3) Implement a sort procedure. You can use the sort procedure given in textbook 2.1.3. [5]
(4) Write the main program. It calls the initialization procedure; prints the numbers in the array; calls the sort procedure to sort the numbers in the array; and print the numbers in the sorted array. [10]• Show less0 answers
- LazyPony520 askedsuppose a typist could type 60 words per minute continuously day after day. how long would it take t... More »1 answer
- LazyPony520 asked1 answer
- UptightTiger7895 askedWhat is the legality of monitoring software that is used to track online conversations, emails, chat... More »1 answer
- Cinderbutter askedThe questions refer to the array diabetics which is a 10 x 4 array containing number of diagnosed di... More »1 answer
- aSmith101 askedIn the class definition -Add private data member int Scores[100] -Add private data member int Leng... More »1 answer
- Cinderbutter askedCalculate the MSE and RMS for the following ordered pairs for the linear model y= x-1. Show your wo... Show more
Calculate the MSE and RMS for the following ordered pairs for the linear model y= x-1. Show your work in tabular form.
• Show less0 answers
- CapableFridge4717 askedFile Guessing.java contains a skeleton of a program that plays a simple guessing game with the user.... More »2 answers
- MagicalSquare516 askedI have to find all the errors to make this program run in C++: #include // We will use cents for all... More »1 answer
- babalu askedOne-D Arrays and functions: Complete the following program. You will mainly implement the MERGE func... More »2 answers
- LiltCow askedTwo positive integers (A and B) will be considered “similar” if A <= X * B and B <= X * A ... More »4 answers
- babalu askedOne-D Arrays and functions: Complete the following program. You will mainly implement the MERGE func... More »2 answers
- MammothComb52 askedVector, Iterator, and Algorithm Write a program that creates a vector and the necessary iterators... More »1 answer
- infamousKnight22 askedI am creating a simple program that finds the factors of a number. I then add the factors up to get ... More »1 answer
- SAB2305 askedIn this assignment you will create a linked list in the HEAP and implement algorithms for manipulati... More »1 answer
- Zero11 askedA TCP segment consisting of 1500 bits of data and 160 bits of header is sent to the IP layer, which... More »2 answers
- hasbar askedA comparison is correct only when the correct ____ and operator are used. A) expression B) oper... More »6 answers
- Zero11 askedA broadcast network is one in which a transmission from anyone attached station is received by all ... More »1 answer
- hasbar askedOnce your logic enters the body of a structured loop, ____. A) the entire loop must execute B) th... More »6 answers
- TheVolcano7431 askedWrite a JAVA program with the following: 1. Accepts user input for tracking their name, age, and ... More »2 answers | http://www.chegg.com/homework-help/questions-and-answers/computer-science-archive-2013-february-16 | CC-MAIN-2015-27 | refinedweb | 2,719 | 54.42 |
That's what one of my web focused customers asked recently. I thought about it and I came to the conclusion, that Visual Studio 2008 provides a great balance between higher productivity and risk mitigation. Read more at: Visual Studio 2005 or 2008? What's more risk?
As Tim announced last week, Silverlight 1.0 Release Candidate 1 is live.
Now if you're wondering how you and the users of your Silverlight apps are seamlessly getting from RC to RTM and beyond to take advantage of new features and security updates, you can find the details in my post at:
Are you still writing deserialization classes for XML types? Don’t you just want to copy an example XML document and have Visual Studio auto generate the deserialization class?
Steve Maine just showed this little tool that’s currently available in the BizTalk Services SDK that takes an instance doc like this:
<bla>
<foo />
</bla>
Then you select Paste XML as Serializable Type from the Edit Menu in VS (2005 or Orcas):
And you’ll get a class to deserialize the document:
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", ElementName = "bla")]
public class BlaClass
{
private string fooField;
[System.Xml.Serialization.XmlElementAttribute(Namespace = "", ElementName = "foo")]
public virtual string Foo
{
get
{
return this.fooField;
}
set
this.fooField = value;
}
}
You can find the tool at:
C:\Program Files\BizTalk Services SDK\Samples\Web\Tooling
Enjoy,
Christoph
A customer recently requested a briefing on a list of topics related to Team Foundation Server (TFS) and Visual Studio Team System (VSTS). In response, we had a LiveMeeting call, during which I used the attached slide deck as the talking points.
Since many of my architect contacts have shown interest in these and other TFS and VSTS topics, I'm publishing the slides here. Their primary value is in the many links they give to deeper material. Also, I attached the excellent whitepaper on System Definition Model, since it can be a little hard to find.
A couple of years ago I was showing a customer how to configure ASP.NET for use in a web farm. Part of the procedure requires you to adjust the <machinekey> element in each server to the same settings, so that the ASP.NET encryption logic is using the same keys throughout the farm.
MSDN article KB312906 showed a simple command-line utility for generating the keys, but I wanted something more like the CreateGuid utility included with Visual Studio. Therefore, I wrote a WinForm version of the KB utility that I call CreateMachineKey and gave it to my customer and a few other folks who heard about it.
Recently I revisited CreateMachineKey in order to update it for ASP.NET 2.0, which has some significant changes that are described in a Patterns & Practices document. Since I had the code open on the operating table, I decided to zip it up and make it available via this blogsite. It's attached to this article, and I hope you find it useful.
For those of you who are really picky: Yes, I know CreateMachineKey doesn't support MD5, but that wasn't necessary for my purposes. However, if you decide to add that feature, please post it in a comment. Likewise if you find any bugs, although I doubt that's even possible. :-)
Dave SchmittJuly 20, 2006
A customer recently sent me a long list of questions with a generally skeptical tone. Since I spent a good deal of time generating a written response, I thought it would be useful to share it with readers of this blog.
Note that this is my representation of Microsoft’s history and policies, based on many years as a Microsoft-focused customer, teacher, writer, and now as a Microsoft employee. Any errors are mine alone, and I would appreciate you pointing them out to me.
Dave Schmitt
July, 2006
Questions for Microsoft
Platform Independence and Portability
Security
Time to Market and Tool Set Productivity
Scalability and Performance
Maintainability and Complexity
Longevity of Product and Company
The new MSDN Wiki encourages contributions from users in order to improve the documentation of Visual Studio and other developer products. I decided to give it a try and so I tacked my words of wisdom onto the LoginView class description. It’s something unusual that I discovered while showing a customer architect how .NET 2.0 simplifies declarative role checking.
This is a pretty cool way to contribute our discoveries to the MSDN documentation without going through a lengthy publishing process.
I just posted a blog about Microsoft Unified Communications strategy we just unveiled:
- hanuk
Look at my blog entry for high level information on our recent WinFX rebranding: WinFX rebranded as .NET Framework 3.0!
Based
Well, my first team blog entry. I work with Dave, whom you've met, except I cover MN, ND, SD, Iowa and Nebraska. I cover most accounts in those states with the exception of some of our big retail and healthcare accounts.
Ever since the idea of a team blog was floated around I've been thinking about what I'd write. Do I try to impress people and write some great posting on the next greatest technology? Give my two cents on upcoming products such as Origami? Why does anyone want to read what I have to say? Hmmm. Well, so what I came up with is I will blog mostly about two things.
The first is, as I get customer questions that I think others would be interested in hearing the answers, I'll try to take the time to post that here as well. It might be something interesting I come across that I want to tell people about or it might be on something specific like can you use ADFS for active client protocol.
The other, well, here is the deal. It's a fact that I'm different than all of the architects I meet with. Yes, I wear pink and I'm not going to stop. Yes, I hold events and quite often, I'm the only woman. I go to customers and I'm the only woman. Oh wait, every once and a while there is a project manager or an admin who is taking notes in the room to keep me company. Ugh! So, I might occasionally post on how it sucks that if I were male, I'd be in the bar networking over scotch, but since I'm not, I just get face time at lunch. Or I might touch on other aspects on the softer side of architecture like how you need to influence people to get them on board with your architecture. Enough on that for now...
I'll leave you with one final tidbit. We're nearing the launch and RTM of TFS. If you haven't seen it, check it out! It is one of the more exciting technologies we're releasing from a development improvement perspective. I can't wait to see what customers do with customizing it.
Jacquelyn
D.
Welcome to our team blog. We created this site in order to share the experiences and insights of the Microsoft Architect Evangelists who serve the United States Central Region.
This idea was suggested by Microsoft customers who attended our Central Region Architect Forum during the past few years. The interactive roundtable discussions proved to be the most popular part of the forum, and many attendees suggested that we find some way to continue these discussions throughout the year.
MSDN blogging looks like the answer, so we hope this site will become a popular place for architects to share information. We welcome any and all suggestions for improving this site.
Trademarks |
Privacy Statement | http://blogs.msdn.com/craeblog/default.aspx | crawl-002 | refinedweb | 1,286 | 62.58 |
Composite Number Sum Error
New to sage, although familiar with a few other coding langages. Trying to obtain a sum of alternating terms. Any idea on this one? Thanks in advance.
def a(n) : return [k for k in (1..n) if not is_prime(k)] from mpmath import * mp.dps = 15 mp.pretty = True nsum(lambda n: (1)/(a(n)), [1,5000], method='alternating')
Error Received:
TypeError: unable to coerce <type 'sage.libs.mpmath.ext_main.mpf'> to an integer
What sum are you trying to compute?
OEIS A269229. The sum of ((-1)^n) / x(n) where x(n) is the next composite (non-prime) number. | https://ask.sagemath.org/question/34100/composite-number-sum-error/ | CC-MAIN-2017-17 | refinedweb | 105 | 62.64 |
..
We have also used Bluetooth module HC-06 in our previous project: Voice controlled LEDs using Raspberry Pi. Also check our previous Raspberry Pi Projects along with some good IoT Projects.
Installing Required Packages for Bluetooth Communication:
Before start, we need to install some softwares. But before that, connect your USB Bluetooth dongle with Raspberry Pi and check that whether it is detected or not, by using below command:
lsusb
our Video given at the end.
As told earlier, you can also use Desktop interface to pair the Mobile phone. After installing Blueman, you will see a Bluetooth icon in right side of your Raspberry Pi desktop as shown below, using which you can easily do the pairing.
Circuit Diagram:
Circuit diagram is very simple, we just connected a LED to PIN 40 (GPIO 21) of Raspberry Pi with a resistor of 220 Ohm:
Controlling LED with Android App BlueTerm:
Now after paring the Mobile Phone, we need to install a Android App for communicating with Raspberry Pi using a Bluetooth Serial Adapter. switch ON and OFF the LED connected to this pin. Press ‘q’ to exit the program. You can use Google Voice Typing Keyboard to control the GPIO using your Voice. Check the complete demo in the Video given at the end.
So this is how you can wirelessly control the GPIO Pin)()
All the other code is easy and self-explanatory. Check the full code below. Try to modify this project and you can use it to control many other things wirelessly, like using Relays you can control the home appliances or can also control a Robot car through android phone.()
May 09, 2017
I can't seem to get the pairing to work. When I type in "pair" and then the address that comes up for my phone, i get the error "org.bluez.error.AlreadyExists". Any help for how to work this would be very much appreciated.
Aug 19, 2017
Unpair the device before you try to connect
Sep 05, 2017
nice work. I couldnt type anything in Blue term app ??
can i get rid of it ?
Sep 06, 2017
Yes you can use any Bluetooth App on your mobile. "Bluetooth Terminal" is also a good app
Nov 22, 2017
Hey,
I've tried with python, its working perfectly. But when I switch to python3 its telling that import bluetooth no module found
Nov 30, 2017
can I know what is the full name of the usb Bluetooth dongle type that being use? I plan to buy it.
Dec 14, 2017
What should I do if the message is "org.bluez.Error.Blocked"?
Dec 19, 2017
hi
i am getting error in this code plz anyone assist me to know about it
error is below
Traceback (most recent call last):
File "/home/pi/bluetooth.py", line 1, in <module>
import bluetooth
File "/home/pi/bluetooth.py", line 10, in <module>
server_socket=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
AttributeError: module 'bluetooth' has no attribute 'BluetoothSocket'
Dec 21, 2017
Did you download the bluetooth librarey? If not follow these steps below, you should enter these commands on your cmd promt
we need python Library for Bluetooth communication so that we can send and receive data through RFCOMM using Python language:
Also install the GPIO support libraries for Raspberry Pi:
Jul 10, 2018
even i have same attribute error: module 'bluetooth, has no attribute 'bluetoothsocket'
have you fixed this error
Dec 22, 2017
Can you help me with this message? thank you
pi@raspberrypi:~ $ sudo python GpioOverBluetooth.py
Traceback (most recent call last):
File "GpioOverBluetooth.py", line 13, in <module>
server_socket.bind(("",port))
File "/usr/lib/python2.7/dist-packages/bluetooth/bluez.py", line 140, in bind
return self._sock.bind (addrport)
_bluetooth.error: (98, 'Address already in use')
Jul 26, 2018
I have had same issues.
plz help us....
Jan 10, 2018
can you help me with this message?
connect failed-no usable services on this device android
Mar 03, 2018
you made my day.
i start study raspberry pi on yesterday.
i made pi communicate to smartphone over the HTTP it work fine then i think may it drain the battery
so i use my day looking for tutorial, watch video, read article do follow instruction so many hours with no lucky.
then i found you in YouTube that link to here, and it works!
so thank you.
PS. I'm java(Webapp)Developer
Aug 10, 2018
Good to know that you got it working.
I wanted to know can you send strings from app to pi.
May 08, 2018
server_socket.bind(("",port))
File "/usr/lib/python2.7/dist-packages/bluetooth/bluez.py", line 140, in bind
return self._sock.bind (addrport)
_bluetooth.error: (98, 'Address already in use')
I tried a lot but I was getting this error repeatedly. If anyone has the solution please do reply here.
Thank you in advance.
May 17, 2018
I was having the same issue.
Only worked for me when I wrote the MAC Adress of my device between the quotation marks on the line:
server_socket.bind(("",port))
I suspect that is something related to the use of Wifi and Bluetooth simultaniously.
Jul 08, 2018
even after i copied my mac address it is showing the same error
May 16, 2018
Nothing happens when trying to connect via BlueTerm.
After pressing Ctrl+C on RP terminal, got the following lines:
Traceback (most recent call last):
File "GPIO_Bluetooth.py", line 17, in <module>
client_socket,address = server_socket.accept()
File "/usr/local/lib/python2.7/dist-packages/bluetooth/bluez.py", line 167, in accept
client, addr = self._sock.accept ()
KeyboardInterrupt
May 17, 2018
hey guys,
my phone is conected with the pi, it is ok, but when i press the numbers, in my python shell shows Received: b'1'
Received: b'0'
can anyone help me with this?
Oct 07, 2018
I had the same problem. I got it working by changing this: if (data == "0") by this: if (data == b'0').
I hope it works for you too!!!!
Jun 01, 2018
Will this work in Raspberry pi 3, if I want to use the internal bluetooth?
what if I want to us the internal bluetooth and the external UART port(TTYAMA0) for a GSM module simultaneously. What should I do? Someone please hekp me with this.
Thanks in advance.
Oct 07, 2018
Yes, it will perfectly work on Raspberry pi 3 internal Bluetooth, I have one and I made it work. Thing is that Rpi has only one UART interface: UART0. So you would have to choose between Bluetooth or the UART port. Anyway, you could buy a USB to UART controller and use it for the GSM module, and use at the same time the internal Bluetooth.
Hope it helps!!! | https://circuitdigest.com/microcontroller-projects/controlling-raspberry-pi-gpio-using-android-app-over-bluetooth | CC-MAIN-2019-39 | refinedweb | 1,128 | 74.08 |
Is this what is meant by one to many mapping?
Originally posted by eammon bannon: I'm trying to understand why you'd want to map a 25 field DB table as an array of Strings - what is it you want to achieve? You don't map things in Hibernate that way.
Originally posted by Drew Lane: So what would be the best way to map this information using Hibernate?
Sorry, I'm not the best with databases.
Originally posted by Lasse Koskela: Making "(name, address, city, state, email, etc.)" into a class and mapping that class (its fields) into the database schema.
Originally posted by eammon bannon:
public class DAOEmail {
public EmailDto createEmail(String[] contents) {
Session session = sessionFactory.openSession();
HibEmail hibernatePOJO = new HibEmail();
hibernatePOJO.setField1(contents[0]);
....
session.save(hibernatePOJO, PK);
}
Very, very over simplified and obviously that won't even compile, but you get the idea? My biggest worry is how fixed the 25 element array is - you certainly want some validation on the input methods to stop 26 and 24 (and so on) element arrays being accepted. | http://www.coderanch.com/t/214787/ORM/databases/String-columns | CC-MAIN-2015-18 | refinedweb | 180 | 55.95 |
tag:blogger.com,1999:blog-294866812018-06-04T23:21:55.677-04:00Unidentified AppellationUnfortunately the vast vineyards of Brooklyn still remain highly unrecognized in the modern wine world. We hope to petition for an A.V.A. this fall while we harvest an abundance of diluted borough fruit.Brad Coelho a New Wine ShopI<a href=""><img style="MARGIN: 0px 10px 10px 0px; WIDTH: 413px; FLOAT: left; HEIGHT: 304px; CURSOR: hand" border="0" alt="" src="" /></a>airway Grocer down the block, I’m beginning to change my tune. Well, at least a little.<br /><br /.<br /><br /.<br /><br /.<br /><br /.<br /><br /<a href=""><img style="MARGIN: 0px 0px 10px 10px; WIDTH: 220px; FLOAT: right; HEIGHT: 220px; CURSOR: hand" border="0" alt="" src="" /></a>ar.<br /><br /.<br /><br / <em>separate</em>.<br /><br /…<img src="" height="1" width="1" alt=""/>Brad Coelho Chablis on the Cheap<a href=""><img style="FLOAT: right; MARGIN: 0px 0px 10px 10px; WIDTH: 293px; CURSOR: hand; HEIGHT: 238px" alt="" src="" border="0" /></a><br /><div>Christian Moreau Chablis ‘08<br /><br />This is an outstanding wine for the money, no doubt about it. The richness of ’08 creeps into the body of this young village wine at a young village price (high teens or so)- as notes of crushed stone, lemon peel, ginger & poached pear pepper the profile. The entry is smooth and expansive, packing in atypical power & persistence for its category & relative weight class. I’m tempted to refer to the finish as heady, but haven’t the cojones to go for the jugular. No fear for the old Chablisean guard, the electric output is still churning at high acid wattage, in spite of the current of fruit, 90 points.</div><img src="" height="1" width="1" alt=""/>Brad Coelho Lakes Top Producers<a href=""><img style="FLOAT: left; MARGIN: 0px 10px 10px 0px; WIDTH: 371px; CURSOR: hand; HEIGHT: 272px" alt="" src="" border="0" /></a><br /><div><strong>Red Newt Cellars</strong><br />.<br /><br /.<br /><br /><div align="left">Wine Rating<br />Sauvignon Blanc ’08 83<br />Dry Gewurztraminer ’08 88<br />Sawmill Creek Gewurz ’07 91<br />Curry Creek Gewurz ’07 92<br />Dry Riesling ’08 85<br />Reserve Riesling ’07 91<br />Pinot Gris ’07 89<br />Cab Franc Glacier Ridge ’08 88</div><div align="left"><br / ravi<a href=""><img style="FLOAT: right; MARGIN: 0px 0px 10px 10px; WIDTH: 354px; CURSOR: hand; HEIGHT: 336px" alt="" src="" border="0" /></a>oli.<br /><br /.<br /><br />Time to round ‘bout the wine trail cul-de-sac towards Anthony Road & Fox Run next…</div></div><img src="" height="1" width="1" alt=""/>Brad Coelho Finger Lakes Producers<strong>Hermann J. Wiemer</strong><br /><br / g<a href=""><img style="FLOAT: left; MARGIN: 0px 10px 10px 0px; WIDTH: 220px; CURSOR: hand; HEIGHT: 211px" alt="" src="" border="0" /></a>orgeous & delineated, awash in pure, clean flavors that just wouldn’t quit.<br /><br /.<br /><br /.<br /><br /.<br /><br /.<br /><br />My wife’s on-going Cabernet Franc contest, her favorite varietal, gave honorable mention to Wiemer. The ‘07s walked a fine line between herbacity & straight up ve<a href=""><img style="FLOAT: right; MARGIN: 0px 0px 10px 10px; WIDTH: 324px; CURSOR: hand; HEIGHT: 356px" alt="" src="" border="0" /></a>get.<br /><br /.<br /><br />Wine Rating<br />Pinot Rose ’06 78<br />Dry Rose NV 84<br />Blanc des Noirs ’03 83<br />Brut ’06 87<br />Dry Riesling ’08 87<br />Semi-Dry Riesling ’08 86+<br />Reserve Riesling ’08 90<br />Late Harvest Riesling ’08 88<br />HJW Riesling ’08 92+<br />Magdalena Riesling ‘08 91+<br />Bunch Select Riesling ’08 93<br />Gewurztraminer ’08 88<br />Cab Franc ’07 84<br />Cab Franc Reserve ’07 87+<br /><br /><br /><div align="left": </div><div align="left"><br /> </div><div align="left".</div><img src="" height="1" width="1" alt=""/>Brad Coelho Wine Cellars, One of the Finger Lakes' Finest<a href=""><img style="FLOAT: right; MARGIN: 0px 0px 10px 10px; WIDTH: 173px; CURSOR: hand; HEIGHT: 77px" alt="" src="" border="0" /></a>ing, Wagner & the like. Ransom’s concept was a smart one, serving as an all-encompassing ‘New York Winery’ tasting room of sorts, where all wines could be sampled and purchased on the premises. The tasting room abutted a wine bar, carrying a broad spectrum of New York wines to be paired w/ various foods from said state. Smart business plan huh? Well New York apparently didn’t think so, as both Vintage sites in Soho & the Upper West Side eroded to sluggish sales & couldn’t compete w/ rising neighborhood rents. Thankfully the postmortem on Vintage proved the notion not in vain, as the ‘eat local-drink local’ baton has been successfully passed to NY’s Wine & Culinary Center of the Finger Lakes.<br /><br /.<br /><br />The finest winery I visited:<br /><br /><strong>Ravines</strong>:.<br /><br / <strong>’06</strong> <strong>’07</strong> showed contrasting ripeness, w/ dried pineapple, crushed rock & an unnamable Chablisean character. The frame was gossamer, w/ high toned fruit flavors that sailed on and on. The <strong>’08</strong>, a tightly coiled embryo, seemed chiseled out of stone, w/ hay, floral and green fruit flavors contracting through the taut, firm finish. The gem of the collection, a single vineyard designated Riesling, comes from the <strong>Argetsinger</strong> plot. The <strong>’08</strong> was a full bodied, opulent, mineral-rich Riesling. Brooding, wrapped in a penetrating core of ginger, lemon peel, key lime and stone fruit flavors that seem backward to the point of intimidation, yet structurally impressive. This on'es built for the cellar. The <strong>’08 Sauvignon Blanc</strong> was a touch angular, yet beguiling in its <a href=""><img style="FLOAT: left; MARGIN: 0px 10px 10px 0px; WIDTH: 300px; CURSOR: hand; HEIGHT: 463px" alt="" src="" border="0" /></a>own right. The flinty nose of grass, savory herb, grapefruit & lime expanded & grew in complexity as the wine warmed. The inner-mouth perfume was a ricochet of scent, fleshing out a bit on the finish. The <strong>’08 Pinot Gris</strong> was just bottled and suffered accordingly, though its honeysuckle & melon notes were round, juicy & ample, in spite of being bottle-shy.<br /><br />I’d said previously that <strong>Pinot</strong> belonged in Finger Lakes fizz, well it doesn’t do a terribly bad <strong>Rose</strong> either ;) The winery was still pouring their <strong>’08</strong>, a soft nose of berry and briar turning creamy and well textured in the mouth, finishing w/ a snap. The <strong>’08 Pinot Noir</strong> <strong>’07 Cabernet Franc</strong> was stellar, perhaps the best of the trip. A meaty, seared edge dominated the aromas, but the palate was all polish, tugged by a tarry, graphite grip on the finish. The <strong>Meritage</strong>, an <strong>’06</strong>, was a long, red-fruit flavored Claret-doppelganger, keen on verve and finesse.<br /><br /.<br /><br />Wine Rating<br />Rose ’08 87 points<br />Dry Riesling ’06 90 points<br />Dry Riesling ’07 92 points<br />Dry Riesling ’08 91+ points<br />Argetsinger ’08 93 points<br />Sauvignon Blanc ’08 90 points<br />Pinot Gris ’08 87 points?<br />Pinot Noir ’08 87 points<br />Cabernet Franc ’07 90 points<br />Meritage ’06 88 points<br /><br />*As I’ve already drunk a case of them I do offer one bit of serving advice:<br />Decanting is a must & they show best when they’re a bit warmer than fridge temp.<br /><br /> <div><br /><div>Other top producers to follow...</div></div><img src="" height="1" width="1" alt=""/>Brad Coelho Lakes Region Report, I'm Hearing Great Things Cornell kids dwell. <a href=""><img style="FLOAT: right; MARGIN: 0px 0px 10px 10px; WIDTH: 407px; CURSOR: hand; HEIGHT: 244px" alt="" src="" border="0" /></a><br /><br /.<br /><br / <strong>Wildflower Cafe</strong> in Watkins Glen, as in Nascar & Indy Car Watkins Glen, told me all I needed to know about land prices. Are you sure you charged us for 4 beers, an appetizer and two sandwiches?<br /><br /:<br /><div><ul><li><em>Chardonnay</em>.</li><li><em>Sauvignon Blanc</em>-.</li><li><em>Pinot Noir</em>-?</li><li><em>Blaufrankisch</em>, <em>Lemberger</em> here. Reason being- Blaufrankisch is a weird name, no one can market such an oddity, yet Lemberger is way too phonetically similar to stinky cheese for it to sell either. I hate Catch 22’s.</li><li><em>Cabernet Franc</em>- while not quite on par w/ the North Fork as of yet, I saw nothing but promise from the producers dedicated to Franc. There’s been some interesting research at Cornell demonstrating that pyrazines (the unwelcome component implicated in the bell pepper phenomenon of Cab Franc) can be greatly minimized by leaf pulling early in berry development. Managing the canopies a few days before methoxypyrazine accumulation ramps up (roughly 30 days post bloom) seems to do the trick. Several Californian Franc producers have dealt w/ pyrazines by burying them under layers of ripe fruit, but the Finger Lakes aim is to nip them in the bud before they get cookin’ in the first place.</li><li. </li></ul><p>As for the top wines of the region, the styles vary from dry to semi-dry to semi-sweet. Fans of Mosel Riesling will likely find the semi-sweet wines of the Finger Lakes to be almost trocken (dry) by relation, as the alcohols trend well over 12 percent and the acidities are almost uniformly brilliant, RS or no RS. When there’s a bit more sugar to go around, these wines wore it exceptionally well. To generalize, Alsace, Clare/Eden Valley & Austria are better comparators, w/ Finger Lakes Riesling at its best showing an uncompromising severity akin to a Grosset Polish Hill or Trimbach Cuvee Frederic Emile (I’m not exaggerating on either front, fans of said wines will love a top Finger Lakes Riesling). The cha<a href=""><img style="FLOAT: left; MARGIN: 0px 10px 10px 0px; WIDTH: 425px; CURSOR: hand; HEIGHT: 275px" alt="" src="" border="0" /></a>racteristics for drier Riesling varies from smoky slate & petrol aromas to subtle floral, citrus blossom notes & possess an near-impaling sense of cut. Off dry versions give you the classic peach, apricot and lime notes, yet are not short on nervy malic acidity to keep things fresh, focused and lithe. I was particularly impressed with how intensely mineral-driven the wines were as a whole, leaving me to believe that there’s no area in the US that churns the Old World mineral gear as it does here- at least not that I can think of.<br /><br /.<br /><br /.<br /><br /.</p></div><img src="" height="1" width="1" alt=""/>Brad Coelho Ranger Relay, Hospice du Rhone<ul><li><strong>Samsara</strong>:<a href=""><img style="FLOAT: left; MARGIN: 0px 10px 10px 0px; WIDTH: 361px; CURSOR: hand; HEIGHT: 290px" alt="" src="" border="0" /><). </li><br /><li><strong>Gramercy Cellars</strong>:. </li><br /><li><strong>Herman Story</strong>:.<br /></li><li><strong>Hug Cellars</strong>:<a href=""><img style="FLOAT: left; MARGIN: 0px 10px 10px 0px; WIDTH: 150px; CURSOR: hand; HEIGHT: 125px" alt="" src="" border="0" /><. </li><strong></strong><br /><li><strong>Cabot Winery<<a href=""><img style="FLOAT: left; MARGIN: 0px 10px 10px 0px; WIDTH: 420px; CURSOR: hand; HEIGHT: 202px" alt="" src="" border="0" /></a>ed mouthful of beefy, chewy Syrah seared in a rocky edge & framed by firm tannins. The Cabots have really got something here & it will be a fascinating project to follow as they continue to unearth new enological ground.<br /></li><li><strong>Tercero</strong>:. </li><br /><li><strong>Red Car</strong>:.<br /></li><li><strong>Arnot Roberts</strong>:<a href=""><img style="FLOAT: right; MARGIN: 0px 0px 10px 10px; WIDTH: 297px; CURSOR: hand; HEIGHT: 471px" alt="" src="" border="0" /><. </li></ul><p>Odds & Ends: </p><ul><li. </li><br /><li.</li><br /><li.<br /></li><li).</li><br /><li.</li><br /><li.</li></ul><img src="" height="1" width="1" alt=""/>Brad Coelho du Rhone: Misc notes from CDP to Cote RotieThe following impressions were collected over a couple two hour walk around sessions during the Hospice du Rhone. Considering the environment, my propensity to babble on w/ winemakers & the frenetic pace of each event, my notes aim to capture a bit broader stroke than the typically pedantic wine prose to which you may be accustomed. My penmanship deteriorated as the afternoon’s progressed, as did the content of my impressions. My hopes are that this preface suffices as an adequate apology for the shortcomings of the following:<br /><br />· <strong>Clos St. Jean</strong>: In addition to the behemoths that were sampled during the seminar, Vincent poured his ‘08s, a vintage destined for obscurity, caught in the vortex of the ’07-’09 tornado. The Vieilles Vignes showed very well, w/ forward fruit in an immediately complex package. The palate was augmented by a wily spice note & framed by well rounded tannins. If the price is right, the balance of this young wine should provide for great drinking early in the game. The Deus Ex Machina & Combe des Fous suffered a bit from high extraction syndrome- all thrust & not enough raw materials to fill out their stocky shoulder pads. The bittersweet cocoa & espresso notes were there, but each cuvee displayed a level of grit that I had yet to experience from either. ’08 will likely be a year to avoid Clos St. Jean’s luxury cuvees, save for an unlikley discounting freefall.<br />· <strong>Domaine de la Sol<a href=""><img style="FLOAT: left; MARGIN: 0px 10px 10px 0px; WIDTH: 279px; CURSOR: hand; HEIGHT: 362px" alt="" src="" border="0" /></a>itude</strong>: Perhaps the least represented great producer in my Rhone-centric cellar. My excuse? Idiocy. I plead hollow cranial disease, particularly in regards to the cuvee Barberini, pound for pound one of the most under-rated wines of the appellation. The ’04 showed brilliantly w/ its peppery, velvet textured palate displaying equal sides of grace & power at this stage of its evolution (94 points). The ’07 Blanc was solid (89 points), but a mere afterthought once the elephantine Secret de Solitude ’07 passed my lips. The superlatives were super-elementary and might as well be distilled into recess garbles of ‘totally awesome’ and ‘wicked great dude’ and ‘stuff rocks man’ nonsense, as the overwhelming intensity of the wine battered my dissection of the wine’s characteristics to sophomoric dribble. Gorgeous young trophy wine, and a genuine trophy she is (99 points). The Cuvee Constanza (originated in the ’05 vintage, 100% Grenache aged in 80% tank, 20% wood barrels) demonstrated just how dramatically different the ’05 vintage is from ’07, particularly at this stage in development. The ’05 had a taut, sinewy spine that was wrapped in a great wall of tannin- China style, while the ’07 was an enveloping, lush siren, pillowed impressively in sweet Grenache baby fat (95+ and 97 points respectively).<br />· <strong>La Nerthe</strong>: One of my favorite white Rhones year in; year out has to be from La Nerthe, w/ their ’09 CDP blanc generating all that Chenin Blanc-like character I’ve come to expect from the house. Aromatics of green tea, persimmon and baked apple were backed by a lilting, zingy palate that kept freshness at the forefront (92 points). The ’07 Chateauneuf du Pape Rouge echoed just the reminder I needed regarding the vintage: buy cheap cuvees by the truckload. Just a beautifully poised, round young Chateauneuf du Pape w/ all the depth of flavor you’d hope for in the Cuvee des Cadettes (sans the oak) & a style that likely will be most flattering over the first dozen years of its existence (94 points).<br />· <strong>Domaine de Barroche</strong>: The two traditional cuvees from Barroche contrasted the ’08 & ’07 vintages nicely, w/ the ’08 shaded in a floral, elegant frame lifted by easy delineation and harmony. The ’07, on the other hand, blackened to the core, brooding & bubbling over a powerful fist of fruit that trumped the anthropometrics of the ’08 in terms of length & breadth, reminding me how opulence can overwhelm charm at a tasting such as this, like bringing a knife to a gunfight (92 and 95 points respectively).<br />· <strong>Domaine Cristia</strong>: The 3 offerings from Cristia were tri-polar, filling out one of the most awkward wine geometries imaginable. The ’06 Vieilles Vignes, a pure Grenache cuvee, must have been the inspiration for Justin Smith’s ‘Rocket Block’ nomenclature, as it was a flat out rocket blast of fruit, rifling through spades of kirsch, fruitcake & sweet licorice notes as if touched off by high energy dynamite. This fantastic, scintillating ride is well worth the amusement park line wait & is simply uncanny for an ’06 (96 points). The Renaissance ’05 was an inevitable drop-off, though I didn’t imagine the drop would cover such ladders of altitude. The wine was a grapey monolithic mess, disjointed at oblique angles and puckered to an astringent clip. I have no idea what was cooking w/ this showing but let’s cross our fingers and toes and chalk it up to ’05 structural awkwardness. Phasic. The Quartz, ’07, had no such excuse, yet was equally awkward in its unyielding, compressed profile that was far too tight-lipped to utter a sound. I do not know if this was a late bottled version, but ‘07s don’t tend to be shy, rather they trend in a 180 degree direction.<br />o Note. Justin Smith likely did not name his Rocket Block after the Domaine Cristia VV ’06. In fact, it would be chronologically impossible for him to do so, considering his Rocket Block originated before said vintage of said wine was hatched. I have not discussed the naming of Rocket Block w/ Justin during any occasion, past or present. I disclaim everything and fabricate anything.<br />· <strong>Yves Cuilleron</strong>: One of Neal Rosenthal’s more modern imports, Cuilleron’s Condrieus have always been impressive w/ their bright, flashy expressions of Viognier fruit, w/ the ’07 Vertige firing on a powerfully opulent angle for the region. What impressed me most w/ Cuilleron is the progress he’s made w/ his Northern Rhone reds, as his Saint Joseph Serine (an appellation the performed particularly well in ’07 based on these tastings) achieved a confluence of seamlessness & savagery. In spite of its beefy nerve it was wrapped in a burnished texture that made it instantly approachable. As for the Cote Rotie, Terres Sombre ’07, it was a much more backward, cellar-worthy red, with notes of bay leaf & spicy graphite holding sway over its tight tendons of dark fruit. His wines; both white and red, are expressive, plump vixens that cover an opposing stylistic ground to Villard.<br />· <strong>Yves Gangloff</strong>: The biggest tease of the tasting came from Gangloff in the shape of a 2 case import, Saint Joseph. Its production & distribution might as well make it a 100 foot plot in some obscure Burgundy appellation, yet Domaine Gangloff had the audacity to pour their diminutively produced bauble at Hospice, which was an ’08 that came damn close in quality & form to the ’04 Chave Hermitage Blanc we’d gulped through at lunch. There’s such limited supply that I doubt I’ll find anyone who’s tasted it to disagree w/ me on its merits, but let me make a not so unobvious plea to the Domaine to either ramp up production (this was their first vintage), extend their reach overseas or simply stop pouring this sauce in places that can’t access it, ie: America. Anyways, the ’08 Condrieu was a sensuous walk through the tropics, with soaring perfume and a lush, apricot inflected palate. The ’06 La Barbarine, Cote Rotie, was an absolute beauty. While I’ve generally considered this vintage to be a bit of a ballerina, this showpiece was loaded, w/ a concentrated wedge of white pepper, mesquite smoke & beefy currant notes that fanned out in long, lush, symmetrical tiers. Out of all the Cote Roties I’d sampled through, this was the most salivatory (next to Ogier), 96 points. The wordplay award goes to team Gangloff for their Santa Barbarine, a Santa Barbara county take on the aforementioned Cote Rotie. Kunin provided the territorial acuity for the project (which I believe is sourced from a vineyard previously owned by Andrew Murray), with the ’07 toeing the line between both worlds Old & New. The nose mixes animal & intensity, with an array of road tar, licorice, cassis & funky unmentionables that neck up & down the spice rack of the kitchen. The round generosity & warmth of the palate is all Santa Barbara, but what really compelled was the outrageous encore, taking shape in a long, multi-dimensional finish which sparked a bitter chocolate bite. The ’06 was even broader & deeper- which could arguably be credited to bottle ageing as much as the distinction between vintages. Gangloff’s dazzling New World joint venture was as much the talk of the floor as any during the big tent tastings at Hospice and deservedly so. I pegged both wines for mid 90’s ratings.<br />· <strong>Francois Villard</strong>: Was there a more enjoyable tasting table than Francois Villard’s? Probably not, considering the guy seemingly makes dozens of different wines (all of which rock like a mineral). The ’08 Version, St. Peray, A Marsanne that takes tang to a new level, cackling away w/ green tea, blanched almond & honey notes that cut through the palate like a switchblade, leaving the mouth watering for another sip. The Mairlant, a 70/30 Marsanne/Roussanne blend, picks up the zip where the St. Peray left off, tucking in quite a bit of nuance to its bony frame. Moving to Francois’s Viogniers, the best deal of the house has to be his Les Conto<a href=""><img style="FLOAT: right; MARGIN: 0px 0px 10px 10px; WIDTH: 225px; CURSOR: hand; HEIGHT: 540px" alt="" src="" border="0" /></a>urs de Deponcins VDP ’08, full of peaches ‘n cream & baked apple flavors that snap up & down the tongue to a fresh finish w/ pronounced clarity & drive. The diamonds of Villard’s collection come in the shape of 3 Condrieu’s: Deponcins, Les Gran Vallon & Les Terrasses Du Palat. The ’08 group, beginning w/ Les Terrasses, shows the flesh & thickness of a Cuilleron, yet w/ hairpin focus & poise, extending to the long, almost ethereal finish. Les Gran Vallon ratcheted up the depth a bit, yet my favorite of the bunch, the De Poncins, had a crunchy, almost severe minerality that buttressed the sparkling tiers of bright licorice & exotic green fruit flavors (92, 93, 94 points, respectively). Again, the ’07 St. Josephs show that they’re a force to be reckoned w/, as the Reflet proved to be the most dynamic & nimble of Villard’s bunch, showing fascinating tar & spice notes throughout its complex, seamless frame. Not to be outdone in the joint venture department by Gangloff, Villard has teamed up w/ Dave Miner (HDR’s person of the year in 2010) to create ‘La Diligence,’ Stagecoach vineyard picked Marsanne & Syrah wines that are also worthy of a wine-search for Rhone enthusiasts. Tablas Creek was onto something w/ this whole Frenchofornian Paso thing…<br /><br />As an aside, our sips and slurps stumbled a bit when the Cotes du Rhone girls walked through the room, scantily adorned in black & red sultry-wear, perhaps metaphorically hinting at the formerly beleaguered region’s current sex appeal. Lipstick wearing Grenache blends may be a new marketing trend, aimed to compete globally w/ Australian Kangroos, Cape taboos & Californian tattoos, but I’d be lying if I didn’t mention that they’re designer perfume came off smelling a bit cheap.<br /><br />I’ll splice in the New World Rhone blends on the next installment, allowing you some time to digest. In totality, wines were universally impressive from either side of the pond, though I do have to couch that appraisal w/ the fact that the Franco-contingency was well represented by almost exclusively top tier producers (and my snobby eyes tend to gravitate to the best).<img src="" height="1" width="1" alt=""/>Brad Coelho Rose for a Fair Fare<a href=""><img style="MARGIN: 0px 0px 10px 10px; WIDTH: 230px; FLOAT: right; HEIGHT: 242px; CURSOR: hand" border="0" alt="" src="" /></a> <span style="font-family:lucida grande;">Bastide Blanche, Bandol Rose '09 </span><br /><span style="font-family:lucida grande;"><br /><br /></span><span style="font-family:lucida grande;"></span><p style="MARGIN: 0in 0in 0pt" class="MsoNormal"><span style="font-family:lucida grande;"></span></p><p style="MARGIN: 0in 0in 0pt" class="MsoNormal"><span style="font-family:lucida grande;".<span style="mso-spacerun: yes"> </span>Packs a Tempier punch at a discounted fare, 91 points.</span></p><img src="" height="1" width="1" alt=""/>Brad Coelho Value in White Bordeaux<a href=""><img style="FLOAT: left; MARGIN: 0px 10px 10px 0px; WIDTH: 266px; CURSOR: hand; HEIGHT: 240px" alt="" src="" border="0" /></a> Value in the un-value of wine categories can be a particularly enjoyable find. At 14 dollars and change it doesn't get much better than this for boutique blanc:<br /><br />Graville Lacoste '08<br /><br />One of my favorite cepages for Bordeaux blanc, w/ this Kermit Lynch import layering a larger portion of Semillon in the blend, keeping Sauvignon Blanc & Muscadelle in the passenger seat. The light golden colored wine has a sensational, waxy nose of chive, freshly cut grass, white peach, guava and honey. Bracing on entry, yet paradoxically wrapped in an unctuous texture that balances well tailored oak w/ good concentration. A lush tug of acidity echoes on the finish, teasing you to another sip. Just a terrific value in white Bordeaux & a great gateway drug to boot, 89 points.<img src="" height="1" width="1" alt=""/>Brad Coelho du Rhone Installment 4: Chateauneuf du Pape<a href=""><img style="FLOAT: left; MARGIN: 0px 10px 10px 0px; WIDTH: 395px; CURSOR: hand; HEIGHT: 282px" alt="" src="" border="0" /></a>…but I digress.<br /><br /.<br /><br /.<br /><br /.<br /><br />Clos St. Jean CDP Blanc, ‘07<br /.<br /><br />Michel Tardieu CDP Blanc, ‘07<br /.<br /><br />Michel Tardieu CDP Grenache, La Crau ‘07<br /.<br /><br />Clos St. Jean Deus Ex Machina, ‘07<br /.<br /><a href=""><img style="FLOAT: right; MARGIN: 0px 0px 10px 10px; WIDTH: 338px; CURSOR: hand; HEIGHT: 287px" alt="" src="" border="0" /></a><br />Michel Tardieu CDP Grenache, La Crau ‘06<br /.<br /><br />Clos St. Jean Deus Ex Machina, ‘06<br /.<br /><br />Michel Tardieu Grenache, La Crau ‘05<br /.<br /><br />Clos St. Jean VV, ‘05<br /.<br /><br />Michel Tardieu Grenache, La Crau ‘04<br /.<br /><br />Clos St. Jean Combe des Fous, ‘04<br /.<br /><br /.<img src="" height="1" width="1" alt=""/>Brad Coelho du Rhone Installment 3: Charles Smith<div><strong>Quiet Name, Loud Wine</strong><br /><br />We were all hung over. The night before involved some 60 odd bottles that took us well into the jet-lagged night. Notes for said bottles escape me, but the residual Sahara grip on the roof of my mouth remains as clear as a Pacific sunrise. 9 a.m. is too early for a damn seminar. Apparently Charles Smith, of K Vintners & Charles Smith wines, agrees- considering he was nowhere to be found at that ungodly hour. Was he dangling out of a dumpster somewhere in downtown Paso Robles? Perhaps his hair, somewhat of a cross between Carlos Valderrama & cotton candy, was taking a tad longer to blow dry than expected? We waited, dry mouthed, staring into our diner placemats complete w/ K Vintner vertical flights and a curious flute of bubbly. A bit of Washin<img style="FLOAT: right; MARGIN: 0px 0px 10px 10px; WIDTH: 350px; CURSOR: hand; HEIGHT: 233px" alt="" src="" border="0" />gton fizz perhaps? Tick-tock tick-tock…Poland Spring bottles pounding down parched lips like they’ve got the cure inside. Desiccated eye lids, swelled red like over-ripe strawberries, watch bound and wondering. Where the hell is Charles Smith?<br /><br />Yo, M.C. Alan Kropf of Mutineer Magazine grabs the microphone like Del Preston at Waynestock to a thunderous pronouncement of “Charrrrrrrrrrlllleeeesssss Smmiiiiittthhh!” Playing possum- the man in question was a former rock band manager. Who’d a known?<br /><br />Buckle your seats folks; get ready for the F-bomb brigade. A command assault of profanity splattered our wings like vulgar clouds of high level flak. No amount of bullet-proofing could prepare our ears for the pummeling they took. The barrage of F-bomb shrapnel left some of us wounded, some in stitches & others simply open-mouthed. ‘Who here loves wine? Raise your hands…if you don’t put your hand up you’re gonna get a beat down! Let me tell you something about Rhone producers and Rhone drinkers, they’ve got F’n balls! It’s not some boring F’n Bordeaux seminar, at Hopsice du F’n Rhone, these F’n wines F-you up!’ Etcetera. The cobwebs were shaken off, we were officially awake.<br /><br />As for the bubbly in question, ‘F’n grower Champagne and don’t F’n spit it out!’ Your wish is my command. Kurt Cobain’s local grunge music & Robert Plant’s hair- all the terroir parallels you’ll need (he threw in Barossa’s AC/DC riff to balance Walla Walla’s Nirvana). When asked about his viticultural practices, Smith replied ‘these grapes are gonna be my bitch!’ Alright Charles, your wines better bring it as much as you do.<br /><br />Truth be told, this was my first experience w/ K Vitners, but be lying if I didn’t admit some serious expectations. Charles Smith, a winner of <em>Food & Wine’s winemaker of the year</em>, owes quite a bit of his start-up to Christophe Baron of Cayuse fame. Anyone that reads me knows my holy grail is branded w/ a Cayuse insignia, so upon hearing such a connection I doffed the earplugs, licked the lips & braced for impact. Offensive guy + access to Cayuse fruit is sure to produce an = amount of excitement & disgust. I’m pumped.<br /><br />Enough F’n foreplay, onto the F’n notes!<br /><br />All of the following wines are Syrah from the 2006 Vintage. The wines were foot crushed & basket pressed, utilizing native yeast fermentation w/ varied upbringing techniques based upon the vintage/vineyard characteristics.<br /><br />Pheasant Vineyard, Wahluke Slope<br />Coming from mostly sandy soils, the Pheasant Vineyard was one of the shyest in the K line-up (oxymoron), w/ its reticent hints of plum, flowers and spice notes peeking through. The attack turns fleshy, w/ a suave, violet-tinged texture coating the mid-palate nicely. The wine really picks up the pace on the finish, which leaves the palate awash in smoky, mesquite spice flavors, 92+ points.<br /><br />The Deal, Sundance Vineyard<br />This is another Wahluke Slope site from K, yet this vineyard is currently demonstrating a far more savage, animal character in its tarry, black shaded scents of pepper, fur & wild beefy suggestions. The mid-palate has a hearty, savory bite to it, rife w/ more up-front power and depth than the Pheasant Vineyard, powering through to the long, heady finish. I absolutely loved it, 95 points.<br /><br />Cougar Hills Vineyard, Walla Walla<br />The first Walla Walla designated Syrah, w/ a serious, immediate density to its briny black olive & tobacco notes. Sometimes crass descriptions serve as the best ones, so let me call this what it is, a brick shithouse. The palate of the wine is a muscular flex, with a spunky beef jerky note (a la Cayuse) holding sway over the vivid belly of purple fruit. Firm & fresh all at once, with its weighty body takin<a href=""><img style="FLOAT: left; MARGIN: 0px 10px 10px 0px; WIDTH: 249px; CURSOR: hand; HEIGHT: 261px" alt="" src="" border="0" /></a>g a load off on the mouth-watering finish spiced in white pepper, 94+ points.<br /><br />Wells, Walla Walla<br />To me, this was the Camaspelo of the bunch, more provocative than it is pleasurable. Flat out funky in its bouquet of cooked cabbage, leather, porcini mushroom, tapenade and sweet balsamic scents. It is a paradoxical wine in that it feels ripe to the tongue yet has a vegetal streak (which could be a vineyard characteristic, brett or Charles Smith’s feet), as the mouth-feel demonstrates surprisingly structure, complexity & intensity. It’s just one of those oddities of overtly expressive wine, leaving you w/ an objective admiration, yet abject revulsion. The score fails me here, much like an awkward stamp on impressionistic art, 84 points.<br /><br />Phil Lane, Walla Walla<br />What a difference a site makes- moving to the minty end of the spectrum on Phil Lane felt like a cool breeze through the nose in its menthol, licorice and milk chocolate notes. Think Andes Candies. Pure, polished and impossibly elegant through the palate, w/ a seamless bent that puts it on an island from the rest of Charles Smith’s portfolio. This is a Syrah for fans of the classics who loathe the obnoxiousness of the rest of the bunch, 93 points.<br /><br />Motor City Kitty, Stoneridge Vineyard, Royal Slope, Columbia Valley<br />The 2006 saw zero new oak, bringing us back to the beef in its tightly coiled, savory scented nose. Undoubtedly in need of extended aeration (or more preferably, ageing), the wine incrementally builds on the palate, un-locking its layers upon layers of spicy, purple fruit flavors. This really augmented in the glass, shifting to an expansive gear that didn’t truly explode until its crescendo of a finish. She needs quite a bit of time to let loose, as 4-5 more years should help shed some of that power left in reserve, 94+ points.<br /><br />Royal City, Stoneridge Vineyard, Royal Slope, Columbia Valley<br />Shall we save the behemoth for last? We shall, with this 17 plus percent alcohol bombshell completely shocking us in its restraint. The nose contradicts its heft, seeming fairly classic with its dusty graphite, cedar & savory plum notes. The raw materials don’t reveal themselves until the wine passes the lips, as the viscosity & sheer mass seem close to bursting at the seams, yet the weight stays in proportion, thanks to a firm skeleton & jazzy bright acidity. The length here is tremendous, suspending dusty earth, hard spices & warm blackberry sauce notes in thin air, resonate and complete, 95+ points.</div><img src="" height="1" width="1" alt=""/>Brad Coelho du Rhone installment 2, Ogier: Finesse, Elegance & Pairing<strong>Finesse & Elegance</strong>- two words that are spewed out to a point of surfeit in wine diction- two words which I'd like to dump into a biodynamic compost heap. They’re tired and they’re cliché and they’re archaic, but what wedgies my tighty whities most is how they’re mechanically thrown about the winespeak pitching mound regardless of who’s up to bat. Setting the bar low (or high, either way you slug it) with a 16.5% percent alcohol elephantine Pinot Noir from Napa Valley that ‘somehow manages to be elegant.’ Come on, really. Or another claret, in the long line of distinguished clarets, that ‘reeks of finesse’…well maybe it does, but can’t we use another word? No not reek, I like reek, I mean for elegant. If you’ve got a dozen elegant Bordeaux, one by one in a shooting gallery, who cares? Doesn’t that make what they don’t have more interesting? The erroneous use & sheer redundancy of 'finesse & elegance' have soured me on said terms a bit, but what about when they’re spot on, dead center apropos, absolutely perfect adjectives to use on a wine at hand? Am I still allowed to sneak ‘em in as descriptors after bashing the hell out of them? Caveat emptor- some wines strike me as so archetypal that they must have existed before the adjec<a href=""><img style="FLOAT: right; MARGIN: 0px 0px 10px 10px; WIDTH: 296px; CURSOR: hand; HEIGHT: 291px" alt="" src="" border="0" /></a>tives came around, as if the words were created just for them, like a tailored suit. Ogier’s Cote Rotie, for lack of better terminology (or perhaps as an emblem of said terminology in its quintessence), are the incarnate of all enological finesse & elegance in all their defining grace. They float, they glide, they tiptoe with authority. Justification for their use noted.<br /><br />If you’d like the inspired gasbag to continue to state his case for using such timid terms for such exemplary wines, feel free to nudge. For brevity’s sake, let’s move onto door number two.<br /><br /><strong>Pairing</strong>- usually a term associated with the grouping of particular wines w/ particular foods, but during the <em>Cote Rotie, The Next Generation</em> seminar, I felt compelled to take the liberty to direct said term towards the grouping of a particular winemaker with...a particular winemaker. John Alban sitting next to Stephane Ogier, tasting his wines. The aforementioned moderator of the seminar makes some of the most burly, broad-shouldered expressions of Rhone varieties on the planet, easily taking the cake in the ‘my wine can beat up your wine’ competition. That said, they not only express their Edna Valley site uniquely, they do so in a way that I find to be compelling, equally and oppositely from the stable of Ogier. How is that possible? Big & balanced, ethereal & elegant- or, sans alliteration- good wines come in all dimensions. The chemist in me is interested in pH, brix, phenolic ripeness, dry extract...though my gustatory marrow tends to win out. In Bacchus we trust (or, for you 80’s pop music fans, consider Paula Abdul’s ‘opposites attract’ in verse).<br /><br />We’ll call Ogier the Chateau Lafite of Cote Rotie (or the Chateau des Tours of the North, or the…you get idea), with John Alban playing the electric bass to his acoustic violin. Seriously, could you possibly make two Viogniers that are more different than Alban & Ogier? No cheating Italian fans, your funky fermented on the skins jobs don’t count. Why don’t they count? ‘Cuz I make the rules, my game.<br /><br />Stephane Ogier’s line-up (minus the ’08 Syrah, La Rosine VDP & ’07 Cote Rotie Reserve, which were casualties of the hit & run variety):<br /><br />Viognier 2008, Viognier de Rosine VDP<br />The bulk of Ogier’s discussion on his whites consisted of ‘I do NOT believe in battonage (stirring of the lees).’ Cautioned w/ a ‘hey, it’s cool if you do it, but that’s just not the way I roll.’ I’m paraphrasing obviously, it sounded much better in his French accent. Well the first of his Viognier came in under 12.5% alcohol, which is exceptionally low for the variety. The hue was slightly pale, but the bouquet was sheer ambrosia. A fiery spray of honeycomb, warm apple pie crust, rose petals & grapefruit peel stole the show, as the palate turned a bit trim, w/ its crunchy, almost tart rip of green apple-peel acidity brimming through the finish, 88 points.<br /><br />Condrieu, 2008<br />A slightly headier (13% alcohol), more golden colored Viognier, with a reserved, coiled nose of quince, sea salt, peach & rose water perfume. This fleshier, naked expression of Viognier rips through the palate w/ a tactile, rocky-river bed like layer of minerality pumping out to the juicy finish. While the Condrieu is obviously a tad riper, it maintains a poise and lacy texture that is all Ogier This wine sees zero small barrels, 91 points.<br /><br />Syrah L’Ame Soeur, VDP 2007<br />How many VDPs come even close to the class of this effort? His ‘07s are just tremendous up & down the line, w/ the VDP revealing a deep ruby core of color. The sultry perfume of wild spices, briar, white pepper, flat iron singed meat & dark, smoky berries almost gave me goose bumps. In the mouth, th<a href=""><img style="FLOAT: left; MARGIN: 0px 10px 10px 0px; WIDTH: 177px; CURSOR: hand; HEIGHT: 438px" alt="" src="" border="0" /></a>e entry weaves in such fabulous layers of suave, velveteen texture that I seldom experience from young Rhone, even in Cote Rotie. The ethereal wave of earthy, delicate fruit spins its way to the finish, propelled by a stony, rippling undercurrent of acidity, 92 points.<br /><br />Cote Rotie, Lancement 2007<br />The Lancement was completely de-stemmed in 2007, firing out another impressively aromatic statement that brings to mind the irresistible scent of smoke swelling up from wood grilled game. The attack brings about a raw kaleidoscope of flavors, shuffling in notes of pepper, brick dust, tilled earth & sun baked dark fruits. The flavors flicker & spark the taste buds throughout the palate through shapely curves- an almost impossibly elegant frame. This is singular stuff that I can’t imagine coming from anywhere but Cote Rotie, 95 points.<br /><br />Cote Rotie, Belle-Helene 2007<br />The Belle-Helene represents some of Ogier’s oldest vines in Cote Rotie, with the 2007 incorporating about 15% of the stems. Quite the contrast to the Lancement, which was full of showy immediacy, the Belle Helene has a taut, more sinewy tannic frame. In spite of its backward disposition, the quality of the fruit is obvious with its intense & perfumy notes of caramel, milk chocolate, cassis & lead pencil shavings. She’s got a body to die for, but a few more years in the cellar are a must, 95+ points.<br /><br />Cote Rotie, Reserve du Domaine 2001<br />In spite of the 9 years under its belt, the Reserve is still impenetrably dark, arguably more so than the babies of the flight. A funky, freaky blast of the bouquet and you’re transported over to something from the world of Bonneau, as a provocative array of cabbage, sweet balsamic, stable floor, mushroom & iron notes smack from the stem. I’d obviously wager Chateauneuf from the bouquet alone, but the savagery toned down a bit as it aired, w/ the enveloping, deftly textured palate of warm currant fruit leaving a silky, almost cascading impression on the finish, 94 points.<br /><br />Roussanne VDP, 2005<br />This wine was so deeply golden it made the previous Viogniers in the grouping look like tap water. Think concentrated urine the Sunday morning after a weekend bender that got way out of hand. Pee shaded robe aside, this was a helluva wine (albeit one that is not for everyone) conceptually reminding me of what hefty, dry Sauternes would taste like. Brazen & complex with its nose of ceiling wax, honeysuckle, French vanilla custard, nail polish, bee pollen & quince. Wow- that’s a lot of characteristics to decipher but trust me, they’re all there! As for the mouth-feel, for all its fat, opulent layers of glycerine, the wild ride was reeled in by an idiosyncratic tang, reeling it all in for the dry finish, 92 points.<br /><br />*For the record, one of my favorite wines (not necessarily best, but favorite) of all time is a ’99 Ogier Cote Rotie. If affluent were part of my checking account’s vocabulary there’d be a LOT more of his wines in my attenuation of a cellar.<img src="" height="1" width="1" alt=""/>Brad Coelho du Rhone installment one: South AfricaHospice du Rhone, the brainchild of Mat Garretson- who has sense passed the baton to make it to Disney World as a kid, so why should adult passions open to slimmer waiting rooms?<br /><br />I left New York’s decaying anatomy of a tombstone skyline in the dust for Paso Robles, California, the anti-New York. It reeks of such belligerent non-New York-ness that it comes out smelling sober. A pastoral baptism in fermenting waters- God love it.<br /><br />The event was a two day affair, sectioned off into morning seminars & afternoon gang tastings. I’m going to spend a bit more time summarizing the seminars (which were eye-opening, fabulously run joyrides with Rhone inspired vistas), so I’ll break things up a bit into installments- the first being a 9 a.m. wake-up call from South Africa, entitled <em>We’ve Come a Long Way Baby! The past, present and future of South African Syrah</em>. Technically the first event was the Rhone ‘n Bowl, Freudian slipped ‘Bone ‘n Roll,’ which I unfortunately couldn’t attend as the Hitching Post II was calling my name.<br /><br />I’d be remiss to not mention than James Molesworth has done a terrific job at Wine Spectator covering the progress of South African Syrah over the past few years (he also moderately the tasting eloquently). James prefaced the tasting w/ a few words on Apartheid, touching on how hamstrung the region had been qualitatively & how dramatic the upswing has been w/ the change in South Africa's political environment. The lion’s share of vines are still dedicated to Chenin Blanc (which has moved from a pure<a href=""><img style="FLOAT: left; MARGIN: 0px 10px 10px 0px; WIDTH: 400px; CURSOR: hand; HEIGHT: 300px" alt="" src="" border="0" /></a>ly jug wine proposition to its now highly versatile expressions from steely & fresh to richer, mouth-filling versions), but Syrah has gone from basically non-existent to representing ten percent of the total vineyard acreage. While the progress has been fast and furious, wine enthusiasts must keep in mind that nearly two thirds of the Cape's red vinifera are under ten years old. As the vineyards & vignerons mature, one can only imagine what the qualitative ceiling is for South African Syrah.<br /><br />Before I get into the wines I just wanted to make two brief points. One of which is that stylistically speaking, South African Syrah falls somewhere in between the guts of the Rhone and the flash of Barossa. They tend to have a freshness and delineation that the headier Syrahs of Australia lack, while hinting at some of the beefier elements Rhone enthusiasts expect from Hermitage, Cornas & Cote Rotie. Secondly, the major impediment I see for these wines in the U.S. is a function of their raw market presence. While Syrah is such a global & highly competitive category, South African versions do have a singularity in style that was noted by just about all in attendance (most commented that this seminar was the most eye opening), but its penetration into the U.S. market is fairly spotty. I’d imagine it is a multi-factorial issue, dealing w/ business specifics of importation (most are brought in by Cape Classics), sales representation stateside, production numbers & the lingering consequences of the Pinotage phenomenon. That being said it does appear that their presence in the U.K. is relatively strong from what I’ve heard.<br /><br />Fairview Reserve Shiraz, 1986<br />(The semantics between Shiraz/Syrah are mostly due to the Australian influence, you’ll see both in South African labels) This was one helluva Apartheid era statement, keeping in mind that this wine was made when little to no Syrah was planted in South Africa. The colors showed a faded, brick-like diaphanous rim, with the lively aromas of smoked apple-wood bacon, decaying vegetation, dark olive & new saddle leather bringing to mind a mature Cote Rotie. The entry showed a spicy, peppery lift, turning mid-weight and complex throughout the palate. The body of the wine was shapely, shaded in finesse & finely resolved tannins, with a pretty, lingering finish awash in red fruit. This was just an outstanding experience to taste an almost 25 year old, one of a kind (literally) Cape Syrah, which can only be dubbed as a tribute to an unwavering artisan, 90 points.<br /><br />Stellenzicht Syrah, 1994<br />James Molesworth’s background on this bottle was particularly interesting to me, as it apparently was a fruit bomb at birth- constructed as a showpiece of ‘hey, look what I can do’ cellar stud, with its high class oak, polish and little reference to varietal or place. Well a bit of time in the bottle surely served it well, as it maintained a fair amount of color for its 16 years of age, yet turned the corner aromatically w/ its cedar, lead pencil shavings, black currant and tilled soil notes. The attack came on smoothly, w/ a silky resolve to the texture that turned up the poise dial well past 10, with a good tug of acidity keeping the finish long & defined. In the entirety of its experience, this bottle reminded me of a charming, near-mature claret, 92 points.<br /><br />Boekenhoustkloof Syrah, 2001 & 2006<br />This is a producer which you’ll see on the broader restaurant wine lists and reputable urban retailers. The ’01 was still fairly opaque, w/ an impenetrably dark core. The taut, very reserved palate shows a sneaky hint of spice box, olive & black currant fruit surrounded by a foursquare frame. While a bit more character perks up on the grippy, meaty finish, the ’01 was far less persuasive than the ’06, which exploded w/ a wilder, smoky clap. Savory, rich flavors of dark plum & grilled steak pump over the bed of velveteen tannins, w/ the structure still holding sway over the wine’s opulence. A dash of black pepper stretches out the finish nicely. This is a channeled, sharply balanced wine that pays close attention to detail & should really blossom in the cellar, 88 & 92+ points respectively.<br /><br />Mullineux Family Syrah, 2008<br />The debut vintage for Chris Mullineux is a showy one, full of warm, primary fruit the likes of cassis, pepper and a basket's worth of deep red cherries. An explosive attack fans out to a big splash, with the midpalate fleshing out a big punch of anise & spicy new oak. Rock solid & pure baby fat, with firm, yet refined threads of tannin tying it all together, 93 points.<br /><br />Tulbagh Mountain Vineyards Syrah Mourvedre, 2005 <a href=""><img style="FLOAT: right; MARGIN: 0px 0px 10px 10px; WIDTH: 320px; CURSOR: hand; HEIGHT: 313px" alt="" src="" border="0" /></a><br />I’m not sure if it was the Mourvedre that was doing the talking, but this wine just didn’t cut the mustard relative to its peers. The dried fruit character was not the most flattering, as it wasn’t brightened by the spunk & lift of the previous producer's bottlings. The mouth-feel had a somewhat austere casing to it, with its hard edges poking out in their obviously brash youth. I left this wine w/ the impression that it was a closed/dumb phase, yet I’d be hard pressed to imagine it would show the class of the rest of the flight even at its apogee, 84 points.<br /><br />Sadie Family Columella 2, Syrah Mourvedre, 2005<br />The Sadie Family has come up w/ a fantastic label for their Columella blend & a ‘wow’ nose to boot, with its intoxicating blend of dried flowers, cedar, cardamom and a spicy array of sun-baked black fruits. The plump, generously round entry makes way for a gutsy belly of flavor, still wearing primary clothing in soft textures. The one bugaboo I had w/ this showing was its length, which seemed to die down just as things were really getting exciting, 92 points.<br /><br />De Trafford Shiraz, 2007<br />Save the bombshell for last, eh? She was a bombshell indeed, popping and crackling from the bouquet of melted licorice, bittersweet cocoa, blackberry liqueur and sweet toast notes. The palate is best described as an enveloping presence, all in symmetry, polish and dazzling proportion. David Trafford’s Shiraz was the class of the group, lithe & dark, with tantalizing purity. I’d love to see what this beauty does w/ a bit of bottle age, 95 points.<br /><br />A brief epilogue:<br /><br />I had the good fortune of connecting w/ Marc Kent of Boekenhoutskloof, David Trafford & the Mullineux family at a barbeque chez Pisoni in the Santa Lucia Highlands. This group of bright, spirited South Africans couldn’t have been more kind or diverse a group. They were quick to acknowledge the sharp learning curves they've faced, yet attack each new vintage w/ a curiosity & experimenting verve that shows they’re not afraid to fail. While Syrah was the theme of the HDR stage, what South African vignerons have been doing w/ Chenin Blanc shouldn’t go w/o mention. Just about every version of the grape outside the Cape comes in a straight varietal package, but in South Africa blending Chenin is fairly common practice for several producers, including Mullineux & De Trafford. It is not uncommon to find a dab of Viognier, Grenache Blanc or Clairette stirring in South African Chenin, with David Trafford’s eyeing Roussanne as another potential partner (his white wine vision reminds me of Bob Lindquist’s bottlings at Qupe, particularly w/ regards to aromatic lift & early harvesting). In addition to Chenin, I sampled a couple outrageously good South African Chardonnays which revealed Meursault-like richness & subtly nutty aromas in just a few years of bottle age.<br /><br />To demonstrate the contrast in styles I alluded the pendulum. For a twist on summer sipping, the Petit Chenin checks in w/ clean flavors of straw, grapefruit, quince & fresh flowers that zip along nicely over its bony frame. The ’08 is a bit ampler than previous vintages, yet still packs all the nerve & pizzazz of the bottling, 87 points. Now the flip side to Chenin’s coin, the De Morgenzon, is the product of full-throttle, native fermentation that ages on the lees for 15 months in new French Oak barrels. The nose brings a Vouvray Demi-Sec to mind, w/ its wild notes of honeysuckle, bee pollen, candle wax & persimmon fruit. Its palate is full, fat & expansive, turning bone dry on the back end. What really keeps this from being a malo’d up battonage bomb is its buried ripple of acidity, lighting the spark through the well defined finish, 92+ points.<br /><br />While it is frustrating to me that wineries like the Mullineux family still don’t have an American home, I’m hopeful that they strike a healthy relationship w/ an importer sooner rather than later. As the presence and level of representation for South African wineries increases in the states, I encourage all Rhone-aholics to seek them out. Something tells me you’ll be just as impressed as the 300 or so that attended this past year’s Hospice du Rhone. They really have come a long way, baby!<img src="" height="1" width="1" alt=""/>Brad Coelho or Treat?I attended a great BBQ over the weekend at the behest of Jay Hack, who outdid himself as evidenced by the raw tonnage of turkeys that met their demise in his deep fat frying tank. While there was an abundance of wines poured during the day, the resounding impression I was left w/ was one of…WTF is ‘The Treat’ and why did I put that cement mixer in my palate?<br /><br />I'm not an uber negative guy, so let me preface w/ a couple positives:Big fan of the Cabot Syrah- great couple, inventive site selection (where the hell is Humbolt county anyway?) & distinctive juice. If Jim Gallagher wasn't pouring, most would believe the '95 Bedell to be a decent, plateau’d classified growth. His shtick for brown bagging Long Island wine is up (a la Jaouen's 'blind wine' being a Musar 9 times out of 10). The Jadot Moulin a Ven<a href=""><img style="MARGIN: 0px 10px 10px 0px; WIDTH: 460px; FLOAT: left; HEIGHT: 350px; CURSOR: hand" border="0" alt="" src="" /></a>t was another pleasant surprise (until hearing about the pricetag), which of course came from Leo alongside his '06 Sassicaia (which was a burly bitch of a Sass, very backward, tannic & powerful).<br /><br />That said, the Treat deserves a bitch slap. First off, the wine is called Treat. Huge pet peeve. Anyone have any words that they loathe just for the sound of them? Nooks and crannies always pissed me off, something phonetically about it just grated on my eardrums. Treat is no better- what a friggin’ crappy word…and for consistency sake, what a friggin’ crappy wine. Wine caricatures happen; at least w/ Scholium there is a Star Trek-like vision and passion for obliterating enological boundaries w/ a bazooka, but the Treat ain’t no Scholium, nor is the Scholium much of a treat to the palate (god I hate the word treat). The treat tasted as if it were the fragmentary parts of a Turley Petite Sirah, bisected by a lumber fist & messily pieced together to make a deadline. While it isn’t quite as offensive as Heidi Barrett's <em>Amuse Douche</em> (I REALLY hate that wine), it’s almost as insipid. Is it really a cabernet? I mean sometimes varietal recognition doesn’t matter I guess, but come on! Wine product…this coming from a guy that likes acid <strong>and</strong> likes well-made ‘spoof.’<br /><br />Now that I’ve got that pejorative saliva pumped from my glands, it is time to finally catch you all up w/ my recent trek to Paso Robles for the Hospice du Rhone. I’ll post my impressions in installments, with the first being a focus on South African Syrah. I hope you enjoy!<img src="" height="1" width="1" alt=""/>Brad Coelho & RavingDoes Bordeaux ever piss you off? Personally, I don’t want to give it the satisfaction. The redundancy of another spring futures campaign is such a bland, stale parade that its predictability alone has allowed me to shut it off for the most part. That being said, the region’s dynamic hasn’t always been this way, has it? Read between the lines, right? Dog-shit years like ’91, ’92 & ’93 would get the ‘claret drinkers’ lip service. The aristocracy knew that high price tags couldn’t be sustained for wines that are as transparent as fishbowls, but they had to save face to keep the machine well oiled. We all get it. Then once the hype ignition lit a subsequent vintage aflame, the hoards would be dubious, but tingly nonetheless, right? I mean ups and downs make sense. Sullen, diffuse optimism for any period of time is just another way to prime the pump for a crazy wino. It readies them for their future crest of enthusiasm, while doubly allowing them to reserve a bit of excess funds from all those ho-hum vintages that rendered their buying decisions remarkably sane. A win-win. <a href=""><img style="MARGIN: 0px 0px 10px 10px; WIDTH: 278px; FLOAT: right; HEIGHT: 320px; CURSOR: hand" border="0" alt="" src="" /></a><br /><br />Who needs Napa’s consistency? I mean if you want consistent, buy Napa- when it’s bad, it really aint that bad. When it’s great, it’s damn good, but come on, not THAT much better than last years polish. Doesn’t some of Bordeaux’s beauty lie in its climatic margins? Don’t the gray skies that shroud the flat gravel lands pave the way for the region’s black and white extremes to see-saw up & down the qualitative pyramid? A confluence of emotions, teetering up & down w/ excitement, depression and neurosis. Sounds great, right? Well sure, consider the alternative. Don’t get me wrong, I am not one-one hundredth as diluted as I seem to be. I’m hardly so foolish to suggest that ‘better, more consistent quality’ is a drawback to Bordeaux. It’s not. I don’t like bad Bordeaux. I’m not even that crazy about mediocre Bordeaux. That said, I have to admit that consistency makes Bordeaux far less viscerally attractive to me (and no, don’t give me that crap about ‘gee, you should be a Burgundy fan if you crave the heartbreak). My outside allure to Bordeaux was partly predicated on its variability, its moodiness. The great are truly singular, not just ‘cuz they’re great, but because they’re uniquely scarce gifts from Bacchus. After all those days of slugging through desiccated, dreary dregs of Cabernet, the sun finally kissed both banks of the Gironde. None of that ‘it rained, it poured…then the September sun saved the vintage’ crap. The suffering through astringency, wood tannins, gritty stems & teeth jarring acidity finally paved the way to something more than palatable, something memorable. Absence makes the heart grow fungus.<br /><br />You get the gist. There’s no real suggestion here, just a nihilistic observation of sorts. See, nihilism, that’s the problem. I’m not willing to admit that it’s my problem that Bordeaux is boring me a bit. It can’t possibly be me! No indictment here, but I have to rant w/o direction when the fire is gone. I do seem to have diagnosed the bit. No volatility + no surprise = no passion. No fire. Another great year, if it really is, is becoming less about doubting the sales pitch and more about ‘didn’t we just have one?’ Well, I’m broke on 2000, I’m broke on 2005. Even if I had the money for ’08, ’09 and I’m sure 2010, 2011, 2012, blah blah blah…I don’t think I’d be able to buy w/ the fever of the past. My heart’s just not in it- perhaps it’s cured. I’ve been cured of a disease by witnessing a painful change, a change towards predictability. Wine has always kept my sanity out of check because of that very fact, its unpredictability. I’m deaf and dumb to the ‘nother great vintage.<br /><br />Maybe when I taste this years champion I’ll sing a different tune, but as of right now, I’d rather drink something funky.<img src="" height="1" width="1" alt=""/>Brad Coelho' Aubert...it's just Chardonnay, right?<a href=""><img style="MARGIN: 0px 0px 10px 10px; WIDTH: 300px; FLOAT: right; HEIGHT: 239px; CURSOR: hand" border="0" alt="" src="" /></a><span style="font-family:lucida grande;">I couldn’t wait to get my meat hooks on a bottle or twelve of these.<span style="mso-spacerun: yes"> </span>Fresh off the FedEx, bottle shock be damned…and I’m already 3 empty bottles deep into my stash.<span style="mso-spacerun: yes"> </span>I’ve drank enough vintages of Mark Aubert’s Chardonnay to be convinced that vintage bares marginal importance on his wines quality, save for a wee bit of ’06 indigestion- or the home run to dead center in ’05 (as opposed to the right-center blast in ’07, but let’s put the tape measure away & squelch semantics).<span style="mso-spacerun: yes"> </span>Screw the vintage, the wines all rock- my note on the ’08 is as much of a non-event as an Olympic qualifier between the Dream Team & the Laotian nationals.<span style="mso-spacerun: yes"> </span></span><div><br /><p style="MARGIN: 0in 0in 0pt" class="MsoNormal"><?xml:namespace prefix = o<o:p><span style="font-family:lucida grande;"></span></o:p></p><p style="MARGIN: 0in 0in 0pt" class="MsoNormal"><span style="font-family:lucida grande;">This type of redundancy can put a firm financial squeeze on yah.<span style="mso-spacerun: yes"> </span>Let’s hope your spouse drinks wine, otherwise consider the couch your new somnolent haven. <span style="mso-spacerun: yes"></span>That’s where your ass will permanently reside post the credit apocalypse.<span style="mso-spacerun: yes"> </span>Why didn’t I buy more of these puppies?<span style="mso-spacerun: yes"> </span></span></p><br /><p style="MARGIN: 0in 0in 0pt" class="MsoNormal"><span style="font-family:lucida grande;">Oh yeah, that damn recession thingy.<span style="mso-spacerun: yes"> </span>No means yes.</span></p><br /><p style="MARGIN: 0in 0in 0pt" class="MsoNormal"><span style="font-family:lucida grande;">Aubert Ritchie '08<br /></span></p><p style="MARGIN: 0in 0in 0pt" class="MsoNormal"><span style="font-family:lucida grande;". </span></p></div><img src="" height="1" width="1" alt=""/>Brad Coelho April, another spring. 2009 rose campaign begins<a href=""><img style="MARGIN: 0px 10px 10px 0px; WIDTH: 440px; FLOAT: left; HEIGHT: 331px; CURSOR: hand" border="0" alt="" src="" /></a><br /><p style="MARGIN: 0in 0in 0pt" class="MsoNormal">The grills are ready to spit their plumes of charcoal dust into thickening skies.<span style="mso-spacerun: yes"> </span>The sun readies to stretch its blazing rays an extra minute of an extra day; teasing mercury up the dial past hardened numbers of cool centigrade. <span style="mso-spacerun: yes"></span>Producers begin to loosen their respective cellar belts & cut primary bait.<span style="mso-spacerun: yes"> </span>The pink assembly has been capped and greased.<span style="mso-spacerun: yes"> </span>The time for heft is dwindling.<span style="mso-spacerun: yes"> </span>Unleash your foils for the salty days to come & share your impressions of saignee as you note them. </p><p style="MARGIN: 0in 0in 0pt" class="MsoNormal"><br /></p><p style="MARGIN: 0in 0in 0pt" class="MsoNormal">Mordoree Dame Rousse, CDR Rose '09</p><p style="MARGIN: 0in 0in 0pt" class="MsoNormal"><br /></p><p style="MARGIN: 0in 0in 0pt" class="MsoNormal">The newborn blush has begun to settle into D.C. wine shops, dripping off the rush of spring delivery trucks by the case. A perennial beauty, the workhorse CDR rose from Mordoree, checks in at all of <em>11 dollars and 19 cents</em>- worth every pink penny. A blast of strawberry, deep red cherry & watermelon notes fold into the thread of round, lush fruit flavors that just won't quit. A bit of warm alcohol spills out off the finish, yet the rest of the package is just about as tasty as Provencal rose gets, 88 points.<?xml:namespace prefix = o<o:p></o:p></p><img src="" height="1" width="1" alt=""/>Brad Coelho Cabernet hell is freezing over, I’m buying in Napa ‘07<p: </p><ul><li>Lack of distinction </li><li>Lack of value</li></ul><p href=""><img style="MARGIN: 0px 0px 10px 10px; WIDTH: 388px; FLOAT: right; HEIGHT: 282px; CURSOR: hand" border="0" alt="" src="" /></a>ave a problem.</p><p>Well, if egg on my face tastes this good (and doesn’t cause me to loose my shirt), I’m all for it. Mea culpa me some Cabernet from Napa Valley baby! Who knows if it is the recession or not, but <a href="">Grapes the Wine Company</a>. </p><p.</p>My previous take on the Phelps:<br /><br />Phelps Napa Cabernet '07<br /.<img src="" height="1" width="1" alt=""/>Brad Coelho cheated again, diving into my pallet of Rhys, palate first<div>Reading Kevin Harvey’s suggestions for his ‘07s made me almost blush to pop this cork so early, particularly after I’ve chided all the trigger happy gluttons who’ve been complaining that their ’07 Chateauneufs ‘don’t seem that great’ at this juncture. That said, my resolve is feeble & curiosity is only curable by experimentation. Don’t worry Kevin, I decanted the hell out of it.</div><a href=""><img style="FLOAT: left; MARGIN: 0px 10px 10px 0px; WIDTH: 350px; CURSOR: hand; HEIGHT: 350px" alt="" src="" border="0" /></a><br /><div>While I’ve got one single reference vintage (’06), this was undoubtedly more structured, taut and had a depth in its core that only augmented my curiosity w/ regards to its potential (time machine anyone?). While I’m certainly an advocate of what Calera, Arcadian & the like have done in the vein of restraint & elegance, even those stalwarts don’t seem to have the poise, precision & seamlessness of young Rhys. The few Rhys Pinots that I’ve prematurely sent to the abattoir have an effortless, unaffected sensibility about them. I don’t mean to suggest that cool climate, New World Pinot Noir typically tastes as if it were ‘trying to’ emulate something, but whatever Kevin Harvey’s doing obliterates affectation altogether. There is no ‘try.’ </div><br /><div>If that’s the case, keep up the ‘lack’ of work, Kevin What’s the oldest vintage you’ve got in the cellar? How’s she doin’?</div><br /><div>Rhys Alpine Pinot '07</div><div>Its youth is obvious, though hardly painful in presentation. A bouquet in segments, with threads of flowers, olive and red cherry notes spread about an intricate tapestry. The core of the wine whispers, suggests its nature; veiled in a bright, flinty mystery that's awash in a nuanced, rocky river of minerality. Nothing but a hint, but what a view...and what finesse, 93+ points.</div><img src="" height="1" width="1" alt=""/>Brad Coelho cure for the '07 Chateauneuf hangover? An '06 horizontal<div>What’s the statute of limitations on note taking? A week? A month? A year? While I haven’t quite hit the latter mark, I feel as if my procrastination has been drawn out long enough to compel me to prostrate myself before you and repent. Let’s hope my brail-inflected chicken scratchings are reliable enough to jog my memory of a not so recent February evening. </div><div><br /.</div><div><br />I decided to put together a pow-wow of sorts for a young, but already forgotten vintage of Chateauneuf <img style="FLOAT: right; MARGIN: 0px 0px 10px 10px; WIDTH: 300px; CURSOR: hand; HEIGHT: 516px" alt="" src="" border="0" />du Pape, 2006. While ’06 lacks the snap, crackle and pop of recent juggernauts like ’05 & ’07, its wines also lack the high price tags. For those that feel overstuffed on opulence, hype & scores that ooze from the pours like salty sweat, I figured that some accounts on the still available, modestly priced 2006 vintage would be music to your ears (as well as mine). The beauty of tasting the ’06 vintage at this juncture is 3fold: </div><ul><li>The wines are cheap enough to sample the big boys, which are otherwise prohibitively expensive in top years </li><li>The character of the vintage is forward, fresh & easy on the palate, allowing for pleasurable samplings early & often </li><li>Bargain searchers have to strike while the iron is hot. Which values are legit & worth stocking up on before they disappear?</li></ul><p).</p><p>We commenced the tasting w/ a <strong>Boxler Riesling Sommerberg 2001</strong>, which has slid into a nice, ample phase. Its waxy aromatics gave way to a teeth-chattering profile of green apple and citrus, leaving an electric tinge on the tongue as it went down the gullet. The 2nd white, an <strong>’06 Clos des Papes blanc</strong>,).</p><p, <strong>Usseglio’s Mon Aieul</strong>. <strong>Mordoree Reine des Bois</strong> <strong>Janasse VV</strong> had expired. </p><p <strong>Clos St. Jean</strong> <strong>Beaucastel</strong> should taste like. Lastly, Paul’s final snafu came in the shape of <strong>Charvin</strong>,.<br /><a href=""><img style="FLOAT: left; MARGIN: 0px 10px 10px 0px; WIDTH: 162px; CURSOR: hand; HEIGHT: 180px" alt="" src="" border="0" /></a><br />Lucky number 7 happened to be the ringer, and although I’ve felt <strong>Tablas Creek</strong>. <strong>Perrin & Fils</strong> <strong>Mont Redon’s</strong> ’06 Chateauneuf du Pape. While this estate has been painted w/ an underachieving brush for years, this particular bottle was absolutely outstanding, dwarfing its performances in top years like ’98, ’00 & ’01.<br /></p><div><br /></div><p>Finally, I guessed <strong>Pegau</strong> <strong>Domaine et Selection</strong>,.’ </p><p>I seemed to have forgotten that Rich was in for a <strong>Clos St. Jean Combe des Fous</strong> :)</p><div>Wine Rating</div><div>Boxler Sommerberg Riesling 2001 92 points</div><div>Clos des Papes Blanc 2006 ?</div><div>Usseglio Mon Aieul 2006 93+ points</div><div>Mordoree Reine des Bois 2006 93+ points</div><div>Janasse VV 2006 95 points</div><div>Clos St. Jean CDP 2006 93 points</div><div>Beaucastel CDP 2006 90 points</div><div>Charvin CDP 2006 ?</div><div>Tablas Creek Esprit de Beaucastel 2006 91+ points</div><div>Perrin & Fils CDP 2006 ?</div><div>Mont Redon CDP 2006 93+ points</div><div>Pegau CDP 2006 92 points</div><div>Domaine et Selection 2006 92+ points</div><div>Clos St. Jean Combe des Fous 2006 96 points</div><img src="" height="1" width="1" alt=""/>Brad Coelho away from the breakdown laneIf wine is a moving target, the way we perceive wine makes the carousel spin even faster. There are plenty of cynical wine geeks that view wine as an extended dogma, perforating their experiences w/ bias and bullshit. Me, I just like wine. Perhaps I’m a bit too broad, but better to expand too far than contract too narrowly, I say. I’ve definitely got my sweet spots (eh-hem Chateauneuf du Pape), so I can’t say my tastes are so varied that my love of wine has become diffuse. While I’ve continued to jot down impressions of just about each bottle I drank over the past month, I have to admit that the backlog of notes has begun to clog up my hard drive space. I wouldn’t call February of 2010 a moratorium on wine writing, but I’d be remiss to not state that I’ve put on the e-brake w/ regards to my feverish documentation of detail. I began to write a post covering some impressions of a recent ’06 CDP horizon<a href=""><img style="FLOAT: right; MARGIN: 0px 0px 10px 10px; WIDTH: 457px; CURSOR: hand; HEIGHT: 288px" alt="" src="" border="0" /></a>tal, but it began to feel mechanical so I had to put the kybosh on it. No room for robotic servitude on this site.<br /><br />The wine bookworm has removed his spectacles and loosened his pocket protector a bit, but let’s not go so far as to say that he’s rockin’ the Cristal at the night clubs just yet. I’m still nerdy.<br /><br />During the past month I’ve committed multiple heretic behaviors that I previously considered inconceivable. I went to the Bahamas and drank ‘house wine’ without cringing. I dove through a deluge of drinks that may or may not have had umbrellas in them, loosening the skirt, err belt, to undisciplined proportions. I let my wife finish the bottle while I had a beer. Not just any bottle but a nice, hoard-worthy one. Oh, and I think I chugged Champagne from the bottle…maybe not Champagne Champagne, but the sparkling stuff from some non French country. You know the drill. Let’s just say I’ve splashed a bit of cold water on the old dome and stopped taking wine so damn seriously. I’ve blown up the bible and washed out my veins w/ some refreshing acidity for the soul.<br /><br />That said, I’m still inappropriately obsessed w/ fermented grape juice, I’ve just taken a bit respite; a sort of Lamaze breathing bump in the road to re-focus the faculties. Renowned wine critic Robert Parker takes a 2 week hiatus from wine each year to recharge the batteries, something I still can’t quite do but I’m beginning to embrace the concept. Who knows if it will balance things out for me or not? I doubt it, considering my wiring is more off-kilter than an Elephant Man’s gait. One step at a time…<br /><br />How do you stay sane w/in your passions? I suppose if you’ve already got a healthy relationship w/ wine you won’t need to change a thing; but how do you cool the engines when the smoky chassis starts to burn out?<img src="" height="1" width="1" alt=""/>Brad Coelho my father, liquid memories<img style="FLOAT: right; MARGIN: 0px 0px 10px 10px; WIDTH: 258px; CURSOR: hand; HEIGHT: 258px" alt="" src="" border="0" />I hardly grew up in a wine culture. My first pseudo alcohol experience was a lukewarm, frothy can of O'douls suds, “what beer drinkers drink when they’re not drinkin’ beer,” which encouraged me to ‘not drink beer’ for subsequent years to come. I always enjoyed the clinking sound that ice cubes made in my dad’s glasses of warming scotch, but never had the stomach for the strong stuff. Needless to say, I had to make my own way to the grape, and once I was smitten I couldn’t help but give back.<br /><br />Introducing wine to a Michelob Light and Macallan man is no easy task, so I let cinema do some of the work for me. He took to the buddy film ‘Sideways’ immediately, so Pinot Noir became an easy test subject. Knowing my father’s penchant for personal details, I figured some background noise on a producer would help do the trick. While I figured he’d find Burgundy too obscure (and his French prejudices wouldn’t exactly help the cause), I knew of a couple American Pinot producers that he could relate to. The character I chose was Gary Pisoni.<br /><br />I don’t know if it was Gary’s smuggling La Tache vines in his underwear, his uncoiled slinky locks of hair or more of a composite of his anecdotal of behavior that got my dad’s juices flowing, but the light sure was turned on. The first bottle of Gary’s we shared was a ’03 Capiaux, which technically wasn’t made by Pisoni but was a product of his viticulture nonetheless. I distinctly remember sitting at the bar next to my father, amidst our drunken and crude reverie and watching his face flush w/ genuine pleasure. The deep, woodsy, haunting flavors of the wine buzzed in our bellies like fireflies, softening his incredulous scowl into an easy smile. “Damn this is good, what the hell is this anyway?” he asked reverently. Thus began the legend of Gary Pisoni in Coelho folklore.<br /><br />Every visit I made up to Connecticut was another opportunity for me to wow my father w/ another bottle. I’d even worked up enough confidence and strength to tote some French bottles up there, with mixed success. Our dinners would typically be a vinous carousel of 2 or 3 bottles from different regions and different varietals, with the food playing a trifling tune in the shadows. It was tough to coax adjectives from my father’s mouth, particularly when he was drunk (I received the genetic gel of floridity from my mother), so I paid close attention to his grunts, gestures and facial expressions to gauge his opinion of each wine. Phrases like ‘damn that’s strong kid’ could be complementary or pejorative depending on the body language. We’d retire to the smoke room to discuss things over a cigar.<br /><br />Through the years he developed a fondness for Chilean Cabernet, Argentinean Malbec, Chateauneuf du Pape and Gewurztraminer from just about anywhere. No matter what the wine or how much he may have appreciated it, they didn’t seem to hold a candle to ‘the Pisoni.’ He wouldn’t always say it, but I could tell. For his 60th birthday I bought him a bottle of 2005 Pisoni Vineyard Pinot Noir, a bottle from the best fruit of his best vineyard, made by Gary’s son Jeff. I told him it wasn’t quite ready, but to give it a year or so and we’ll enjoy it together. It was a great evening.<br /><br />Over the last couple years I’d occasionally ask him when he’d open the Pisoni, to which he’d immediately jest ‘you said it wasn’t ready yet!’ ‘But dad, I said that over a year ago, you can pop it anytime you like.’ ‘It’s a special bottle for a special occasion,’ he’d say, and I could tell he’d be reluctant to ever open the damn thing. It’s not that he coveted it, but the few things in this life that were sacred to him were things he’d make sure you knew he didn’t take lightly. ‘I’ll only open it w<a href=""></a>ith you, but not now, not just yet.’<br /><br />I had an extra wine fridge that I gave my parents which housed the Pisoni. They felt too financially guilty to buy anything that exceeded Yellow Tail in price (too bad I don’t share their same frugality, I’d be le<a href=""><img id="BLOGGER_PHOTO_ID_5434803191037199906" style="FLOAT: left; MARGIN: 0px 10px 10px 0px; WIDTH: 240px; CURSOR: hand; HEIGHT: 320px" alt="" src="" border="0" /></a>ss broke) so the fridge was generally a mélange of 1.5 liter bottles of crappy Chilean Cabernet, dime store Merlot (which really made my dad feel guilty after watching Sideways) and the Pisoni. I’d toss a bottle or two in there on my visits, but they’d be vacated just about as quickly as they got there. I guess you could say that the Pisoni was the only bottle that could call that fridge home, as the rest were just transients.<br /><br />The morning my father died I went upstairs to the fridge and opened it. My first feeling upon seeing the bottle was of anger, as I blurted out ‘bastard never got to drink it,’ and I shed a futile tear or two. I thought to myself for a second and said, ‘screw it, we’re drinking that thing tonight.’ I wasn’t sure if I’d be able to act on impulse, or even if it were the right impulse, but at that point in the day I’d only slept an hour or so all night. My confidence in any thought I’d had was at a bloodless trough. I sat in the smoke room by myself with one of my dad’s cigars and thought aloud. I thought incoherently. Things didn’t really crystallize much in my mind until later that evening, until the rest of my family sat down together for dinner.<br /><br />I don’t remember what we ate, but I remember each face w/ 20/20 lucidity. We’d been crying most of the day; our eyes were dried up sponges and our nostrils, irrigation pipelines. Each look was of deprived malaise, fatigued and spilled, eating of obligation and bereft of pleasure. I got up from my father’s seat and grabbed the bottle. ‘I told dad this wasn’t ready when I gave it to him,’ I said, not fully intending on opening it unless the dried sponge eyes in the audience looked at me affirmatively. I stared for a moment into the crowd like a naked boy in the street begging for a blanket, waiting for a signal. Those faces seemed to nod their heads, as if to say yes, it has to be done. I popped the cork.<br /><br />I’m certain the words we toasted with were heartfelt, but I can’t say that I remember them. All I can remember is my mother whispering in my ear ‘the wine’s ready, Brad.’<img src="" height="1" width="1" alt=""/>Brad Coelho white that's worth searching for...<div>What’s been lost in Chateauneuf du Pape’s <strong>red</strong> hot run has been the progress the appellation has made w/ their white wines. While the trivial percentage of total acreage dedicated to white grapes is likely to remain in the single digits, few white wines in the world are as dynamic as Clos des Papes. The domaine utilizes just about every white grape allowed under A.O.C. law, providing a unique glimpse into the range and finesse of Chateauneuf du Pape blanc.<br /><br />Several popular micro-cuvees have become Roussanne dominated, which is likely the region’s most famous, and only 'noble' white grape. While Roussanne can produce exotic, viscous, exceptionally full-bottled wines packed with honeysuckle and rose water flavors, they tend to lack the freshness and mouth-watering acidity that most enophiles expect from fine white wine. While Clos des Papes does not omit Roussanne from the blend entirely, it’s clear that the singular, razor sharp edge of the wine is thanks to Roussanne’s supporting cast. <span style="font-family:Georgia;">The purity of the flavors is further preserved by an upbringing in stainless steel and neutral wood casks.</span> </div><br /><div>Fans of Huet & Foreau Vouvray or B<a href=""><img style="FLOAT: left; MARGIN: 0px 10px 10px 0px; WIDTH: 376px; CURSOR: hand; HEIGHT: 405px" alt="" src="" border="0" /></a>aumard Savennieres may particularly appreciate the waxy, bitter almond-like profile that Clos des Papes tends to express. In addition, Burgundy lovers are often blown away by how this wine evolves in the bottle, so tucking a few away for the cellar may also be worth your while (Rayas, Vieux Telegraphe & Beaucastel have solid track records for aging as well).</div><br /><div>Clos des Papes '06 Blanc CDP<br />This is always a terrific wine (as well as a great counterpoint to Beaucastel's Roussanne dominated blend) & one of which fans of fine Chenin Blanc should seek out. The coy nose is still reticent & taut, but the ethereal experience that unfolds in the mouth more than attones for its shy scent. A deceptively concentrated wine, packed w/ green tea, crunchy apple, macadamia nut and persimmon flavors that are tied together by a pleasantly bitter finish, which lets a shadow of honey sneak into the picture. A spry, nuanced beauty that is set for the cellar, 95 points.</div><br /><div>Clos des Papes '05 Blanc CDP</div><div>'05 is a quintessentially understated, finely crafted field blend that reveals the typically deft 'Avril touch.' Perhaps the archetypal example of the ‘whole’ netting a greater result than the sum of its parts, the subtle, penetrating sensations of lemon verbena, chamomile tea, paraffin, marzipan and quince reverberate on the reserved, yet deeply rich core. The flavors fan out beautifully on the long, cackling finish that leaves me breathless. This white’s focus is as cunning and chiseled as I’ve ever experienced from the Southern Rhone, and I imagine this won't peak for at least another decade, 95 points. </div><br /><div>Clos des Papes '98 Blanc CDP</div><div>Vincent Avril is a staunch advocate of waiting ten years to drink his white Chateauneuf. While I rarely possess the patience of waiting even ten <em>months</em> to drink any bottle of Clos des Papes, this ’98 makes a terrific case for following Avril's advice. The nose is subtle, as elegant notes of wild flowers, crushed stone, grilled hazelnuts and candied lemon verbena weave their way from the belly of the wine. In the mouth, the body is palpably sharp, with all the piercing pitch one would find in a fine Puligny Montrachet (minus the oxidation). The delicate, yet generous frame is the stuff White Burgundy dreams are made of, 92 points.</div><img src="" height="1" width="1" alt=""/>Brad Coelho search for the most value for the Rhone dollar continues<a href=""><img style="FLOAT: right; MARGIN: 0px 0px 10px 10px; WIDTH: 161px; CURSOR: hand; HEIGHT: 399px" alt="" src="" border="0" /></a><br /><div>While most traditional palates abhor the fruit-bomb generation of modern Chateauneuf, what I find is that the entry level cuvees of houses that are scarred by this rap (ie: Usseglio, Clos St. Jean, Beaurenard, etc.) tend to offer a profile that strikes a nice balance between the old & the new. While certain Rhone enthusiasts may still find Clos St. Jean’s Chateauneuf to be a tad ripe for their tastes, the ’06 vintage (along w/ ’04) emphasized freshness over flamboyance & may be just what the old world doctor ordered.<br /><br />It is exceptionally difficult to find a 19 dollar wine that approaches the depth of this baby.<br /><br />Clos St. Jean CDP '06<br />Cheaper than most CDRs, the '06 bail out continues to rain down on retail pavement. The nose is a pure distillation of black cherry liqueur, w/ a juicy, mouth-filling flush of bittersweet chocolate & sweet earth rounding out the palate. There's enough herbal bite to keep the lush, dark fruit flavors in check, paving the way for a fresh finish, 92+ points.</div><img src="" height="1" width="1" alt=""/>Brad Coelho | http://feeds.feedburner.com/UnidentifiedAppellation | CC-MAIN-2018-26 | refinedweb | 14,889 | 66.88 |
Quick Links
RSS 2.0 Feeds
Lottery News
Event Calendar
Latest Forum Topics
Web Site Change Log
RSS info, more feeds
Jun 20, 2007, 10:35 am
Treasure Hunt, Pennsylvania Lottery's terminal-based Pick 5 game, has exceeded sales expectations. The game, which went on sale May 8, was projected to bring in between $2.5 million and $3 million in its first quarter. Sales have surpassed $3 million.
Treasure Hunt is unique because it is animated online. Players get a grid numbered 1-30 and mark where they think the treasures are hidden. After the drawing at 1:35 p.m., the "sand" covered grid is shown online being cleared off, reveling five treasure chests. Winning numbers are also available in the usual places.
Locally, awareness of the game seems sparse. Several lottery players questioned were either not aware of the game or unsure how to play it.
"It's picking up," said Al Hossain, owner of US Mini Mart on West Main Street in Stroudsburg, but he has not seen any repeat customers yet. Treasure Hunt costs $1 to play. Jackpots start at $10,000.
The most popular lottery game Hossain sells is Powerball. "Pennsylvania Lottery is lousy," he said, because if people are going to put a dollar on the lottery, they want the big payoffs found in Powerball, where jackpots start at $15 million.
Most of Hossain's checkout counter is taken up by lottery information and tickets.
The Pennsylvania Lottery focuses on odds. One of the best odds going right now is the Millionaire Raffle Game, with the best odds for winning $1 million ever offered by the lottery, according to spokesperson Stephanie Weyant.
In this game, 625,000 tickets will be sold. They are available until 5 p.m. July 7. The drawing takes place at 7 p.m. that day. "Seven is a popular number for lottery players," Weyant said.
Retailers earn 5 percent commission from ticket sales. A bonus program also pays retailers cash, between $500 and $100 thousand, for selling jackpot tickets more than $100,000.
"People buy other items when they buy lottery tickets, and the commission money is helpful to small businesses," Weyant said.
But the deal is not as sweet as it once was. Winners of free tickets are time-consuming, and Hossain said retailers used to earn 1 percent of of winnings as low as $100. "We maintain the inventory for the lottery," said Hossain. Holding inventory for lottery tickets is like holding cash. The scratch-offs are tempting theft items, he said.
Related Links
Pocono Record'm from the Poconos. Take my advice, don't live here. It's boring.
Anyway, the reason the game has exceeded expectations is simple, great odds and great returns. It has the best top prize odds of any non-digit game, which people notice right off. And it has the highest prize return (58%), which players don't notice, but they do notice the higher instances of mid-range wins a high return allows. Add that with the $1 price, and it's enough for people to overlook the computerized drawings.
(insert signature here)
i think i can overlook it being computerized.the reason being is that this game is what players need.a 5/30 game that ain't so hard to beat.if lotto 5 in tennessee was 5/30 i would play every draw without fail.i'm just not that interested in longshot odds.5/39 got old quick....
Let's keep in mind several things:
1) PA's 5/39 game, that start off with Jackpots of $100,000+, are won quite regularly throughout the week (check the website to see how often!). $100,000. is far preferable to TH's measley $10,000!
2) That PA camoflauges or masks it's computer-ized 5/30 game with such graphics does not fool me. It's still computer-driven, meaning that its internal software can continue to scan ticket combinations purchased by players to carefully regulate when to "designate" a winner, or loser.
3) PA is wracking up profits while paying out such tiny prize amounts-- again, check the site to see the actual amounts won.
My recommendation? Jump up nine numbers to the 5/39 game, study number selection methods to learn how to eliminate those 9 extra numbers, and cash in on BIGGER prizes for the same hard-earned dollar you are plucking down.
"Always tell the truth-- that will astonish some and gratify the rest!"
-President Harry S. Truman, Democrat
I don't play it much because it is not life-changing money. I prefer the mid-range jackpots, anything from $500,000 up AFTER taxes. I wish it would build up more, but then I am sure 3 or more players would win.
But it's still computerized. It is a bad game. The PA lottery seems to be cheapening itself quite a bit.
One thing I've thought about with the PA Lottery: PA is in a self-made mass transit funding crisis. One of the things that the PA lottery does is subsidize transit for seniors. I'm sure there's a correlation.
I haven't yet won anything on T.Hunt, played it a few times but I do MUCH better with good old Cash 5. I often get 2 numbers so I often play for free, they don't give anything in nj for 2 numbers. I don't like computerized games either, but it's a Midday game so I try it one tkt when I play P'ball over there. I have yet to get more than maybe 1 # on T.Hunt which is maybe because it's RNG? I only play quickpicks for now (use an RNG to play an RNG) until I can systemize it.
I have got 2 and 3 out of 5 on treasure hunt, and a few in the same position and I only played it like 3 times. I would like to play more, but the jackpot it not enough for what I need. Although the extra money would be nice, it would not get me to where I need to be.
A few weeks ago I won $1 on a Treasure Hunt ticket. When Cash 5 was $500,000 I bought 5 tickets and got a free Treasure Hunt ticket as part of their promotion. That's the only way a computerized game ticket gets in my-2016 Speednet Group. All rights reserved. | https://www.lotterypost.com/news/157850 | CC-MAIN-2016-50 | refinedweb | 1,086 | 74.59 |
screen_create_window_type()
Create a new window of a specified type.
Synopsis:
#include <screen/screen.h>
int screen_create_window_type(screen_window_t *pwin, screen_context_t ctx, int type)
Since:
BlackBerry 10.0.0
Arguments:
- pwin
An address where the function can store the handle to the newly created native window.
- ctx
The connection to the composition manager to be used to create the window. This context must have been created with screen_create_context().
- type
The type of window to be created. type must be of type Screen_Window_Types.
Library:libscreen (For the qcc command, use the -l screen option to link against this library)
Description:
Function Type: Immediate Execution
This function creates a window object of the specified type.
Last modified: 2014-11-17
Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus | https://developer.blackberry.com/native/reference/core/com.qnx.doc.screen.lib_ref/topic/screen_create_window_type.html | CC-MAIN-2020-05 | refinedweb | 132 | 52.56 |
Recently I have developed few applications target to Pocket PC using .NET and SQL CE 2.0 .In this article I am sharing my experience on .NET compact framework and SQL CE .Its really very interesting and tuff to develop application for smart devices such PDA or smart phone . .NET Compact Framework 1.0 is a framework for developing mobile device application .It provides the power to run managed code and consume XML web services in smart devices. The most interesting point is the developers never feel much differences while developing compact edition (CE) application because compact framework is nothing but the subset of .NET framework that means it provides the same benefits what .NET framework is giving. We will discuss the differences between this two frameworks later in this article. The device must support Windows CE to run the applications build on .NET compact framework but exceptions for Microsoft pocket PC and Microsoft Pocket PC 2002 that supports .NET compact framework. Some of the benefits of compact framework are:
Now I am going to talk about some of the unsupported controls, events etc of .NET compact framework .The .NET compact framework primarily support for thick client (rich clients).When you are developing win forms using .NET compact framework few controls are unsupported like RichTextBox ,GroupBox, PrintControl, FontDialog , LinkLabel, ToolTip , Splitter, ColorDialog, CheckedListBox etc .Apart from this some of the events are unsupported like DoubleClick, Invalidated, FontChanged and few others like wise .NET compact framework does not support few properties such as Achor,Dock,CanFocus etc.
Before we conclude our discussion lets talk about the differences between .NET framework and compact framework . I have mentions few important points which we are using extensively in our day to day development process
Supported/Unsupported
Late bindings (Reflection)
Note: you can save the data in text format
For demonstration I have developed a sample application called "Employee Appraisal". The main purpose of this application is lets assume you are the project manager , you are planning to propose a good hikes for your team members .To discuss about your team members appraisal in the HR meeting you need to have the current salary of your team members, this application helps you to store the salary information of team. I have used Win Forms,ADOCE.NET and MS-SQL CE 2.0 to develop this application. Let me explain the inside of this application.
This application has two entry screen (forms) one is Employee , this form use for enter the employee name and salary , The ADD button add the employee information to the database and view button helps to display all employee information available in the database. Empview form responsible for display list of employees and there respective salarys.To interact with SQL CE I have developed SqlCeHleper class which have the functionality such as
The client (forms) interacts with the sqlce helper class to communicate with the database. I have not implement the full functionality what actually I am looking for is you to enhance this application like adding roles/responsibility of the employee , expected salary etc in employee entry screen or implement DataAdapter instead of DataReader to make loose coupling of database .You can say it's a beta version and try to give a high quality shape to this application .Download the application for enhancement or for reference purpose .Those who are new to smart device application can go through the below easy steps to create application for Pocket PC.Step1: Click on File->New Project menu option and select your desired language to develop the application and choose smart device application from the template
[Smart device application template to develop application for PDA]
Step2: Select the target platform ( in our example its Pocket PC) and select the type of project ( in our example its windows application ) .You can choose class library if you want to develop service component for smart device or if you want to develop console based application choose Non-graphical application
[Choose platform type and project type]ConclusionThe .NET Compact Framework is no doubt a much smaller set of classes of library than the .NET Framework, and .NET Compact Framework is tuned for size and performance for devices. Binary sizes are also distinct as the .NET Framework is about 20 times larger. The .NET Framework binary size is about 30MB, whereas the .NET Compact Framework is about 1.5MB.Both the .NET Framework and the .NET Compact Framework provide a consistent and familiar programming model. There are key similarities such as namespaces, classes, method names, properties, and data types. Programming is simplified and more secure due to the architecture and design of these platforms. Developers familiar with .NET Framework programming will find it easier adopting the .NET Compact Framework and will enjoy the same experience as developers who are familiar with the .NET Framework on top of this .NET compact framework provides automatically deployment of application and all dependencies ( in our example .NET compact framework, SQL CE and application itself) without users intervene.Now Microsoft is coming with still much more compact version of .NET library is called TinyCLR. TinyCLR. This is a version of the CLR that is smaller than the desktop version and even smaller than the Compact Framework version. It is the really tiner version and MS is able to put the TinyCLR on an integrated circuit running an ARM processor. This is what is in the watches today. The watch also has an FM radio reciver in it and this is how it receives information over the air to know more about it refer more information section of this article.More information
TinyCLR links
Programming with .NET Compact Framework 1.0 and SQL CE 2.0 : Part I
Overview of Automated Transcations
I want to use my j2me apps in windows mobile and want to access the local db sql ce is it possible .......thank u | http://www.c-sharpcorner.com/UploadFile/anandkrao/NETCFrameworkandSQLCE07262005031150AM/NETCFrameworkandSQLCE.aspx | crawl-003 | refinedweb | 982 | 56.96 |
increment a semaphore
#include <semaphore.h> int sem_post( sem_t *sem );
The sem_post() function increments the semaphore referenced by the sem argument. If any processes are currently blocked waiting for the semaphore, one of these processes will return successfully from its call to sem_wait.
The process to be unblocked is determined in accordance with the scheduling policies in effect for the blocked processes. The highest priority waiting process is unblocked, and if there's more than one highest priority process blocked waiting for the semaphore, the highest priority process that has been waiting the longest is unblocked.
/usr/demo/src/semaphores
POSIX 1003.1b-1993
errno, sem_destroy(), sem_init(), sem_trywait(), sem_wait() | https://users.pja.edu.pl/~jms/qnx/help/watcom/clibref/qnx/sem_post.html | CC-MAIN-2022-33 | refinedweb | 109 | 56.66 |
How to: Implement Events in Your Class
The following procedures describe how to implement an event in a class. The first procedure implements an event that does not have associated data; it uses the classes System.EventArgs and System.EventHandler for the event data and delegate handler. The second procedure implements an event with custom data; it defines custom classes for the event data and the event delegate handler.
For a complete sample that illustrates raising and handling events, see How to: Raise and Consume Events.
To implement an event without event-specific data
Define a public event member in your class. Set the type of the event member to a System.EventHandler delegate.
Provide a protected method in your class that raises the event. Name the method OnEventName. Raise the event within the method.
Determine when to raise the event in your class. Call OnEventName to raise the event.
To implement an event with event-specific data
Define a class that provides data for the event. Name the class EventNameArgs, derive the class from System.EventArgs, and add any event-specific members.
public class AlarmEventArgs : EventArgs { private readonly int nrings = 0; private readonly bool snoozePressed = false; //Constructor. public AlarmEventArgs(bool snoozePressed, int nrings) { this.snoozePressed = snoozePressed; this.nrings = nrings; } //Properties. public string AlarmText { ... } public int NumRings { ... } public bool SnoozePressed{ ... } }
Public Class AlarmEventArgs Inherits EventArgs Private nrings As Integer = 0 Private _snoozePressed As Boolean = False 'Constructor. Public Sub New(ByVal snoozePressed As Boolean, ByVal nrings As Integer) Me.snoozePressed = snoozePressed Me.nrings = nrings End Sub 'Properties. Public ReadOnly Property AlarmText() As String ... End Property Public ReadOnly Property NumRings() As Integer ... End Property Public ReadOnly Property SnoozePressed() As Boolean ... End Property End Class
Declare a delegate for the event. Name the delegate EventNameEventHandler.
Define a public event member named EventName in your class. Set the type of the event member to the event delegate type.
Define a protected method in your class that raises the event. Name the method OnEventName. Raise the event within the method.
Determine when to raise the event in your class. Call OnEventName to raise the event and pass in the event-specific data using EventNameEventArgs.
See Also
TasksHow to: Raise and Consume Events
ConceptsEvents and Delegates
Raising an Event | https://msdn.microsoft.com/en-us/library/5z57dxz2(v=vs.85).aspx | CC-MAIN-2015-18 | refinedweb | 373 | 62.34 |
A python package for your sinric alexa skill
Project description
- This is a python library for alexa home automation skill
SINRIC ()
Functions:
Control your home appliances using alexa
Installation :
Python3
pip3 install pysinric --user
or
Python
pip install pysinric --user
Implementing :
from sinric import Sinric from time import sleep apiKey = 'Replace with your api key' # response = any if __name__ == '__main__': obj = Sinric(apiKey) while True: response = obj.initialize() print(response) sleep(2)
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
pysinric-0.1.1.tar.gz (2.6 kB view hashes) | https://pypi.org/project/pysinric/ | CC-MAIN-2022-40 | refinedweb | 108 | 51.78 |
specialization for bool. More...
#include <cxxtools/arg.h>
Detailed Description
template<>
class cxxtools::Arg< bool >
specialization for bool.
Often programs need some switches, which are switched on or off. Users just enter a option without parameter.
example:
Constructor & Destructor Documentation
default constructor.
Initializes value.
- Parameters
-
Use this constructor to extract a bool-parameter.
As a special case options can be grouped. The parameter is recognized also in a argument, which starts with a '-' and contains somewhere the given character.
example:
Arguments debug and ignore are both set when the program is called with:
Options can also switched off with a following '-' like this:
In the program use:
This is useful, if a program defaults to some enabled feature, which can be disabled.
Member Function Documentation
returns true, if options is not set.
returns true, if options is set.
convertable to bool.
Setter for long-options.
The option-parameter is defined with a string. This can extract long-options like:
with
The documentation for this class was generated from the following file: | http://www.tntnet.org/apidoc_stable/html/classcxxtools_1_1Arg_3_01bool_01_4.html | CC-MAIN-2018-09 | refinedweb | 171 | 51.95 |
In this post, our journey through the functional features of classical, modern, and future C++ continues. Today, we stop in the present.
In 2005, 13 libraries based on Boost, were proposed in the so called technical report 1 (TR1) as candidates for the upcoming C++ standard. 12 of them made it into C++11 including the two functions std::bind and std::function. Both functions work very well together. On one hand, std::bind empowers you to easily make function objects. At the other hand, std::functions gets this temporary function objects from std::bind and gives them a name. Both functions need the header <functional>. You can guess, why.
You can generate with std::bind function objects in various ways, because it empowers you to
std::function is a polymorphic function wrapper. Therefore, it can take arbitrary callables and give them a name. Callables are all entities which behave like a function. In particular, these are lambda-functions, function objects, and functions themselves. std::function is always needed, if you have to specify the type of a callable.
That was enough theory. Lets starts with the more interesting stuff.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// bindAndFunction.cpp
#include <functional>
#include <iostream>
double divMe(double a, double b){
return double(a/b);
}
using namespace std::placeholders;
int main(){
std::cout << std::endl;
// invoking the function object directly
std::cout << "1/2.0= " << std::bind(divMe, 1, 2.0)() << std::endl;
// placeholders for both arguments
std::function<double(double, double)> myDivBindPlaceholder= std::bind(divMe, _1, _2);
std::cout << "1/2.0= " << myDivBindPlaceholder(1, 2.0) << std::endl;
// placeholders for both arguments, swap the arguments
std::function<double(double, double)> myDivBindPlaceholderSwap= std::bind(divMe, _2, _1);
std::cout << "1/2.0= " << myDivBindPlaceholderSwap(2.0, 1) << std::endl;
// placeholder for the first argument
std::function<double(double)> myDivBind1St= std::bind(divMe, _1, 2.0);
std::cout<< "1/2.0= " << myDivBind1St(1) << std::endl;
// placeholder for the second argument
std::function<double(double)> myDivBind2Nd= std::bind(divMe, 1.0, _1);
std::cout << "1/2.0= " << myDivBind2Nd(2.0) << std::endl;
std::cout << std::endl;
}
Do you want to see a few variations of invoking divMe (line 6 - 8). In order to use the simple notation _1, _2 for the placeholders std::placeholders::_1, std::placeholders::_2 in the source code, I have to introduce the namespace std::placeholders in line 10.
I bind in line 17 in the expression std::bind(divMe, 1, 2.0) the arguments 1 and 2.0 to the function divMe and invoke them in place with (). I bind in line 20 the function object and invoke it with the arguments 1 and 2.0. Line 24, 28, and 32 follows a similar strategy. I change the sequence of the arguments in line 24. In line 28, only the first argument is bound; in line 32, only the second argument. std::function gets the resulting function objects. Template arguments like double(double, double) (line 24) or double(double) (line 28 and 32) stands for the type of the callable, which std::function accepts. double(double, double) is a function taking two doubles and returning a double.
At the end, the output of the program.
Impressed? I guess, yes. In particular, the last two examples in which std::function gets a function of arity two and returns a function of arity one is quite astonising. The arity of a function is the number of arguments a function gets. std::bind evaluates in both calls only one argument and uses for the non-evaluated one a placeholder. This technique is called partial function application.
Partial function application is quite similar to a technique called currying. Currying is well known in functional programming. It stands for a technique in which a function taking more than one argument will successively be transformed in series of function taking only one argument. Therefore, there are in programming language Haskell only functions taking one argument. I hear your question. How is it possible to implement a function such as add which needs two arguments. The magic is happening implicitly. Functions in Haskell, that needs n arguments are transformed in functions returning a function, which only needs n-1 arguments. The first elements is evaluated in this transformation.
The name currying is coined by the mathematician Haskell Curry and Moses Schönfinkel. Currying is named after the family name of Haskell Curry; Haskell after his first name. Sometimes, currying is called schönfinkeln.
A drop of bitterness remains. As well std::bind as std::function are almost superfluous with C++11. You can use lambda-functions instead of std::bind, you can use most of the times automatic type deduction with auto instead of std::function. With the enriched core language in C++11, we can quite easily rewrite the program.
// lambdaAndAuto.cpp
#include <functional>
#include <iostream>
double divMe(double a, double b){
return double(a/b);
}
using namespace std::placeholders;
int main(){
std::cout << std::endl;
// invoking the function object directly
std::cout << "1/2.0= " << [](int a, int b){ return divMe(a, b); }(1, 2.0) << std::endl;
// placeholders for both arguments
auto myDivBindPlaceholder= [](int a, int b){ return divMe(a, b); };
std::cout << "1/2.0= " << myDivBindPlaceholder(1, 2.0) << std::endl;
// placeholders for both arguments, swap the arguments
auto myDivBindPlaceholderSwap= [](int a, int b){ return divMe(b, a); };
std::cout << "1/2.0= " << myDivBindPlaceholderSwap(2.0, 1) << std::endl;
// placeholder for the first argument
auto myDivBind1St= [](int a){ return divMe(a, 2.0); };
std::cout<< "1/2.0= " << myDivBind1St(1) << std::endl;
// placeholder for the second argument
auto myDivBind2Nd= [](int b){ return divMe(1, b); };
std::cout << "1/2.0= " << myDivBind2Nd(2.0) << std::endl;
std::cout << std::endl;
}
Let me say a few words about the lambda-functions. The expression [](int a, int b){ return divMe(a, b); }(1, 2.0) defines a lambda-function that executes divMe. The trailing braces invoke the lambda-function just in place. This will not hold for the lambda-functions in line 28 and 32. Both will be invoked in the subsequent lines. The impressing fact is that the lambda-function binds the first (line 32) or the second argument (line 28).
The polymorph function wrapper std::function can most of the times be replaced by auto. Most of the times because sometimes you have the explicitly specify the type of the callable. That is the domain of std::function. A typical example for such a use case is a dispatch table which I will present in the next post.
Go to Leanpub/cpplibrary "What every professional C++ programmer should know about the C++ standard library". Get your e-book. Support my blog.
Name (required)
Website
Notify me of follow-up comments
Read more...
Hunting
Today 610
All 382632
Currently are 174 guests and no members online
I am actually enjoying by these.
come with approximately all significant infos.
I would like to peer extra posts like this . | http://modernescpp.com/index.php/functional-in-tr1-and-c-11 | CC-MAIN-2017-34 | refinedweb | 1,190 | 59.19 |
On Thursday 26 March 2009 10:26:13 pm Russ Allbery wrote: > "Gerald I. Evenden" <address@hidden> writes: > > I am quite new to using this system but managed to get it to make a > > distribution of a shared library. The first try was, however, simple > > and straight forward. > > > > However, I want selectively add two files to the library based upon the > > condition that they are *not* present on the target computer. In > > configure.ac I added the lines: > > > > AC_CHECK_FUNCS([strcasecmp strncasecmp],[CASECMP=1],[CASECMP=0]) > > AM_CONDITIONAL([NOCASECMP],[test CASECMP = 0]) > > You need a $CASECMP here, not CASECMP. That's interesting. I had no idea although I guess I should have. > However, more fundamentally, you're reinventing AC_REPLACE_FUNC, which you > probably don't want to do. Check the Autoconf manual for AC_REPLACE_FUNC, > which does exactly what you're trying to do, even down to how it adds > additional source files to a variable that you can use in Makefile.am. I had seen it but, again, I was unsure how it was going to work. I will reread. Also, I am not replacing functions with a new name but adding the source with the same entry names to be compiled into the new library. The documentation is a bit fuzzy to me in this area. > > In Makefile.am I added the lines: > > > > if NOCASECMP > > libproject_la_sources += strcasecmp.c strncasecmp.c > > You need an endif here, which may also be part of the problem with the > errors you're seeing. In the monkey-see-monkey-do example I was working from did not have an endif. So much for my reading material. > Taking yet another step back, do you have a target system in mind that > doesn't have strcasecmp? It's required by POSIX and is usually in the set > of things that aren't worth bothering checking for unless you're porting > to Windows (which particularly for shared libraries involves quite a bit > of work that Automake can't entirely help with). This is a tryout case that will become more complex later when the library grows to its 150 or so files and there may be other places where optional inclusion may be a factor especially where some potential users will accept the X11 license I distribute under but don't want to be involved with GPL and will want to use alternate software. As far as the case insensitive routines, yes, part of the motive was because of M$ but I heard some rumblings that they may be missing at some other OSs. Many thanks for the comments. -- The whole religious complexion of the modern world is due to the absence from Jerusalem of a lunatic asylum. -- Havelock Ellis (1859-1939) British psychologist | http://lists.gnu.org/archive/html/automake/2009-03/msg00066.html | CC-MAIN-2014-49 | refinedweb | 454 | 61.26 |
^operator isn't used for powers, it is actually the bitwise exclusive or XOR.
b*b
pow()function to raise a number to other powers)
sqrt()function
#include <cmath>header for those functions.
int. I'd recommend that you use a floating-point type for all the variables in this case. Type
doublewould be usual,
floatwould work but it's less precise and I'd not recommend it for everyday use.
^is not power. You need to use the function
pow()instead:
(1/2)will result in 0 since it's an integer operation. Use at least one none integer value like
(1.0/2) | http://www.cplusplus.com/forum/beginner/111105/ | CC-MAIN-2015-14 | refinedweb | 105 | 66.84 |
In my website I have some dynamic pages and I noticed when I finish the first version that was hard to integrate them into the website.
I found this code here in the forum:
import wixLocation from 'wix-location';
$w.onReady(function () {
wixLocation.to("/proxEventos/");
})
It worked fine, however just in the administrator version. For all the members it is not working and showing an error 403 or 404.
have you ever experienced one issue like this of the code working only on admin version and how could I solve this problem.
Please help me,
thanks so much
best,
JJ
Then it is a security / permission issue. The 403 says permission denied. So what permission is setup on the page /proxEventos ? I think admin only and that is the reason they get that error.
Hello, Could you just let me know if I am doing it wrong... I have been trying this with the admin I see 404, with other passwords I see 403.
I check the permission and it seems that is open for everyone, however it is not working yet
look these prints
thank you very much!!!!
@emaildojoaoh im with the same problema. Its happens when we try to access a dynamic page without logged in. Im looking for some way to make a "Public" Page, that people only make a log in on checkout
The issue with the above link is that they are trying to access the static url part only of the dynamic page url. They needed to add the dynamic part of the url after that static url part.
Have a look at this tutorial for a simple members profile page which creates two dynamic members profile pages for each member.
You will notice on the first dynamic page they have done the link above in their code, however it is followed up by a dynamic bit in the {ID), in this tutorial it is highlighted as a ID block.
So like this{ID}
The same with the second dynamic page for the update profile page where they add the /Update/{ID}.
Take your test with it.
Use this site in your browsers bar...
It will load up fine and you can use it to get lots of info about dynamic pages.
However, try deleting the dynamic-pages part of the url and you get what the forum user originally had in their wix location to link....
it won't load up, you will get the 404 error screen.
Okay enough waffle, have a read of the dynamic pages link above and of these pages too if they are not already included in that section. | https://www.wix.com/corvid/forum/community-discussion/dynamic-pages-please-help | CC-MAIN-2020-16 | refinedweb | 441 | 70.84 |
locale.h - category macros
#include <locale.h>
[CX]
Some of the functionality described on this reference page extends the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of IEEE Std 1003.1-2001 defers to the ISO C standard
[CX] *);
None.
None.
None.
The System Interfaces volume of IEEE Std 1003.1-2001, localeconv(), setlocale(), Environment Variables
First released in Issue 3.
Included for alignment with the ISO C standard.
The lconv structure is expanded with new members ( int_n_cs_precedes, int_n_sep_by_space, int_n_sign_posn, int_p_cs_precedes, int_p_sep_by_space, and int_p_sign_posn) for alignment with the ISO/IEC 9899:1999 standard.
Extensions beyond the ISO C standard are marked. | http://pubs.opengroup.org/onlinepubs/009695399/basedefs/locale.h.html | CC-MAIN-2018-05 | refinedweb | 113 | 52.36 |
64722/excel-json-import-error-current-preview-value-complex-display
Main Problem: I'm trying to import .json to excel for pivot table. The data contains 4.000.000 rows and i have to create pivot table for summarize the data (My company uses excel because of company structure, so i have to). When i import the json file, excel shows this error: "The type of current preview value is too complex to display".
Statement:
I'm taking the data from excel (5 sheets, because of excel data limitation i have to merge the data). I use these codes for reading excel datasets:
import numpy as pd
df1 = pd.read_excel(r'C:/Users/...Data Location 1')
df2 = pd.read_excel(r'C:/Users/...Data Location 2')
df3 = pd.read_excel(r'C:/Users/...Data Location 3')
df4 = pd.read_excel(r'C:/Users/...Data Location 4')
df5 = pd.read_excel(r'C:/Users/...Data Location 5')
And i merge and export the data with these codes:
import json
frames = [df1,df2,df3,df4,df5]
data = pd.concat(frames,ignore_index=True)
data.to_json(r'C:/Users/.../data.json')
And finally i am trying to import data.json to excel for pivot table (as query, so data limitation problem in excel will not be a problem anymore). In this way i will be combine the dataset only with one file. But when i import the data "The type of current preview value is too complex to display" error is rising. What should i do? Is there any alternative method?
Thanks for your answer in advance.
Hi, @There,
Make sure that your MongoDB instance ...READ MORE
I think you need to create some ...READ MORE
my_list = [1,2,3,4,5,6,7]
len(my_list)
# 7
The same works for ...READ MORE
To print the message that file is not ...READ MORE
Hi. Nice question.
Here is the simplified answer ...READ MORE
Execute the following command on your terminal:
python ... | https://www.edureka.co/community/64722/excel-json-import-error-current-preview-value-complex-display?show=64800 | CC-MAIN-2022-33 | refinedweb | 323 | 61.22 |
What's new in F# 5.0
F# 5.0 adds several improvements to the F# language and F# Interactive. It is released with .NET 5.
You can download the latest .NET SDK from the .NET downloads page.
F# 5.0 is available in all .NET Core distributions and Visual Studio tooling. For more information, see Get started with F# to learn more.
Package references in F# scripts
F# 5 brings support for package references in F# scripts with
#r "nuget:..." syntax. For example, consider the following package reference:
#r "nuget: Newtonsoft.Json" open Newtonsoft.Json let o = {| X = 2; Y = "Hello" |} printfn "%s" (JsonConvert.SerializeObject o)
You can also supply an explicit version after the name of the package like this:
#r "nuget: Newtonsoft.Json,11.0.1"
Package references support packages with native dependencies, such as ML.NET.
Package references also support packages with special requirements about referencing dependent
.dlls. For example, the FParsec package used to require that users manually ensure that its dependent
FParsecCS.dll was referenced first before
FParsec.dll was referenced in F# Interactive. This is no longer needed, and you can reference the package as follows:
#r "nuget: FParsec" open FParsec let test p str = match run p str with | Success(result, _, _) -> printfn "Success: %A" result | Failure(errorMsg, _, _) -> printfn "Failure: %s" errorMsg test pfloat "1.234"
This feature implements F# Tooling RFC FST-1027. For more information on package references, see the F# Interactive tutorial.
String interpolation
F# interpolated strings are fairly similar to C# or JavaScript interpolated strings, in that they let you write code in "holes" inside of a string literal. Here's a basic example:
let name = "Phillip" let age = 29 printfn $"Name: {name}, Age: {age}" printfn $"I think {3.0 + 0.14} is close to {System.Math.PI}!"
However, F# interpolated strings also allow for typed interpolations, just like the
sprintf function, to enforce that an expression inside of an interpolated context conforms to a particular type. It uses the same format specifiers.
let name = "Phillip" let age = 29 printfn $"Name: %s{name}, Age: %d{age}" // Error: type mismatch printfn $"Name: %s{age}, Age: %d{name}"
In the preceding typed interpolation example, the
%s requires the interpolation to be of type
string, whereas the
%d requires the interpolation to be an
integer.
Additionally, any arbitrary F# expression (or expressions) can be placed in side of an interpolation context. It is even possible to write a more complicated expression, like so:
let str = $"""The result of squaring each odd item in {[1..10]} is: { let square x = x * x let isOdd x = x % 2 <> 0 let oddSquares xs = xs |> List.filter isOdd |> List.map square oddSquares [1..10] } """
Although we don't recommend doing this too much in practice.
This feature implements F# RFC FS-1001.
Support for nameof
F# 5 supports the
nameof operator, which resolves the symbol it's being used for and produces its name in F# source.) (sprintf "%s" (M.f 12) printfn "%s" (nameof M) printfn "%s" (nameof M.f)
Three final additions are changes to how operators work: the addition of the
nameof<'type-parameter> form for generic type parameters, and the ability to use
nameof as a pattern in a pattern match expression.
Taking a name of an operator gives its source string. If you need the compiled form, use the compiled name of an operator:
nameof(+) // "+" nameof op_Addition // "op_Addition"
Taking the name of a type parameter requires a slightly different syntax:
type C<'TType> = member _.TypeName = nameof<'TType>
This is similar to the
typeof<'T> and
typedefof<'T> operators.
F# 5 also adds support for a
nameof pattern that can be used in
match expressions:
[<Struct; IsByRefLike>] type RecordedEvent = { EventType: string; Data: ReadOnlySpan<byte> } type MyEvent = | AData of int | BData of string let deserialize (e: RecordedEvent) : MyEvent = match e.EventType with | nameof AData -> AData (JsonSerializer.Deserialize<int> e.Data) | nameof BData -> BData (JsonSerializer.Deserialize<string> e.Data) | t -> failwithf "Invalid EventType: %s" t
The preceding code uses 'nameof' instead of the string literal in the match expression.
This feature implements F# RFC FS-1003.
Open type declarations
F# 5 also adds support for open type declarations. An open type declaration is like opening a static class in C#, except with some different syntax and some slightly different behavior to fit F# semantics.
With open type declarations, you can
open any type to expose static contents inside of it. Additionally, you can
open F#-defined unions and records to expose their contents. For example, this can be useful if you have a union defined in a module and want to access its cases, but don't want to open the entire module.
open type System.Math let x = Min(1.0, 2.0) module M = type DU = A | B | C let someOtherFunction x = x + 1 // Open only the type inside the module open type M.DU printfn "%A" A
Unlike C#, when you
open type on two types that expose a member with the same name, the member from the last type being
opened shadows the other name. This is consistent with F# semantics around shadowing that exist already.
This feature implements F# RFC FS-1068.
Consistent slicing behavior for built-in data types
Behavior for slicing the built-in
FSharp.Core data types (array, list, string, 2D array, 3D array, 4D array) used to not be consistent prior to F# 5. Some edge-case behavior threw an exception and some wouldn't. In F# 5, all built-in types now return empty slices for slices that are impossible to generate:
let l = [ 1..10 ] let a = [| 1..10 |] let s = "hello!" // Before: would return empty list // F# 5: same let emptyList = l.[-2..(-1)] // Before: would throw exception // F# 5: returns empty array let emptyArray = a.[-2..(-1)] // Before: would throw exception // F# 5: returns empty string let emptyString = s.[-2..(-1)]
This feature implements F# RFC FS-1077.
Fixed-index slices for 3D and 4D arrays in FSharp.Core
F# 5.0 brings support for slicing with a fixed index in the built-in 3D and 4D array types.
To illustrate this, consider the following 3D array:
z = 0 | x\y | 0 | 1 | |-------|---|---| | 0 | 0 | 1 | | 1 | 2 | 3 |
z = 1 | x\y | 0 | 1 | |-------|---|---| | 0 | 4 | 5 | | 1 | 6 | 7 |
What if you wanted to extract the slice
[| 4; 5 |] from the array? This is now very simple!
// First, create a 3D array to slice let dim = 2 let m = Array3D.zeroCreate<int> dim dim dim let mutable count = 0 for z in 0..dim-1 do for y in 0..dim-1 do for x in 0..dim-1 do m.[x,y,z] <- count count <- count + 1 // Now let's get the [4;5] slice! m.[*, 0, 1]
This feature implements F# RFC FS-1077b.
F# quotations improvements
F# code quotations now have the ability to retain type constraint information. Consider the following example:
open FSharp.Linq.RuntimeHelpers let eval q = LeafExpressionConverter.EvaluateQuotation q let inline negate x = -x // val inline negate: x: ^a -> ^a when ^a : (static member ( ~- ) : ^a -> ^a) <@ negate 1.0 @> |> eval
The constraint generated by the
inline function is retained in the code quotation. The
negate function's quoted form can now be evaluated.
This feature implements F# RFC FS-1071.
Applicative Computation Expressions
Computation expressions (CEs) are used today to model "contextual computations", or in more functional programming-friendly terminology, monadic computations.
F# 5 introduces applicative CEs, which offer a different computational model. Applicative CEs allow for more efficient computations provided that every computation is independent, and their results are accumulated at the end. When computations are independent of one another, they are also trivially parallelizable, allowing CE authors to write more efficient libraries. This benefit comes at a restriction, though: computations that depend on previously computed values are not allowed.
The follow example shows a basic applicative CE for the
Result type.
// First, define a 'zip' function module Result = let zip x1 x2 = match x1,x2 with | Ok x1res, Ok x2res -> Ok (x1res, x2res) | Error e, _ -> Error e | _, Error e -> Error e // Next, define a builder with 'MergeSources' and 'BindReturn' type ResultBuilder() = member _.MergeSources(t1: Result<'T,'U>, t2: Result<'T1,'U>) = Result.zip t1 t2 member _.BindReturn(x: Result<'T,'U>, f) = Result.map f x let result = ResultBuilder() let run r1 r2 r3 = // And here is our applicative! let res1: Result<int, string> = result { let! a = r1 and! b = r2 and! c = r3 return a + b - c } match res1 with | Ok x -> printfn "%s is: %d" (nameof res1) x | Error e -> printfn "%s is: %s" (nameof res1) e let printApplicatives () = let r1 = Ok 2 let r2 = Ok 3 // Error "fail!" let r3 = Ok 4 run r1 r2 r3 run r1 (Error "failure!") r3
If you're a library author who exposes CEs in their library today, there are some additional considerations you'll need to be aware of.
This feature implements F# RFC FS-1063.
Interfaces can be implemented at different generic instantiations
You can now implement the same interface at different generic instantiations:
type IA<'T> = abstract member Get : unit -> 'T type MyClass() = interface IA<int> with member x.Get() = 1 interface IA<string> with member x.Get() = "hello" let mc = MyClass() let iaInt = mc :> IA<int> let iaString = mc :> IA<string> iaInt.Get() // 1 iaString.Get() // "hello"
This feature implements F# RFC FS-1031.
Default interface member consumption
F# 5 lets you consume interfaces with default implementations.
Consider an interface defined in C# like this:
using System; namespace CSharp { public interface MyDimasd { public int Z => 0; } }
You can consume it in F# through any of the standard means of implementing an interface:
open CSharp // You can implement the interface via a class type MyType() = member _.M() = () interface MyDim let md = MyType() :> MyDim printfn "DIM from C#: %d" md.Z // You can also implement it via an object expression let md' = { new MyDim } printfn "DIM from C# but via Object Expression: %d" md'.Z
This lets you safely take advantage of C# code and .NET components written in modern C# when they expect users to be able to consume a default implementation.
This feature implements F# RFC FS-1074.
Simplified:
#r "nuget: Microsoft.Data.Analysis" open Microsoft.Data.Analysis let dateTimes = PrimitiveDataFrameColumn<DateTime>("DateTimes") // The following line used to fail to compile dateTimes.Append(DateTime.Parse("2019/01/01")) // The previous line is now equivalent to this line dateTimes.Append(Nullable<DateTime>(DateTime.Parse("2019/01/01")))
This feature implements F# RFC FS-1075.
Preview: reverse indexes
F# 5 also introduces a preview for allowing reverse indexes. The syntax is
^idx. Here's how you can an element 1 value from the end of a list:
let xs = [1..10] // Get element 1 from the end: xs.[^1] // From the end slices let lastTwoOldStyle = xs.[(xs.Length-2)..] let lastTwoNewStyle = xs.[^1..] lastTwoOldStyle = lastTwoNewStyle // true
You can also define reverse indexes for your own types. To do so, you'll need to implement the following method:
GetReverseIndex: dimension: int -> offset: int
Here's an example for the
Span<'T> type:
open System type Span<'T> with member sp.GetSlice(startIdx, endIdx) = let s = defaultArg startIdx 0 let e = defaultArg endIdx sp.Length sp.Slice(s, e - s) member sp.GetReverseIndex(_, offset: int) = sp.Length - offset let printSpan (sp: Span<int>) = let arr = sp.ToArray() printfn "%A" arr let run () = let sp = [| 1; 2; 3; 4; 5 |].AsSpan() // Pre-# 5.0 slicing on a Span<'T> printSpan sp.[0..] // [|1; 2; 3; 4; 5|] printSpan sp.[..3] // [|1; 2; 3|] printSpan sp.[1..3] // |2; 3|] // Same slices, but only using from-the-end index printSpan sp.[..^0] // [|1; 2; 3; 4; 5|] printSpan sp.[..^2] // [|1; 2; 3|] printSpan sp.[^4..^2] // [|2; 3|] run() // Prints the same thing twice
This feature implements F# RFC FS-1076.
Preview:.
F# 5 adds preview support for overloading custom operations in Computation Expressions. It allows the following code to be written and consumed:
open System type InputKind = | Text of placeholder:string option | Password of placeholder: string option type InputOptions = { Label: string option Kind : InputKind Validators : (string -> bool) array } type InputBuilder() = member t.Yield(_) = { Label = None Kind = Text None Validators = [||] } [<CustomOperation("text")>] member this.Text(io, ?placeholder) = { io with Kind = Text placeholder } [<CustomOperation("password")>] member this.Password(io, ?placeholder) = { io with Kind = Password placeholder } [<CustomOperation("label")>] member this.Label(io, label) = { io with Label = Some label } [<CustomOperation("with_validators")>] member this.Validators(io, [<ParamArray>] validators) = { io with Validators = validators } let input = InputBuilder() let name = input { label "Name" text with_validators (String.IsNullOrWhiteSpace >> not) } let email = input { label "Email" text "Your email" with_validators (String.IsNullOrWhiteSpace >> not) (fun s -> s.Contains "@") } let password = input { label "Password" password "Must contains at least 6 characters, one number and one uppercase" with_validators (String.exists Char.IsUpper) (String.exists Char.IsDigit) (fun s -> s.Length >= 6) }
Prior to this change, you could write the
InputBuilder type as it is, but you couldn't use it the way it's used in the example. Since overloads, optional parameters, and now
System.ParamArray types are allowed, everything just works as you'd expect it to.
This feature implements F# RFC FS-1056. | https://docs.microsoft.com/en-us/dotnet/fsharp/whats-new/fsharp-50 | CC-MAIN-2020-50 | refinedweb | 2,211 | 58.79 |
if statement - Edit Order confirmation on Shopify
I've been editing the code of the order confirmation on my Shopify store, my target is that if a customer orders a product with "this" tag and the transaction type is "Bank Transfer" then it will show "this" text. I've been trying to edit it but the code doesn't reflect on the email notification of the user. Can anyone have an Idea about this?
My Code looks like this:
{% assign found_pnmm = false %} {% assign found_svmml = false %} {% for line in subtotal_line_items %} {% if product.tags contains 'PNMM' and transaction.gateway == 'Bank Transfer' %} {% assign found_pnmm = true %} {% elsif product.tags contains 'SVMML' and transaction.gateway == 'Bank Transfer' %} {% assign found_svmml = true %} {% endif %} {% endfor %} {% if found_pnmm %} <p><strong>show this</strong></p> {% elsif found_svmml %} <p><strong>show that</strong></p> {% endif %}
Answer
Solution:
Your issue is probably coming from these lines:
{% if product.tags contains 'PNMM' and transaction.gateway == 'Bank Transfer' %}
and
{% elsif product.tags contains 'SVMML' and transaction.gateway == 'Bank Transfer' %}
You are trying to access
product.tags, but in the context here,
product is going to be a property of
line inside your for loop. So you need to be accessing
line.product.tags rather than
product.tags.
Answer
Solution:
Upon doing some tests, Shopify can't capture 2 values at the same time which are tags and payment gateway. I just did create a collection and call the spill once the product inside the collection is. | https://e1commerce.com/items/edit-order-confirmation-on-shopify | CC-MAIN-2022-40 | refinedweb | 242 | 58.48 |
Well that was one long, long week…
My plan following the upgrade was to post about how it went and to introduce everyone to the new features of the site. And now it’s 9 days later… oh well, you live, you learn, you try to get some sleep once in a while..
D-Day… that’d be deployment day.
Finally around 4am I went home. Exhausted but at least we had the blogs migrated and accessible…
The days that followed…
We spent the next few days working through additional performance investigations and listening to the literally hundreds of people telling us how much we sucked for moving their cheese. We heard complaints about the W3C validation. We heard complaints about the rolling blog post list no longer existing. Heck, I think I even saw a few demands for someone to be fired… eeek!.
And today we’ve been able to bring back the rolling blog post list..
What’s up with the home page?…
So we have a few things on the home pages now…
-.
If you’re one of those who just want to the old blog post list back then use the new rolling blog post list page. There is nothing else on the page to distract you. Enjoy. 🙂
What’s next?.
So what’s next… well we are working on the next update which should be out in a couple of weeks from now. This should include:
- Bug Fixes: Yep, there are bugs. We’ve been logging them and we are working on fixing them.
- Performance Improvements: There is still yet more performance we can wring out of this platform. We’re analyzing load times, SQL traces, CSS and HTML to reduce what we can.
- Search within a Blog:.
- Default discovered RSS Feed on a Blog: Right now it’s broken. It points to a search RSS feed that doesn’t exist. This one slipped through. We’ll correct this to be the posts for a blog.
- A few new widgets: Our bloggers will have a few new widgets to use including a standard code syntax highlighter along with the Microsoft Translation widget.
- Validation of HTML: We have identified a few issues with the HTML being output. We’ll fix those over time as we…
Thanks,
Sean
Hi Sean,
I feel for you with all the changes recently being made and how they are impacting people. Best of luck wth that.
I'm a consumer of these blogs and I'd like to request that the prefix on every blog be removed ie "Blog Post: ". Everything coming from the aggregated msdn blog (which I read amonst many other blogs in my reader) shows "Blog Post: " at the start.
This is making scanning volumes of blogs difficult because my eyes need to adjust left and right constantly to read the actualy content heading instead of just zipping down through all the posts which I arleady know are blog posts because they're in my reader!
If you are intent on adding this identifying information can I suggest it be a suffix instead.
@Trees: use the 'BlogsOnly' URL:
blogs.msdn.com/…/mainfeed.aspx
Hi Sean,
for performance and (everybodys!) bandwidth, what about HTTP Conditional Get (by timestamp/ETag: 304) for the RSS/Atom feeds? Thanks!
I like your narative about how the upgrade went. Our team just upgraded ITWeb here at MS and although it went smooth, we had our own issues. I might post something like this that tells the story of how cool it was to share desktops with PMs and Developers in China during our sync ups about the project. We had a couple odd issues that held us up until 3am but that's IT. Nice work and thanks for all that. I would really like to see non-FTE's who have expertise and experience working here at MS as "a-" and "v-" folks to be able to blog on MSDN though. We have to have an FTE own the blog which means we don't control it when we leave.
It would be nice on the rolling blog post list page to have different sytles for visited blog entries. Seems that right now they are painted with the style as unvisited ones.
What's with the /b/ prefix? Is this a sharepoint 2010 platform, and the "b" is a bucket to get around the hard limits around folder items? If it's 2010, did this migration experience go towards sp1 improvements for sp2010? Any other technical design detials available?
Great Job!
I like the reference to Who Moved My Cheese. I would say it is a good book, but I don't read and if I read the book then I would be moving my cheese. I also like the analogy that there is a lot more going on in the world than MS updating the Blog. Oil can leak into the Gulf, but God forbid MS from updating the Blog engine.
I am with Trees on the prefix. IMO when building a list with many different types of data points then something to identify those differences in the list would be nice. If I had a list of movies, music, and pictures I might prefix the list with something to identify what type the item is.
The challenge is that the RSS list only consists of one type (so far), Blog Post. If everything is a blog post then what is the need for the prefix? I know I have seen other prefixes but so few that one is to believe that Blog Posts is all there is. Even if there was another type would the percentage be so small that having the prefix is over kill.
What else could there be? Are there other things coming? I have seen User, but it seems to be meaningless.
oh, real feedback… thanks everyone 🙂
To answer a few questions…
– The /b in the URLs: The platform we are using is the Telligent Community Server platform. The platform can do more than just blogs (wiki's, forums, media galleries etc.) and each of those gets its own namespace in the platform. We spent a good deal of time looking into how to remove, hide or obstruct the /b from the URL but in the end the cost and time was very prohibitive and should we do it, we'd be on our own with the platform. It'd be tough to pick up hotfixes and changes from Telligent. In the end the best decision for future platform development and support was to leave the /b in.
– The Blog Post: prefix. As Thomas said, there is a different feed now for just the blogs. The main site feed at /rss.aspx combines users and blogs (and if the platform was also hosting wikis, forums etc. would be pumping out those into that main list.)
– Perf and Etags: We'll see if we can get them on the feeds. Good idea.
– Rolling Blog Post Colors: Yes, that's a great idea. Now I just need to find a color… 🙂
On the sharing desktops, we've been doing a lot of that since launch. It really is great technology and really speeds up solving problems for people. It's just like being there I guess 🙂
One of the things you promised before the conversion was better HTML closer to the standards.
It was surpsing that the HTML validation seemed to be worse (something we would have expected to have been tested).
I still would like to see direct links to the comment on the frontpage of blog
Both next to the article for short preview themed frontpage (like your blog) but also below the article for blogpages that show full posts on the frontpage.(like the IE blog)
I would also prefer the blog reader to be in control of the number of comments per page.
Thank you for the reply I thought there had to be more than just Blog Post and User. Now htat I think of them Twitter? News, Promos? Maybe and explaination of what they are and how we can filter. Where did Thomas find out about BlogOnly?
But now I'm confused I did some testing and found there are different URLs?
blogs.msdn.com/MainFeed.aspx redirects to /rss.aspx. Has a title page that is generic "Site Home"
This URL shows the prefix, Shows User: and Page: It is as if this is the "New Look (in progress)" tied to the old URL.
blogs.msdn.com/…/mainfeed.aspx title page is "MSDN Blogs"
Which does not show the prefix, does not show User: nor Page: and I did not need the parameter BlogsOnly. It is as if this is the "Old Look" tied to a new URL.
IMHO I would have had them switched it is as if we are forced the new look and the old look can be had by using a new URL. Instead of havig the new URL point to the new site and leave the link that everyone uses alone. You moved my cheese 😉 just joking. Why even have the two URLs? How about making the MainFeed.aspx redirect to /b/mainfeed.aspx instead of /rss.apsx? Ohh wait then we would be back to the old look.
I guess the solution is to change links and rss feeds from /mainfeed.aspx to /b/mainfeed.asxp to get the old look and feel? But then we will not get Page: or Twitter or Forum: or any other Group that comes along?
Na what I'm going to do is a have a bit of fun with this one. I'm add them both to my Favorite Bar and watch them (my cheese) move over time.
Keep up the good work! I know it is these little things can seem to be a bin pain after the huge accomplishments you have made.
As I was writing this a new one popped up Walkthrough: Build, Host, and Test Simple RESTful WCF Service. The funny thing is that was with the BlogsOnly.
Now I'm really confused!!!!
Then if I go back to /rss.aspx I get (test BlogOnly)
Blog Post: Walkthrough: Build, Host, and Test Simple RESTful WCF Service
A Blog Post and a Walkthrough.
I'm done the more I try to explain as data is being posted I get more confused.
I could not put this down for more than five minutes.
blogs.msdn.com/…/mainfeed.aspx
Is the way to go. Except the Type=BlogOnly does not work.
The concept I believe goes along the lines of what I was thinking before. There might not be any other type so why have a prefix, overkill. The majority of these will be blog posts so why prefix them all with Blog Post. This what you get when you use /b/mainfeed.aspx. It only prefixes those that are not a Blog Post. That is why the post about Build, Host, and Test Simple RESTful WCF Service is prefixed with Walkthrough because it is not a Blog per say but a Walkthrough.
If this is the desired effect than the /rss.aspx or /mainfeed.aspx is prefixing everything with BlogPost regardless. That is why there is duplication of the prefix? The Build, Host, and Test Simple RESTful WCF Service was prefixed with Walkthrough but it is as if /rss.aspx is prefixing everything regardless then Walkthrough: Build, Host, and Test Simple RESTful WCF becomes Blog Post: Walkthrough: Build, Host, and Test Simple RESTful WCF Service
I hope I'm not casted in a bad light I do want to help. It seems as I go out to the blog feeds they change minute by minute. 😉
A new prefix Automatic Reply:
Here is a weird one. Now this might just be what it is, but it would be a nice clean up. I know there are bigger things going on this can be a back burner item.
It appears that if you post via email and have an out of office auto reply then that gets posted to the web as well. Was that a desired effect? A user error? Is it possible that this person keeps on posting vie email while on a trip then for ever post there would be a an Automatic Reply?
blogs.msdn.com/…/radio-silence-for-a-bit.aspx
blogs.msdn.com/…/automatic-reply-posterous-re-radio-silence-for-a-bit.aspx
And as one would guess with /rss.aspx it appears as
Blog Post: Automatic Reply: Radio silence for a bit
and on /b/mainfeed.aspx it appears as
Automatic Reply: Radio silence for a bit
Recent Blog Posts not functioning again…just displays:
blogs.msdn.com/…/mainfeed.aspx
@StealthTech – I totally appreciate the feedback and the information you're collecting. We are finding new scenarios everyday!
I think when you see something like "Automatic Reply:" or "Walkthrough:" that's probably the name of the post not neccessarily a group or action on the site. Though that Automatic reply one is an interesting usage case, I guess it could be someone on vacation 😉
We are going to switch the RSS feed redirect so that the original mainfeed.aspx goes to the same content in the new place. That's what you said in your comment if I'm confusing here 🙂 That'll be coming in an update in the next few weeks.
BTW, it's Type=BlogsOnly (not sure if it was a typo to have BlogOnly)…
@Kizzer – thanks for reporting it. We are fixing a time out issue on the control that renders that RSS feed list. Hoping to have that fixed in the upcoming weeks as well.
Your welcome Sean,
There have been some intermittent issues with displaying the RSS list in IE 8 due to some posting having errors. Therefore my list gets grayed out. It happens sometimes, but seems to be happening more often than before.
Doing some more testing today related to my typo. Here are my use cases (time/day dependant done at 11:22 a.m -8 time zone)
If I go to blogs.msdn.com/…/mainfeed.aspx I get 62 out of 62
Regardless of what Parameter I choose makes no difference. That is why I think the typo did not matter. If there is a Question Mark at the end of the URL the query is thrown off:
blogs.msdn.com/…/mainfeed.aspx
I get 15 posts which is no different if I use a typo such as "Type=BlogOnly" or use the real deal "Type=BlogsOnly " I get 15 posts. Just as much as "Type=AllBlogs" clicked on from the MSDN Blog home page. I get 15 posts.
You raise a question with your answer about the Walkthrough prefix. How are end users going to know what prefixes relate to a "group or action" and what is a user prefix? How was I to know that "Walkthrough:" was entered by the blog poster and not the RSS feed trying to put the post into a group called "Walkthrough:"? I agree that htis was a user entry because if you view the Blog you will see in the Title Walkthrough. But because the formating of the text with a collen was the same as how prefixes are done it was not obvious.
You are spot on with the Redirect. I will be looking for that to come. I know how I was explaining was confusing, but that was part of the point. So confusing it is hard to explain ;). And yes the ideal solution is to have all links go to the same place and not have too many different looks. At the moment how many URLs to the RSS feed? I count three /rss.aspx, /MainFeed.aspx, and /b/MainFeed.aspx.
I'll keep posting if I find anything.."
I never understood the difference between TechNet and MSDN. I still don't. At the last Microsoft seminar I attended, I was asked to check a box for whether I was a developer or a something else… maybe it was "developer or an IT professional", or something. My answer was "yes, I am. Both".
@DWalker59 – Totally understand what you are saying – it's definitely something we have been talking about here in the MSDN/TechNet team (which is all the same team). We absolutely realize that folks are more than just developers or IT Pro's and that we need to evolve our approach to the current industry. Stay tuned, we'll keep working on it 🙂 | https://blogs.msdn.microsoft.com/seanjenkin/2010/06/02/the-aftermath-of-the-blog-platform-migration/ | CC-MAIN-2017-26 | refinedweb | 2,765 | 81.93 |
This action might not be possible to undo. Are you sure you want to continue?
Project Feasibility Study
Thai-North Rubber Industry Co., Ltd.
Lee La Wa Dee Group
Mae Fah Luang University, Thailand
THAI-NORTH RUBBER INDUSTRY CO., LTD
To Lecturers: Mr. Chaiyawat Thongintr
Module: 1203302 – Project Feasibility Study Evaluation 2010 Semester: 2, 2010/2011 Department: Business Administration
Class Roster – 1203302_Sec 01
By: Lee La Wa Dee Group
1. Miss Jaruwan Muangpang 2. Miss Chanida Ploddee 3. Miss Chutinard Kunmaneelert 4. Miss Ponphan Kong-iam 5. Miss Rattanaporn Mekthrong ID: 5031203014 ID: 5031203019 ID: 5031203021 ID: 5031203047 ID: 5031203057
Credits and acknowledgments borrowed from other sources, with permission, in this project appear on appropriate page within text.
THAI-NORTH RUBBER INDUSTRY CO., LTD
Mae Fah Lunag University. This Project is organized into 7 Chapters. Chaiyawat Thongintr the Lecturers of Project Feasibility Study Evaluation. Chapter 5 Financial Analysis. Chapter 4 Technical Operation Feasibility Study. Chapter 6 Risk Management and Final Chapter Summary Student or entrepreneur who interest about rubber business or rubber industry in Thailand and have the group of customers in China should read this project We hope the reader will get the benefit from this project. Business Administration department. The information that we use to support this project can practically. We study and operation this business plan to be close possibility. This project will not happen if we don’t have supported by Mr. By Lee La Wa Dee Group we are students of Mae Fah Luang University. Chapter 1 Introduction. Chapter 2 Industry Profile Chapter 3 Market Feasibility Study.PREFACE The Purpose of this project is to explain how to make the business plan of Thai-North Rubber Industry Company Limited to be feasibility for study and evaluation in subject of Project Feasibility Study Evaluation 2010 (1203302). Thailand .
4 Promotion 3.2 STP analysis 3.3.3.2.5 Activities and Gantt chart 1 2 3 3 4 4 Chapter 2 Industry Profile 2.2.2 PES Analysis 3.3.1 Market Analysis 3.3 Marketing Mix Strategy 3.3.TABLE OF CONTENTS Chapter 1 Introduction 1.1 Rubber Industry in the World 2.1 Product 3.1.2 History of rubber in Asian 2.3.2 Objective 1.2 Rubber Industry in Asia 2.2.1 Market segment 3.3.1.1 General Environment Analysis 3.3 History of rubber in Thailand 2.3 Benefits of this Study 1.2 Situation of Industry 2.3Positioning 3.2.3.1 History of rubber in Europe 2.3 Mission of our organization 2.3 Place 3.3 Competition Analysis 3.3 Summary of Market value 2.3.1 Nature of Industry 2.2 Price 3.4 History of rubber in China 2.2.4 Strategy 5 6 6 8 9 10 11 11 16 18 25 27 27 28 28 29 Chapter 3 Market Feasibility Study 3.4 Sale Forecast/Profit estimate 3.1.2 Market Target 3.1.2.1 Background and significant of the project 1.4 Rubber Industry in China 2.2.1 Industry and rubber products 2.1.4 Brand of our company 1.1.2 Vision of our organization 2.5 Marketing Expend Budget 31 32 32 36 44 49 49 49 51 53 53 54 54 60 62 73 .3 Rubber Industry in Thailand 2.1.
5 Production cost 4.4 Land Tax 4.5.3 Payback period 5.7 Administration cost 4.5.2 Building 4.1.3 Fees for the establishment of the factory 4.5 Tax labels (per 500 square centimeters) 4.Table of Contents v Chapter 4 Technical Operation Feasibility Study 4.5.7.8 Depreciation 4.2 Cost of good 4.4.3 Balance Sheet 5.1 Organizational structure 4.1 NPV (net present value) 5.3.9 Conclusion 78 79 79 83 86 87 89 89 91 92 92 93 94 94 95 95 95 96 98 100 107 107 109 111 117 117 118 118 129 139 Chapter 5 Financial Analysis 5.1 Financial Statement 5.4.2 Income statement 5.1.4.1 Rubber Smoked Sheets (RSS) 4.1.1.1 Logistic Management 4.4 Break-event point 141 142 142 147 150 155 159 160 161 161 161 162 163 .3.3 Total Logistic 4.6 Logistics and Transportation cost 4.4.4 Preopening cost 4.5.1.3.1.3.1.4.3 Administration Zone 4.2 IRR 5.1.2 Inventory management 4. 4.1 Product Characteristic 4.3 Features and Dimension 4.2 Prepare to be company limited 4.4.6 Total Sale 5.4 Cash Flow Statements 5.6.2 Investment Criteria 5.2 Administration Expense 4.6.7 Total Cost of Pre Opening Cost 4.6.4 Operating investment cost 4.2 Block Rubber 4.4.3 Pricing product 4.7.5.6 Trademark registration fee.5 Loan 5.1 Total requirement and the source fund 5.7.1 Cost of request Electric and Water 4.5 Operating investment cost /Operating expense 4.1 Land 4.
2 Economic Factor 6.1 Political Factor 6.2 External Analysis 6.1.2.2.1.1.1.1 Human resource 6.3 Changing operating environment 6.1 Internal Analysis 6.2 The limits of the employee 6.2.4 Health and Safety 6.3 Technological Factor 164 165 165 166 166 166 167 167 167 170 Chapter 7 Conclusion 173 Reference Appendix .vii Table of Contents Chapter 6 Risk Management 6.
although we have the many risk which is the economical risk. Technical Operation Feasibility Study.353 million tons in 2010.. to study in subject of Project Feasibility study and Evaluation 2010.1 percent are expected for 2010 and 2011. Risk Management and Final Summary. The Purpose of this project is to explain how to make the business plan of Thai-North Rubber Industry Company Limited to be feasibility for study and evaluation. Thai-North Rubber has a strong in the financial status that also represent in the ratio analysis.show the positive growth rates in world rubber consumption of 8. has and will be increasingly dominated by Asian countries. Today Thailand has rubber plantation area by about 15 million hectares of rubber growing areas to support the demand that increasing. Thailand's largest rubber exports to China. Said that rubber is one of the crops that are important to the economy of Thailand. the number increasing in demand of rubber from 2007 there are 2.com. it can be acceptable because we also cope with this risk from using the risk management.Exclusive summary Rubber Industry is an issue of Business concern to most Asia. According to rubberword.8 percent and 5. Increase 10% within 4 years. . Mae Fah Luang University. Financial Analysis. In China. Market Feasibility Study. And the total combined NR and SR consumption and production. in term of processing rubber industry. Rubber Research Institute of Thailand. Lee La Wa Dee group saw this opportunity and we establish Thai-North Rubber Industry co. Our group we study and evaluated this project start with Introduction. operating risk and etc.754 million tons to be 3. political risk. respectively. ltd. and has been in the public conversation nearly every day for years. most with 54 % of the export value of rubber.. Industry Profile.
P age |1 Chapter 1 Introduction .
1. Although with some privates to processing rubber are only a few cases to invest. Chiang Rai is a possible for our business to make high profit and easy to growth in the North of Thailand. You will see why we do this project from this chapter. (Source:. Chiang Khong . objective. For the Northern of Thailand especially in Chiang Rai. Luang Namtha and Lao PDR .aspx?NewsID=9530000131252 ) .manager. the total of rubber plantation with 18 districts in Chiang Rai up to 347. and Trang. Chiang Rai also has the ability to export to South of China via R3A Road.Huai Sai. And now.co.Yun Nan province distance just only 250 km and office of the Rubber Replanting Aid Fund is planning to set additional offices at the port’s Chiang Khong to facilitate for export rubber to the South of China.Overview of Project Feasibility P age |2 This chapter explains about overall of project. Bo Kaew Kwang. Nakhon Si Thammarat.th/Local/ViewNews. we decide to take this advantage of rubber in Chiang Rai to study the feasibility of this project. For the market is not worry because in Thailand is most focusing and government support on exports to China reached 39%. There are background and significant.1 Background and significant of the project Our project is a rubber industry which has processing rubber which Rubber Smoked Sheet (RSS) and Block Rubber to respond the higher demand in market.857 rai and are likely to increase much more. Rubber plantation is just the beginning and trends to increased as well. the number of rubber plantations growing a huge leap. and brand of our company. Surat Thani. Chiang Rai has rubber-largest cities deputy from Songkhla. Chiang Rai doesn’t have enough of factory to processing plant and we believe that it has both a large source of latex and the major export. activity and timework. benefit. That is why.
1. 1.2 To study operation and the distribution channel of Rubber industry for export products to China.3 Get experience from doing this project (management strategies.1 Know more about the market of Rubber industry business in Thailand. Thailand.3.2 Know more about consumer behavior of Rubber industry in China.2 Objective 1. 1.2.5 To study the feasibility of investment Rubber industry business in Thailand. 1.3 Benefits of this Study 1. . team work.3 To study about consumer behavior of Rubber industry in China.3.4 Can be applied to real investment.3.4To education approaches and management strategies of Rubber industry business.2.5 Know more about operation and distribution channel of Rubber industry for export products to China.2. 1.2.1 To enhance knowledge and understanding about analyzing the market feasibility of Rubber industry in Chiang Rai province.P age |3 1. 1.2. 1.3. 1. solving problem.3. etc) 1.
STP Marketing mix strategy Sale forecast Marketing expense Technical Feasibility study Finance statement Finance analysis Risk analysis Summary all of them Prepare draft final report Prepare final report Prepare group presentation 17-23/2/2011 9-15/12/2011 30-5/1/2011 27-2/2/2011 2-8/12/2011 6-12/1/2011 3-9/2/2011 .P age |4 1.2 Logo is Logo of Thai-North Rubber Company 1.4.4.1 Our company name is “Thai-North Rubber” 1.4 Brand of our company 1.5 Activities and Gantt chart EXHIBIT 1-1 Activities and Gantt chart 16-22/12/2011 23-29/12/2011 18-24/12/2011 25-1/12/2011 13-19/1/2011 20-26/1/2011 10-16/2/2011 Activities Prepare for topic submission Introduction path Nature of industry Situation of industry Summary of market value Marketing analysis PEST.3C.
P age |5 Chapter 2 Industry Profile .
Thailand has rubber plantation area by about 15 million hectares of rubber growing areas of southern most Followed by the East Central region included. Singapore and Java and the year after in Malaysia.hevea brasiliensis . Common name in English: Para rubber.22. Northeast and North have a total of 60 provinces. 4001. Scientific name: Hevea Braslilensis.495 million baht and wood products worth 55. 4001.10. Consists of the export value of raw materials are 58. .is originating from Brazil. seedlings of hevea were shipped to India.21. rubber is high of economic value with 162. the latex is collected from a diagonal incision in the tree trunk i.0000 technically specified natural rubber (TSNR). Ceylon. value of rubber products 48. Family name: EUPHORBICEAE. On the other hand. the production in Thailand. Today.703 million baht.0000 Natural rubber latex.955 million Baht. This action does not affect the health of the tree and the tree wound later heals itself.1.e. It was exploited in the wild state there till the beginning of the XXth century.1 History of rubber in Europe Where does rubber come from? The hevea tree . the hévéaculture developed from the end of the XIXth century in Southeast Asia: in 1876.0000 Smoked sheets.Industry Profile P age |6 2.29. A province the most rubber growing areas is Surat Thani. Rubber is one of the crops that are important to the economy of Thailand for long time.0000 other. Code HS (Harmonized System): 4001. In 2001 November. 4001. Indonesia and Malaysia represents about 70 % of the world production of natural rubber. 2.1 Nature of Industry Name: A rubber.757 million baht.Today. When a tree matures at the age of 6 or 7 years. the tapping process.
During the hot summer. From this early use. What were first rubber applications in Europe? The first rubber applications date from the end of the XVIIIth century and were mainly erasers and medical probes. Mayas.g. best known for his discovery of oxygen. noted that pencil marks could be "rubbed out" by the substance. In spite of the enthusiasm of the authors for the extraordinary properties of the rubber.P age |7 Who were the first users of rubber? The Indians of Central and South America (Incas. Olmecs. When was rubber first imported into Europe? The first scientific study on rubber was realized by the French academician Charles de la Condamine in the XVIIIth century within the framework of a mission on the South American continent and by François Fresneau. Indians also found the incredible propriety of waterproofing and used it for their clothes and shoes. etc) are known to have used the unique properties of rubber for religious or magical ceremonies e. numerous figurines and balls made from rubber moulded were found in the heart of the sacred wells. The first full bandages appeared in 1834. rubber was sticky and malleable. the rubber was used to waterproof some textiles. At the end of XVth century.In England during the XVIIIth century. rubber derived its name. engineer in Cayenne. Joseph Priestley. Christopher Columbus was certainly the first European assisting to the famous Aztec game with rubber balls representing the Sun. and the first tyres not before the end of the XIXth century. most important Aztec god. while it became hard and brittle in . Aztecs. Then. they will not succeed in interesting their contemporaries in the use of this “new” substance What are the origins of the French and English terms? The French rubber term comes from the Indian " ca-o-tchu " word or " wood which cries ". Why 1839 is an essential date for rubber manufacturing? Prior to 1839. the properties of rubber were dictated by the surrounding temperature.
World demand for rubber has a lot of hands-stall. Colombia and Panama. This phenomenon was further called: “vulcanisation” in reference of the Roman god of fire and metallurgy. A 1839 winter evening. including tyres. that period. it has no idea if the world (meaning Europe) still has to rely on rubber that comes from various sources them alone.etrma. Assistant Secretary-General regularly Governor Annual India Efforts to bring rubber planting in Asia for the first time it happened. partly during the time before. 2443 (1900) is mostly a rubber plantation in South American countries are Brazil. When it was removed. No one knows that much rubber. it always returned to its original shape.asp ) 2. Goodyear dropped accidentally a mixture of rubber. Rubber start is important to human life and more.2414 (1871) has led to painting from Sir Joseph Yang Hung markers see.1. and many other products. This was finally remedied by the unexpected discovery of the process of vulcanisation. In the future. overshoes. mostly.2 History of rubber in Asian Manufacture of rubber in the world the past year. There are also rubber from Russia and Africa.org/public/activitiesrubberh. While Tire situation in countries America quite badly with the world due to the .P age |8 the winter. it became possible to use rubber in raincoats. C. white lead and sulphur upon a hot stove. may be caused by a shortage of rubber are likely to find that New in other parts of the world to remove the tires planted sometime in the year 2398 (1855) brings this idea to consult Sir Joseph Hung markers. What looks like rubber or even how the tires came from the leaf until BE 0. you have an interest in planting more rubber has consulted with Sir Cliean Siemens Markham House. but did not receive much attention should the Europeans. Despite stretching. (Source:. Thanks to this discovery. the material was no longer affected by temperature.
"Phraya Ratsadanupraditmahitsornprakdee" is the same one “Father of rubber" is the leader to bring the rubber tree at Amphor Kantrang. Disperse in the South East and Northeast. . There are set up more responsibility in the research. and found the best varieties of rubber tires or rubber. Then Phraya Ratsadanupraditmahitsornprakdee was sent to learn how to teach people to plant rubber. Rubber growers in Colombia and Panama are hard rubber tapping exert finally rubber in that country has been hurt a lot and killed and no rubber left on the bar again Sir Clean Siemens. development and technology transfer.Which has expanded the rubber from 22 tree species to in the country of Asia.th/Para1. The weather. Finally.co. soil and terrain conditions. Promote to the people planting.htm) 2. Rubber is grown widely in the colonial territories of Britain and Holland are also mostly German rubber is grown on some of Africa and some rubber in Russia because rubber is growing very popular in Asia. Has rubber been planted in the territories. May be due to Asia has the right elements to grow. (Source:. A British colony.3 History of rubber in Thailand Since that is also called "Siam" Estimated after the 1882. Hevea Brasiliensis species so since the year 2425 (1882) is a rubber. Trang province is the first. He was ordered and tires to the species distribution.P age |9 high demand of rubber. Including funding assistance instead planted with rubber. Since Chumporn province was border province. Which is a growing source of new and industrial rubber country? Thailand is a manufacturer and exporter of rubber most of the world. Students who are all sent to a district Chief Officer.reothai. Grow extensively in the Cape Malays in the very early stages. including rainfall labor readily available. Which at that time the people bring to plant and have expanding the rubber plant area into the south in 14 province. In Year 1899.1. he found that Peninsular territory is where the rubber will grow best. village headman. Combine with agricultural and commercial properties of the rubber itself as. Every time the government has focused on the development of rubber has always been. Thailand has a planted area of rubber and the country about 12 million rai. Rubber was used to test varieties grown in India for the first time but without success. sub district headman.
During the 1970s and 1980s.1. By 2004. however.ehow. increasing demand for rubber tires led to China's "Rubber Boom. Into the 21st Century Since 1990. China's economy was ranked second worldwide in 2010. with the popularization of bicycles and the emerging automobile industry. (Source: ) Read more: History of the Rubber Manufacturing Industry in China | eHow. China's rubber industry boomed. For the next several decades.com/facts_6920005_history-rubber-manufacturing-industrychina.4 History of rubber in China For over a century. In spite of ups and downs over the last hundred years. China was the largest producer of shoes and a leading exporter of tires. the Great Depression caused the global economy to stagnate. foreign investment and relaxed industrial restrictions allowed the economy to grow rapidly. China's economy struggled as the country faced civil war. China is currently one of the world's leading rubber distributors.ehow. marking the beginning of the rubber industry in China. rubber production has been one of China's most profitable industries. The rubber industry was on its way to thriving once again. and is expected to rise to first place by 2030. The Rubber Boom In the early 1900s. producing over 50. as its rubber industry continues to thrive. industry reform. rubber consumption has risen steadily.com/facts_6920005_history-rubber-manufacturing-industrychina. famine and unstable government. (Ref 1 section 3 paragraph 2 and 3) By 1910. a new process for rubber extraction in China allowed for a higher yield over an extended time.com a g e | 10 2.000 rubber products.html#ixzz179k8k7AY ." A Struggling Economy In the 1930s. domestically and abroad.
1987). from roughly 1910 on. By the middle of the eighteenth century. sheets. 1983. from the late 1700s through 1900.” however. Initially the problem of natural rubber was its sensitivity to temperature changes. The boom would then be accentuated after 1900 by the development of the automobile industry and the expansion of the tire industry to produce car tires (Weinstein.1. was centered in Brazil. the first period of rubber’s commercial history. which modified rubber so that it would support extreme temperatures. and other products. which grew predominantly in the Brazilian Amazon (but also in the Amazonian regions of Bolivia and Peru). low wages.1 Rubber Industry in the World 2. Dean 1987). What initially caused the beginning of the “Rubber Boom.2. The best source of latex. by geographical accident. was the popularization of the bicycle. and very high prices. the period following 1910 was one of rapidly increasing production. Uses of Rubber The early uses of the material were quite limited. It was then that natural rubber became suitable for producing hoses. the second period. was hevea brasiliensis. the milky flui1d from which natural rubber products were made.P a g e | 11 2. high wages. tires. shoe soles. rubber was used to make waterproof shoes (Dean. The first century of rubber was typified by relatively low levels of production. . In the early nineteenth century. industrial bands.1 Overview of the Rubber Market. Europeans had begun to experiment with rubber as a waterproofing agent. shoes. 1870-1930 Natural rubber was first used by the indigenous peoples of the Amazon basin for a variety of purposes. and falling prices. was increasingly centered in East Asia as the result of plantation development.2. which altered its shape and consistency.2 Situation of Industry 2. In 1839 Charles Goodyear improved the process called vulcanization. Thus.
rubber was in the hands of mainly Brazilian.P a g e | 12 Exporting Rubber From the ports. rather than selling it to a exporter in the Amazon (Shelley. to ports in Europe and the US to be distributed to the industries that bought large amounts of the product in the London or New York commodities exchanges. Brazilian producers or local merchants from the interior could choose whether to send the rubber on consignment to a New York commission house. Contrary to what Weinstein (1983) argued. A large part of rubber produced was traded at these exchanges. British and American exporters. like other commodities. Rubber was taken. Figure 2-1 Production and Prices 1900-1935 . but tire manufacturers and other large consumers also made direct purchases from the distributors in the country of origin. 1918).
the volume of rubber demanded by car tire manufacturers expanded dramatically. and especially after 1910. at the same time. during this period. rubber was increasingly produced on low-cost plantations in Southeast Asia. First. in terms of both supply and demand. Uncertainty. it was associated with high costs of production and high prices for final goods. prior to 1910. most rubber was produced. 1900-1930 Figure 2-3 Rubber production and imports. The price of rubber fell with plantation development and. After 1900.P a g e | 13 Figure 2-2 World Rubber Production and Consumption. 1870-1899 Conclusion The natural rubber trade underwent several radical transformations over the period 1870 to 1930. by tapping rubber trees in the Amazon region of Brazil. .
respectively. positive growth rates in world rubber consumption of 8.rubber.e.P a g e | 14 (often driven by changing tire technology) meant that natural rubber producers and tire manufacturers both experienced great volatility in returns.1.0 percent.1 percent and 0.2 Natural Rubber Supply And Demand Forecast and Price Outlook The Rubber Economist Ltd. NR output is expected to continue to increase by an average of 1. the average annual growth rate for 20092011 will only reach 1. The relatively lower price of NR when compared with SR helped to increase NR shares last year and is expected to do so again this year before the trend reverses in 2010 and 2011. The overall evolution of the natural rubber trade and the related tire manufacture industry was toward large volume. lowcost production in an internationally competitive environment marked by commodity price volatility and declining levels of profit as the industry matured.04 million metric tons in 2007. which is lower than that of 23. and much of the growth will mainly be in Asia/Pacific.international.2 percent by 2011 as compared to 56.97 million metric tons in 2011.. However. (Source: percent in 2008.6 percent. may be a lot lower than during recent years. Consumption of natural rubber (NR) is expected to show a sharper increase than for synthetic rubber (SR). however. an annual growth rate of 1. expects that the trough of total world rubber consumption may not hit bottom until the end of 2009. the sharp decline globally depends significantly on the performance of China. The increasing SR shares in Europe will balance out the decline in North America. particularly in major producing countries. will be even worse than last year and the worst since 1942. which is forecast at -9.8 percent and 5.9 percent. respectively. A fall off in 2009 is expected for most countries. Despite a return of a sharp growth rate. Hence the world percentage of SR is forecast to decline only marginally to 56. The growth rate.1 percent over the next three year period. This means rubber consumption may only rise to 22.net/encyclopedia/article/frank. which is expected to show a recovery in the second half of this year to show a positive growth by the end of the year. leaving the world share relatively stable.1 percent are expected for 2010 and 2011.market) 2. Rubber forecasts have been scaled down steadily since the second half of last year.2. This means the decline this year. The continued increase . Despite a slowdown in demand. i. However. the relatively fast increase in production in Indonesia means it will move to a closer position to overtake Thailand as the number one producing country.
rubber consumption declined in 2008 and is expected to fall further this year. NR prices may increase during 2009-2011. The continued increase in rubber output in China means it may overtake Thailand as the largest rubber.S. but not so sharply. Asian countries comprised 7 of the 10 largest rubber economies. SR output is forecast to show a marginal decline by only -0. after six years of growth. Hence.e. a return to the level reached in 2000. the USA and Thailand. In 2008.. NR output is expected to continue to increase. Unlike NR. dollar can influence both consumers and producers. Despite a slowdown in demand. i.S. will leave only a slight increase for the following three year period. The important assumption is that the exchange rate of US$ to SDR will gradually weaken during this period. So far in 2009. Furthermore. has and will be increasingly dominated by Asian countries. NR plus SR. SR stocks have and will continue to rise steadily. there may be an increase of SR output in Asia in relation to other regions. Despite the rising stocks both in absolute terms and relative to consumption. In conclusion. In general.S.P a g e | 15 in production in India will also mean it may overtake Malaysia to become the third largest NR producer by 2011. US$ has been fluctuating around a gradual depreciation trend. whereas previously it had been appreciating sharply against many currencies.2 percent/year. Furthermore. by 2011 Indonesia will overtake Japan for fourth place behind China. growth may only reach 1 percent a year. NR prices rose to a record . The steady rise in rubber prices since 2002 has resulted in an increase in new planting during this period in many smaller producing countries. This is in contrast to the global consumption to stock ratio for NR. dollar weakened in July. Despite weaker prices than the first half of 2008. This certainly is true for NR. many smaller producing countries may find the price levels profitable enough with their lower cost of production. Compared to NR. a weaker U. which is expected to increase from less than three months to four months. but show a gradual rise from the trough reached last December. Our forecasts indicate that the SR stocks to consumption ratio. the total combined NR and SR consumption and production. A sharp slowdown in demand in relation to supply means NR stocks may continue to increase during the next few years. SR suppliers can simply turn off the tap as demand slows and hence there will be a gradual rise in stocks. dollar results in higher commodity prices and vice versa. which may increase relatively sharply in 2009 before a fall. hence prices have been relatively stable. and in particular in 2008 when the U. supplier. The world rubber economy. allowing them some flexibility. The change in the value of the U. Even though a rise is expected in 2010 and 2011. Despite declining sharply in the second half. many SR consumers are also producers. which have lower price elasticity than the major producing countries.
(Source: million metric tons in 1998. Figure 2-4 Rubber production – U.S. according to the International Institute for Synthetic Rubber Producers (IISRP).2. Imports from Asia So urce: Trade Stats Express.2 million metric tons.2.8 percent. Asia continued to experience the aftermath of the economic crisis that hit in 1997.P a g e | 16 high in 2008.4 percent in 1998 after 3 consecutive years of gains.rubberworld.2 Rubber Industry in Asia 2.asp?id=287) 2. China experienced a decrease in consumption of 0. dollar is weakened. In the aftermath of the Asian financial crisis and as a result of sluggish demand in the automotive sector. In 1998. Rising stocks will have a negative impact on NR prices. world synthetic rubber consumption remained flat at best and by some industry estimates decreased 1.3 percent to 3. a substantial drop for a country that has consistently enjoyed growth between 7 and 10 percent.1 Rubber trends Worldwide synthetic rubber consumption reached 10.com/RWmarket_report. 2008 . but they may not decline as much if the U. Asia decreased synthetic rubber consumption 8.S.
SBR consumption remained stable at 0. of synthetic rubber are expected to remain relatively flat in 1999 due to the recovering state of Asian and Latin American economies. exports over imports will persist through 2000. according to data released by the IISRP.2 percent. the world experienced a relatively higher increase in the consumption of synthetic rubber. Most Asian producers. China’s production declined 2 percent to 589 kt after 8. Only Taiwan weathered the Asian storm with an increase in production.1 million metric tons in 1998. world synthetic rubber output fell by nearly 2 percent to 9.5 million metric tons. resulting in declining stocks in the second half of 1998. experienced declines in production in 1998. and India’s plummeted 12 percent to 66 kt in that period.9 million metric tons in 1998 after 3 consecutive years of growth. up 5 percent to 428 kt in 1998. still suffering from the 1997 financial crisis and overcapacity in that region.com/Rubber_Marketing_Research_-_Asia) . Slower growth for U. (Source: percent. and Latin America. particularly if Asian markets fail to grow faster than capacity. dropping to(NBR) consumption remained relatively flat at 320 kt.4 percent to 1. Acrylonitrile butadiene 0. BR consumption was down 3.4 percent growth in 1997–1998. China. growing 3. both ethylene-propylene copolymer (EPM) and ethylene-propylene terpolymer (EPDM)] experienced the largest consumption increases.3 million metric tons. Korea’s dropped 2 percent to 530 kt.2 percent to reach 814 kt. reaching a level of 3. According to data collected by the International Rubber Study Group (IRSG). Japan’s production declined 4 percent in 1998 to 1. Asia’s capacity has continued to grow.9 million metric tons. ethylene propylene rubber [EPR.S.S. tempered with unexpected pockets of demand in places like Korea and Venezuela.P a g e | 17 With regard to growth by elastomeric type in 1998. Exports from the U. mainly because of significant decreases in Asia and Oceania. During that period. or 3.
Investment per tapper in Brazil was reportedly 337 pounds sterling circa 1910. When the British did attempt to restrict production in the 1920s. Labor-Intensive In Asia. they were potentially eighty percent more productive (Dean.3.2.2. the British and Dutch drew upon their superior stocks of capital and vast pools of cheap colonial labor to transform rubber collection into a low-cost.1 Growing Rubber Trees in Thailand Rubber trees grow best on flat low land. the new plantation system proved equally susceptible to uncertainty and competition. Such an expensive solution made no economic sense in the 1910s and 20s when coffee and nascent industrialization in São Paulo offered much more promising prospects. these areas. 1987). in the low-cost Asian plantations. Not only were Southeast Asian tappers cheaper. labor-intensive industry. investment was estimated at just 210 pounds per worker (Dean. the British and Dutch were unable to collude to control production and prices plummeted after 1910. the game was no longer worth the candle: in order to compete in rubber production.2.3 Rubber Industry in Thailand 2. would have been mostly rainforest. The dramatic change has meant that Thailand’s forests have been swapped for cash. Unexpected sources of uncertainty arose in the technological development of automobile tires. Fifty years ago. the United States attempted to set up plantations in Brazil and the Dutch were happy to take market share. 2. with rubber tree plantations now prevalent in Thailand. In spite of colonialism. 60% of Thailand was covered with forests.2 Alternative Southeast Asian Plantations Develop a Low-Cost. In a sense. then. .P a g e | 18 2. Brazil would have to have had significantly lower wages -. Yet it was too late for Brazil: the cost structure of Southeast Asian plantations could not be matched.which would only have been possible with a vastly expanded transport network and domestic agriculture sector in the hinterland of the Amazon basin. if left uncultivated. 1987).2. now it is less than 20%. Ironically.
In 2006 alone. Tropical rainforests in Thailand offer great value in the area of tourism. it would work out as many millions of dollars every year. where obviously rubber plantations offer no interest to visiting foreign tourists. Ecotourism is the fastest-growing tourism sector in Thailand. but putting a value on rainforest is more difficult. over 3 million tons of natural rubber was sourced from Thailand. Until they are totally depleted and that crop can no longer be grown until. and destroying rainforest to make way for rubber production produces little reward.3. . Probably significantly more than is produced from the sale of products produced from the rubber plantations. soil erosion can often wipe out the life-giving topsoil.2. Land that is used for rubber cultivation quickly suffers a rapid decline in the fertility of the soil. If you were to calculate the value of the rainforest to tourism in Thailand. but before they can be planted. rather than life-giving rainforests. This climate helps Thailand’s rubber farmers achieve high yields roughly 1. After areas are cleared of forest ready for planting of rubber trees. which is highly conducive to rubber tree cultivation.2% per annum between 2007 and 2009. 2.76 tons of rubber per hectare – and has allowed Thailand to lead the world in natural rubber production since 1991. Never the less modern day culture seems to put a higher value on material items. In a village named Kireewong.P a g e | 19 Putting a value on a rubber plantation is easy. landslides caused by a tropical downpour killed over 300 people and devastated the town of Nakhorn Si Thammara. These already sizeable production levels are projected to increase 2. This is because growing one crop removes the same nutrients again and again from the earth. Compared to the huge amount of tourist dollars flowing in Thailand every year from people who wish to visit the natural wonders the Thais have to offer their visitors. In some extreme cases lives have been lost. Simply because there were no trees to hold the ground together to prevent the landslides. as happened at a site that had been cleared for rubber trees in Thailand in 1988. the nutrients are replaced.2 Thailand: World Supplier of Natural Rubber The southern part of Thailand has a monsoon climate.
The top five recipients of Thailand’s rubber products. Major opportunities for investment exist in the production of value-added rubber products. The proximity of its production sites to its destination sites allows for the ‘just-intime’ delivery essential for complex rubber products. the United States. and South Korea. Over 2. nearly 90% of Thailand’s natural rubber production is for export.771. 65% is processed into value-added goods. and elastic (8-9%). Rubber wood.P a g e | 20 In fact. Thailand is optimally located to supply the natural rubber demands of the Asia Pacific region. which accounted for 54% of the total rubber consumption in 2006.673 tons. Of this portion. of natural rubber was exported in 2006. many of which are used by the growing domestic automotive industry. airplanes.9% between 2007 and 2009. a renewable resource that presents an attractive alternative to hardwoods timber. This rise in demand will predominantly originate in the Asia and Pacific region. in terms of export values for 2006. is an increasingly important product in the domestic market as this market raises its environmental awareness. Japan. gloves (13-15%). is expected to experience an annual growth of demand for rubber of 5. cars and bicycles (46-51%). the International Rubber Study Group (IRSG) has forecast a 4. such as tires and tubes for motorcycles. Ten percent of all the rubber produced in Thailand is used for domestic consumption.4% annual growth rate for global rubber consumption for the period of 2007 to 2009. This region. The following products present strong investment opportunities: Tires and tubes for automobile Piping and tubing tires Gaskets / Seals Gloves Elastic Hoses Condoms Furniture from rubber wood .41 billion. or an estimated US$5. rubber bands (8-10%). Furthermore. were: China. Malaysia.
Research and development: Thailand has higher R&D spending than either Malaysia or Indonesia.P a g e | 21 Another growth market is the developing market and cultivation for organic rubber. Since its introduction in Thailand during the early 1900s. more than 2.3. Availability of workforce: Thailand’s labor is cost-effective relative to that of Malaysia and Indonesia. By 2009. Solid transportation and communications infrastructure combine to promote ease of export. Thailand is home to a wealth of highly skilled personnel. ASEAN countries. It is required in the manufacture of many industrial and consumer products. The first experimental planting area was located in Trang Province at the southern part of Thailand. Free Trade Agreements: Thailand has already negotiated reduced tariffs on rubber products with China. and New Zealand. and graduates 80. condoms and gloves. Location in a high demand region: The Asia and Pacific region has the highest rubber consumption growth rate. from hoses and vehicle tires to belts. In addition to being the leading exporter and processor of high-quality rubber.72 million hectares were being cultivated throughout the country.3 Thailand: World’s Top Supplier of Natural Rubber Rubber is an indispensable resource. enhancing its competitiveness. . 2. Why Thailand? Abundant resources: Thailand is the largest producer of natural rubber. but quality is never sacrificed to quantity. Thailand is also a top R&D center for the material. Australia. The goal through 2012 is for the Thai rubber industry to develop sophisticated technology and generate added value. Enhanced Infrastructure: Thailand has ample water supply and low incidence of power outages to insure the availability of the resources essential to manufacturing ventures. There is a growing demand for organic rubber and Thailand is already a leader in the development of sustainable and environmentally sustainable methods for rubber processing.000 science and engineering students annually.2. the country has grown to become the world’s largest producer and exporter of natural rubber.
76 tons of rubber per hectare – and has allowed Thailand to lead the world in natural rubber production since 1991.1 million tons of natural rubber was produced in the country. dominate the rubber plantation landscape. In2009 alone. 90% of which are located in southern Thailand. 2. . Malaysia. nearly 3. This helps Thai rubber farmers achieve high yields – roughly 1.3. More than 2.6 billion in 2012. the country’s rubber product exports could reach US$6. According to projections by the Office of Industrial Economics.4 Lively Export Sector Nearly 90% of Thailand’s natural rubber production is for export. Japan.7 million tons or US$4. holding 95% of the planting area. which is highly conducive to rubber tree cultivation. However.26 billion worth of natural rubber was exported in 2009. The already sizeable production yield is projected to increase at least 2% per annum.P a g e | 22 Figure 2-5 World’s Top 5 Produces of Natural Rubber in 2009 (Source: Thai Rubber Association) The southern part of Thailand has a monsoon climate. the rubber sector itself is controlled by large processing plants that purchase the material via local dealers. Small landholders. The top five destinations for Thailand’s rubber products in terms of export value that year were China. the European Union and the United States.2.
P a g e | 23 Figure 2-6 Thailand’s Natural Rubber Export Market 2009 (Source: Rubber Research Institute of Thailand) 2. Growth is being fueled largely by rising demand in the Asia-Pacific region. cars and bicycles (46-51%).6 Value-Added Rubber Products Ten percent of all rubber produced in Thailand is used in domestic consumption. 2. airplanes.1% and 5.3.2. The proximity of the country’s production sites to regional markets allows for the just-in-time delivery essential for complex rubber products. is an increasingly important product in the domestic market amid greater environmental awareness.5 Thailand: Strategic High-Demand Region The International Rubber Study Group has forecast 5. Rubber wood. 65% is processed into value-added goods such as tires and tubes for motorcycles. Thailand is optimally located to supply the Asia-Pacific’s natural rubber requirement. respectively.3.8% growth for global rubber consumption in 2010 and 2011. Of this portion. rubber bands (8-10%) and elastic (89%).3. gloves (13-15%). . a renewable resource that presents an attractive alternative to hardwood timber.
Ltd. trade associations and R&D institutions are actively promoting the growth and competitiveness of the rubber industry. Supporters include: Rubber Research Institute of Thailand National Science and Technology Development Agency National Metal and Materials Research Center (MTEC) National Center for Genetic Engineering and Biotechnology (BIOTEC) Research and Development Institute of Industrial Production Technology..3. Dunlop Tire (Thailand) Co.3. opened its factory with a new production system. Thai-Bridgestone. has invested US$25 million in its radicalization project to raise the plant’s daily production capacity for airplane tires from 130 to 160 units and for automobile tires from 4. Ansell 2.3. Already.. Ltd. 2.3.3.8 Thailand’s Growing Tire Industry Thai Bridgestone Co.3.9 Supporting Organizations Thailand’s government. Ltd.P a g e | 24 2. expansion of production capacity is in the works. in February 2010 hosted the opening ceremony of its newly established Bridgestone Retread Center.900 to 7. Goodyear (Thailand) Public Co.7 Thailand’s Major Rubber Product Companies Tire products: Goodyear. Kasetsart University Prince of Songkhla University Department of Industrial Promotion Thai-German Institute Rubber Estate Organization Polymer Society (Thailand) .200 units. Michelin-Siam. boasting high investment efficiency and manufacture of high-quality radial tires at the Amata City Industrial Estate in Rayong Province. Dunlop Other rubber products: Top Glove..
6.50 million metric tons of rubber in 2008. Pipe and Belt: 450 thousand metric tons.4 Rubber Industry in China 2.1 Chinese Rubber Industry and Market China consumed a quarter of the rubber in the world. As such. Cycle tire: 420 thousand metric tons. Tire (sans cycle tire): 3. Emulsion: 200 thousand metric tons. increased 10% in 2008.8% of the world’s total consumption (22. Rubber consumption in the Chinese market in 2008 by industries: 1. The consumption keeps increasing due to the booming automotive industry. .50 million metric tons.18 million metric tons).3. accounting for 24.4. Footwear: 400 thousand metric tons. Total: 5.10 Attractive Investment Incentives The Board of Investment has classified the manufacture of natural rubber and rubber wood products as a priority activity.P a g e | 25 2. Others: 180 thousand metric tons.2. 2. the main rubber finished products. projects receive an eight-year corporate income tax holiday and are exempt from import duties on machinery.85 million metric tons. China consumed 5. 3. Driven by the automotive industry.2. 4. 2. China Rubber Industry Chen Nanyang The 2008 consumption increased 6% from the 2007 level mainly due to the booming automotive industry.3. 5. China's output of tires.
Read more at Suite101: China Rubber: Chinese Rubber Industry and Market million metric tons. But 0.4 metric tons of smuggling rubber from Vietnam impacted the market a lot due to the low price. Tire (sans cycle tire): 2. Cycle tire: 120 thousand metric tons. and China National Petroleum Corporation. 5. 6.000 yuan ($1. 2.170) per metric ton in late 2008.suite101. Pipe and Belt: 90 thousand metric tons.16 million metric tons.com/content/chinarubber-a163348#ixzz17L8svrz8) . (Source: of the world’s total consumption (9. Footwear: 30 thousand metric tons.45 million metric tons).53 million metric tons. Nature rubber consumption in the Chinese market in 2008 by industries: 1. Others: 70 thousand metric tons. National Bureau of Statistics of China.4. The import was around 1. accounting for 26. which went down to 8. Emulsion: 60 thousand metric tons. China’s output of nature rubber reached 600 thousand metric tons in 2008.P a g e | 26 2.2.53 million metric tons of nature rubber. Sources: China Rubber Industry Association. 4. 3.2 China Nature Rubber Industry and Market In 2008 China consumed 2.com/content/china-rubber-a163348 . Total: 2.
Material Raw rubber sheet (Source: ) . RSS4 and RSS5. We can see that the rubber industry is important to the nation with both of employment and exports. and compounds.unctad. Material Composition: Latex RSS (Rubber Smoked Sheet) Description: Our rubber smoked sheet (RSS) is available in standard strengths. Since Thailand is well equipped in terms of the material that is an advantage to competitors.html ) (Source:. It is used as a raw material for industrial production.th/office/import-export/rubber-rss. Thailand is the world first of natural rubber producer and can generate revenue from exports of rubber products in most of the world as well. sizes.ksgroup.3. RSS3. Block Rubber Description: The production of block rubbers involves relatively sophisticated machineries and heavy power consumption.P a g e | 27 2. The basic layout of block rubber production from latex. Thailand will need to accelerate the value creation of a more natural rubber. Smoked sheets are classified into 4 grades varying from RSS2. colors.3 Summary of Market value 2.1 Industry and rubber products.co.
farmkaset.4 million tons. and be recognized as.3. 2.11 percent because of government's policy is support more. And rubber trees in the high yield more. In 2010.aspx?id=1034&content=00262 ) 2. We will develop standards of raw rubber sheets and rubber smoked sheets of now a day to be high quality form level 3 to level 2 and level 1 that will have to acceptable of markets both . Korea. resulting in natural rubber in the world market will tend to increase continuously. And are confident that Thailand also holds a leading manufacturer and exporter of rubber in the world market amid competition is increases.2 Vision of our organization To be. Thailand can export up to 64 per cent per year to China.7 million tons of 2009 or 5. Rubber yields approximately 3. Meanwhile.7 percent from the year 2009.5 percent because China has been importing rubber from Thailand increase especially in the form of the compound.1. the trend of the growth of the tire industry in China.85 million tons up from 2. the leader complex rubber industry in the North of Thailand and group of neighbor country.3 Mission of our organization Thai-North Rubber tries to be the central of rubber industries in Indochina to accommodate the higher amount of rubber including support neighboring countries. Thailand will be use rubber about 0. Japan and the United States and Russia.1. which in the last three years.3. up from 0.22 percent.1 Production In 2010. up 6.5 million hectares of 2009 or 4. Malaysia.P a g e | 28 2.3 tons.37 million tons of year 2009 or 8.org/contents/defaultToLocalDetails.2 Export Thailand is expected to export about 2. Thailand will have more rubber tapping area are about 11. (Source: million hectares from 11. Malaysia and Vietnam. Because in many areas that can be opened gradually cut rubber tapping more open. The important competitions are Indonesia. Japan. as well as provide best of service for customer. 2. the United States and the EU.
Korea.3. The cost of rubber production in China is quite high.3.4. We chosen the market development to organized the company to export the rubber. the United States and EU. 2 in the world after the United States.3. by buying from local farmers will be use the local price.4. Japan. For rubber trade.P a g e | 29 domestic and international markets especially with China. 2. higher than that produced quite a lot. So we focus on the market to provide the rubber and we would to be the center north of Thailand to be export the rubber for neighbor countries. Malaysia. 2. So we should to concentrated for our competitors like Indonesia and We are the ones who collect the latex yield from the tag to leave the factory to produce our company for processing rubber sheets and rubber pieces. To Compared with another countries including Thailand. and EU.1 Corporate Level According to China’s demand for rubber. In additional any countries like Korea. up to 970. to export the rubber. which is No.4 Strategy 2. So. because we will use Time to send out a very long . And we will management marketing and international contacts to find loyal customers by planning to retain satisfaction by using CRM (customer relationship management) include of grower and farmer. rubber. for exports will be use the overseas market as a futures market and just at time which a criterion. The cost of rubber production in China is quite high. While China can produce about 500. US. Since the current investors in foreign investment into manufacturing base tire vehicles in China in 2543 increased. Because the climate is not suitable The Chinese can only rubber plantation area in the southern provinces only. Japan.000 tons per year. To Coupled with China’s rubber farmers lack the expertise in rubber cultivation.2 Business Level According to the status of our company we would to be the central North of Thailand to export the rubber to the neighbor countries like China. Malaysia.000 tons of rubber per year only makes rubber Chinese imports from abroad reached 470. the Chinese demand for rubber.000 tons / year.
2. In Chiang Rai province so no one company to export business of this type and rubber in the form as required by the market in China is extremely.3 Functional Level We will observe and analyze more sales from countries that we export and less profitable.3. We can assume that the processing and export of rubber. and we will bring the budget from that country to increased investment in the success or profitability of the business country. So.P a g e | 30 time. We will cut the country that we get the less profit or return loss.4. . we had chosen retrenchment strategy to organize our company.
P a g e | 31
Chapter 3
Market Feasibility Study
Industry Profile
3.1 Market Analysis
3.1.1 General Environment Analysis 3.1.1.1 General information of the People's Republic of China (PRC)
P a g e | 32
The People's Republic of China (PRC), 中华人民共和国, commonly known as China, is the most populous state in the world with over 1.3 billion people. Located in East Asia, China is a single-party state governed by the Communist Party of China (CPC)..
3.1.1.2 Geography (9,000 mi) long coastline bounded on the southeast by the South China Sea and on the east by the East China Sea beyond which lie Taiwan, Korea, and Japan.
P a g e | 33
Area Total 9,640,821 km2 [c] or
9,671,018 km²[c](3rd/4th) 3,704,427 sq mi - Water (%) 2.8[d] -. - The border between PRC and ROC is located in territorial waters. - China has a land border of 22,117 km(13,743 mi) , The largest in the world.
3.1.1.3 Demographics As of July 2010, was 0.6%. The PRC officially
recognizes 56 distinct ethnic groups, the largest of which are the Han Chinese, who constitute about 91.9% of Large the total ethnic
population.
minorities include the Zhuang (16 million), (10 million), Miao Hui Manchu (9 million), Uyghur
(8 million),
(7 million), Yi (7 million), Tujia (5.75 million), Mongols (5 million), Tibetans (5 million), Buyei (3 million), and Koreans (2 million).
283 (98th) . Hong Kong.Per capita $4. Between 150 and 200 million migrant workers work parttime in the major cities and return home to the countryside periodically with their earnings.745 trillion (2nd[5]) .4% to 46. Today. Figure 3-1 Major cities in China play key roles in national and regional identity. The country's urbanization rate increased from 17.Total $5.P a g e | 34 In the past decade. and Shanghai.084 trillion (2nd) .518(99th) GDP (nominal) 2010 estimate . a scale unprecedented in human history. China's cities expanded at an average rate of 10% annually.Total $10. culture and economics . including the three global cities of Beijing. GDP 2010 estimate .8% between 1978 and 2009.Per capita $7. the People's Republic of China has dozens of major cities with one million or more long-term residents.
the government advanced its basic education goal by pledging to provide completely free nineyear education. the central budget of the national scholarships will be tripled in two years and 223. are popular among the middle-class families who can afford them. As of 2007.3% of the populations over age 15 are literate. In March 2007. As of 2007.116 secondary schools.5 billion Yuan (28.2% for males and 98.5 Transportation Transportation in the mainland of the People's Republic of China has improved significantly since the late 1990s as part of a government effort to link the entire nation through a series of expressways known as the National Trunk Highway System (NTHS).4 Education In 1986. China announced the decision of making education a national "strategic priority". almost all children in urban areas continue with 3 years of high school. China's youth (age 15 to 24) literacy rate was 98. second only to the United States. often investing large portions of the family's income on education. The total length of expressway is 65. there were 396.1.000 mi) at the end of 2009. including textbooks and fees.380 mi) of service routes. Free compulsory education in China consists of elementary school and middle school. such as in foreign languages or music.567 primary schools.9% (99. China set the long-term goal of providing compulsory nine-year basic education to every child.1. which lasts for 9 years (age 6-15).5% for females) in 2000.000 km (40.236 higher education institutions in the PRC.P a g e | 35 3. Private lessons and recreational activities. 93.050 km (4. 3. 94. Many parents are highly committed to their children's education. In February 2006.65 billion US dollars) of extra funding will be allocated from the central government in the next 5 years to improve the compulsory education in rural areas. and 2.1.1. China has also the world’s longest high-speed rail network with over 7. .
(Source:. and freedom of religion. divided into various railway bureaus in different regions.1. and the National People's Congress has been described as a "rubber stamp" body. North Korea. however the PRC is still far from the liberal democracy practiced in most of Europe or North America. Hong Kong has one of the most developed transport systems in the world. At the rates of demand it experiences.org/wiki/People's_Republic_of_China#Education) 3. and Cuba). but simple characterizations of PRC's political structure since the 1980s are no longer possible. Railways are the vital carrier in China. the system has historically been subject to overcrowding during travel seasons such as Chunyun during the Chinese New Year. Compared to its closed-door policies until the mid-1970s.2 PES Analysis 3. reproductive rights.1. with heavy restrictions remaining in many areas. . The major cities have rapidly expanding networks of underground or light rail systems. the liberalization of the PRC is such that the administrative climate is less restrictive than before.P a g e | 36 Private car ownership is increasing at an annual rate more than 15%. Shanghai has a Maglev rail line connecting its urban area to its main international airport. but remains too expensive for most. most notably on the Internet. but also as authoritarian. they are monopolized by the state. Long distance transportation is dominated by railways and charter bus systems.wikipedia. The PRC government has been variously described as communist and socialist. the press. Numerous cities are also constructing subways. freedom of assembly. Laos.2. Pudong International Airport. and China surpassed the United States became the largest automobile market in the world with total sales of more than 13.1 Political The PRC is regarded by several political scientists as one of the last five Communist states (along with Vietnam. The sale of automobiles had been increasing rapidly after the financial crisis in 2009.6 million Domestic air travel has increased significantly. The PRC's incumbent president is Hu Jintao and its premier is Wen Jiabao.
whose power is enshrined in China's constitution.1 foreign donor for China. To propel the country towards a modern.1. Collectivization of the agriculture was dismantled and farmlands were privatized to increase productivity. The political system is very decentralized with limited democratic processes internal to the party and at local village levels. the CPC wins by default most of the time. referred to in China as democratic parties. Political concerns in the PRC include lessening the growing gap between rich and poor and fighting corruption within the government leadership. which participate in the People's Political Consultative Conference and the National People's Congress.2. Private businesses and capitalism did not exist. Since 1978. and that legislatures have shown some assertiveness from time to time. China's economy is mainly characterized as a market economy based on private property ownership. the People's Republic of China was a Sovietstyle centrally planned economy. the Party retains effective control over government appointments: in the absence of meaningful opposition.P a g e | 37 The country is ruled by the Communist Party of China (CPC). Japan has been No. There are other political parties in the PRC. The level of support to the government action and the management of the nation is among the highest in the world. Mao Zedong instituted the Great Leap Forward. However. Following Mao's death and the end of the Cultural Revolution. Foreign trade was focused upon as a . There have been some moves toward political liberalization. Deng Xiaoping and the new Chinese leadership began to reform the economy and move to a market-oriented mixed economy under one-party rule.2 Economic From its founding in 1949 to late 1978. although these experiments have been marred by corruption. In 1978. industrialized communist society. A wide variety of small-scale enterprises were encouraged while the government relaxed price controls and promoted foreign investment. in that open contested elections are now held at the village and town levels. China and Japan had normalized diplomatic relations and China had decided to borrow money from Japan in soft loans. with 86% of people who express satisfaction with the way things are going in their country and with their nation's economy according to a 2008 Pew Research Center survey 3.
8%. The PRC. an undervalued exchange rate. The latter has been sometimes blamed for the PRC's . Ten years ago.06 trillion Yuan (US$4. and some say. The PRC's success has been primarily due to manufacturing as a low-cost producer. China was the seventh largest country in global wealth and China currently holds $ 16. resulting in massive job losses. favorable government policy.9 million inbound international visitors in 2009.6%. The PRC owns an estimated $1. Inefficient state-owned enterprises (SOEs) were restructured by introducing western-style management system and the unprofitable ones were closed. and 42.05 trillion corresponding to US$6.800 per capita. medium level of technology and skill.700 is still low and puts the PRC behind roughly a hundred countries he primary. secondary. Since economic liberalization began in 1978. 35 percent ahead of the wealthiest European country.99 trillion). which led to the creation of Special Economic Zones (SEZs) first in Shenzhen (near Hong Kong) and then in other Chinese cities.21 trillion – US$1. the PRC's investment. the PRC's economy is second only to the US at US$9. If PPP is taken into account. holding US$801. It is the world's third largest recipient of inward FDI by attracting US$92. It now has the world's second largest nominal GDP at 34.5 billion in Treasury bonds. although its per capita income of US$3.and export-led economy has grown 90 times bigger and is the fastest growing major economy in the world. The PRC is the fourth most visited country in the world with 50. making it by far the world largest. 46.4 trillion. relatively high productivity.P a g e | 38 major vehicle of growth.20 trillion in export and US$1.01 trillion in imports. The inaugural Global Wealth Report by Credit Suisse Research Institute collects data across more than 200 countries in mid-2010 stated China is expected to overtake Japan as the second wealthiest country in the world by 2015 ($35 trillion) on the back of rapid economic growth and strong domestic consumption. It is a member of the WTO and is the world's second largest trading power behind the US with a total international trade of US$2.5trillion. This is attributed to a combination of cheap labor.6 trillion of US securities. good infrastructure.2 billion in 2008 alone becoming the world's sixth largest outward investor. France. is the largest foreign holder of US public debt.6% respectively to the total economy in 2009. and tertiary industries contributed 10. Its foreign exchange reserves have reached US$2.4 billion in 2008 alone. while the country itself increasingly invests abroad with a total outward FDI of US$52.
302 trillion) in 2007 and growing at 16. four of the world's top ten most valuable companies are Chinese. Today. It is also now the world's second biggest consumer of luxury goods behind Japan with 27. Measured using market capitalization. SSE's market capitalization reached US$3 trillion in 2007 and is the world's fifth largest exchange. China now ranks 29th in the Global Competitiveness Index. and Japan – despite the yuan having been de-pegged and risen in value by 20% against the US$ since 2005.000) has now reached more than 100 million. EU.5% of the global share.5 million) is estimated to be 825. 2005) of GDP in 2005. the PRC's rapid growth managed to pull hundreds of millions of its people out of poverty since 1978. Its middle class population (defined as those with annual income of at least US$17. Although a middle income country by the world's standard. about 10% of the Chinese population (down from 64% in 1978) live below the poverty line of US$1 per day (PPP) while life expectancy has dramatically increased to 73 years. 46 Chinese companies made the list in the 2010 Fortune Global 500 (Beijing alone with 30). compared to 20% in 1950. Its stock market in Shanghai (SSE) is raising record amounts of IPOs and its benchmark Shanghai Composite index has doubled since 2005. . Some of these include first-ranked Petro China (world's most valuable oil company). China's retail market is worth RMB 8. The state still dominates in strategic "pillar" industries (such as energy and heavy industries). fifth-ranked China Mobile (world's most valuable telecommunications company) and seventh-ranked China Construction Bank.7 billion in 2007) and has become a major source of dispute between the PRC and its major trading partners – the US.000 according to Huron Report.8% annually. third-ranked Industrial and Commercial Bank of China (world's most valuable bank). while the OECD estimate is over 50% of China's national output.9 trillion (US$1. but private enterprise (30 million private businesses) now accounts for anywhere between 33% (People's Daily 2005) to 70% (Business Week. More than 93% of the population is literate. while the number of super-rich individuals worth more than 10 million Yuan (US$1. up from 1% in 1978. Urban unemployment declined to 4 percent in China by the end of 2007 (true overall unemployment might be higher at around 10%).P a g e | 39 bulging trade surplus (US$262.
Coupled with a lax environmental regulation. which was aimed at improving sanitation and hygiene. the health of the Chinese public improved rapidly because of better nutrition despite the disappearance. Health care in China became largely private fee-for-service. as well as attacking several diseases.Consequently. The country's life expectancy at birth jumped from about 35 years in 1949 to 73. oversees the health needs of the Chinese population. Despite significant improvements in health and the introduction of western style medical facilities. China has several emerging public health problems. The urban-rural income gap is getting wider in the PRC with a Gini coefficient of 46. and central regions of China. along with the People's Communes. the Communist Party started the Patriotic Health Campaign. Malnutrition as of 2002 stood at 12% of the population according to United Nations FAO sources. and scarlet fever were nearly eradicated.P a g e | 40 The PRC's growth has been uneven when comparing different geographic regions and rural and urban areas. An emphasis on public health and preventive medicine characterized health policy since the early 1950s. of much of the free public health services provided in the countryside.18 years in 2008.1.9%. together with its counterparts in the provincial health bureau. and infant mortality went down from 300 per thousand in the 1950s to about 23 per thousand in 2006. this has led to a massive water and air pollution (China has 20 of the world's 30 most polluted cities). The economy is also highly energy-intensive and inefficient – it uses 20%–100% more energy than OECD countries for many industrial processes. At that time. the government has promoted development in the western.2. To counter this. typhoid. It has now become the world's largest energy consumer but relies on coal to supply about 70% of its energy needs. Development has also been mainly concentrated in the eastern coastal regions while the remainders of the country are left behind. the government has promised to use more renewable energy with a target of 10% of total energy use by 2010 and 30% by 2050.3 Public health and Environment The Ministry of Health. northeastern. This has shown major results as diseases like cholera. which include . 3. With economic reform after 1978.
But the environment continues to deteriorate. China started to develop its own nuclear weapons and delivery systems. Some 90% of China's cities suffer from some degree of water pollution.6 billion invested in clean technology in 2009. 3.1. such as the 2003 outbreak of SARS (a pneumonia-like disease) which has since been largely contained. Part of the price China is paying for increased prosperity is damage to the environment.4 Science and Technology After the Sino-Soviet split.000 people per annum from air and water pollution (including indoor air pollution). Estimates of excess deaths in China from environmental pollution (apart from smoking) are placed at 760. China has some relevant environmental regulations: the 1979 Environmental Protection Law. they are frequently disregarded by local communities while seeking economic development. China produces more wind turbines and solar panels each year than any other country. a possible future HIV/AIDS epidemic. successfully detonating its first surface nuclear test in 1964 at Lop Nur. With $34. China's large population and close living quarters has led to some serious disease outbreaks in recent years. and nearly 500 million people lack access to safe drinking water. While the regulations are fairly stringent. According to the Ministry of Water Resources. which was largely modeled on US legislation. to be significant health hazards in China. only one Chinese city was making an effort to clean up its water discharges. In 2007. A . roughly 300 million Chinese are drinking unsafe water. with 400 out of 600 cities short of water. Reports by the World Bank and the New York Times have claimed industrial pollution.2. and an increase in obesity among urban youths. Leading Chinese environmental campaigner Ma Jun has warned that water pollution is one of the most serious threats facing China. particularly of the air. Twelve years after the law. This makes the crisis of water shortages more pressing.P a g e | 41 respiratory problems as a result of widespread air pollution and hundreds of millions of cigarette smokers. China is the world's leading investor in renewable energy technologies. China has overtaken the United States as the world's biggest producer of carbon dioxide.
China has plans to build a space station in the near future and to achieve a lunar landing in the next decade.000 researchers. using a Long March 2F launch vehicle and carrying Chinese astronaut Yang Liwei. There are also plans for a manned mission to planet Mars.3 million in the United States. making it the third country to have the capability to conduct a spacewalk. including renewable energies such as hydro. wind and solar power. China has the world's second largest research and development budget. In 2007. China successfully completed the Shenzhou 7 mission. the first Chinese satellite. China completed its second manned mission with a crew of two. named after the ancient Chinese moon goddess. President Hu Jintao called for China to make the transition from a manufacturing-based economy to an innovation-based one and the National People's Congress has approved large increases in research funding. Stem cell research and gene therapy. China has an estimated 926. The Chinese government continues to place heavy emphasis on research and development by creating greater public awareness of innovation. and have potential applications for the hydrogen economy. In 1992. After four unmanned tests. . In 2008. This made the PRC the fifth nation to independently launch a satellite. making the PRC the third country to put a human being into space through its own endeavors. the Shenzhou manned spaceflight program was authorized. face minimal regulation in China. which culminated in 1970 with the launching of Dong Fang Hong I. and is expected to invest over $136 billion in 2006 after growing more than 20% in 2005. second only to the 1. Shenzhou 5 was launched on 15 October 2003. which run cooler and safer. Shenzhou 6 in October 2005. semiconductor and energy industries.P a g e | 42 natural outgrowth of this was a satellite launching program. the PRC successfully sent the Chang'e spacecraft. which some in the Western world see as controversial. In 2006. to orbit and explore the moon as part of their Chinese Lunar Exploration Program. China is also actively developing its software. and reforming financial and tax systems to promote growth in cutting-edge industries. China has been pioneering the deployment of pebble bed nuclear reactors. In an effort to reduce pollution from coal-burning power plants.
a number of New Confucians have advocated that democratic ideals and human rights are quite compatible with traditional Confucian "Asian values. such as the individualistic Song Dynasty neo-Confucians. They further argue that many important aspects of traditional Chinese morals and culture. such as Confucianism. They sought to change some traditional aspects of Chinese culture. while preserving others. The system is expected to process seismic data for oil exploration. such as the belief that calligraphy and literati painting were higher forms of art than dancing or drama. such as rural land tenure. while others say that the CPC's rule has damaged the foundations of Chinese culture. . China developed Tianhe-IA.P a g e | 43 In 2010. and a Confucian education.2. currently stored in the National Supercomputing Center of Tianjin. It is two publicy (for military or something secret usually is not announced) available supercomputers among world's top 10. who believed Legalism departed from the original spirit of Confucianism. Chinese art. especially through political movements such as the Cultural Revolution. China's traditional values were derived from various versions of Confucianism and conservatism. conduct bio-medical computing and help design aerospace vehicles. Besides China's National SuperComputer Center's Tianhe-1A above. The literary emphasis of the exams affected the general perception of cultural refinement in China. were destroyed. opportunity for economic and social advancement in China could be provided by high performance on Imperial examinations. sexism. such as Legalism.1." The first leaders of the People's Republic of China were born in the old society but were influenced by the May Fourth Movement and reformist ideals. A number of more authoritarian and rational strains of thought have also been influential. 3. where many aspects of traditional culture were labeled 'regressive and harmful' or 'vestiges of feudalism' by the regime and thus. There was often conflict between the philosophies. In recent years. such as the family structure and obedience to the state. China also has Nebulae. Many observers believe that the period following 1949 is a continuation of traditional Chinese dynastic history.5 Culture For centuries. the world's fastest supercomputer. Examinations and a culture of merit remain greatly valued in China today.
Current output is used in only 4% and sent to China. Since the Cultural Revolution ended. and sparked interest nationally and even worldwide. Most of them are targeting the same product. Artifacts from the history of the silk route.3 Competition Analysis 3.sritranggroup. and folk and variety art in particular have gained a new found respectability.. Thailand's largest rubber. fashion and architecture have seen a vigorous revival. lauding it as an important achievement of the Chinese civilization and emphasizing it as vital to a Chinese national identity. (Source:. as well as from the natural history of the Gobi desert. literature.P a g e | 44 literature. it is currently involved with private business. film.php) Southland Holding Co. we inflicted a direct competitor. is expected to grow at least equal to China for this reason. and 39% most 17% by the Indian market. We need more foreign and rubber non-stop.org/wiki/People's_Republic_of_China#Education) 3.1.com/en/page/10_corporate. Therefore. Ltd (Source:. India..com/) Sri Trang Agro-Industry Public Company Limited (Source:. Today. Chinese culture and the West were linked by the Silk Road. and Thailand did not stop the production and Exports of rubber behind demand. as manufacturer and exporter behind Thailand.1 Competitor Analysis Now Chaing Rai province is the area of rubber plantation and processing factory rubber export demand growth from China. The Company has many competitors. are displayed in the Silk Route Museum. and performing arts like Beijing opera. were altered to conform to government policies and propaganda at the time. (Source:. And similar in some for our major competitors such as Chalong Latex Industry Co.com/e_index.Ltd. India.php) .wikipedia. the Chinese government has accepted a great deal of traditional Chinese culture as an integral part of Chinese society.3. music. various forms of traditional Chinese art. In the future.1.
The company started producing smoked rubber in 1978 with Bridgestone as its first customer. (Source:. Thai Hua Rubber Public Co. In total the company employs about 1900-2000 workforce. The company has business joint ventures with foreign investors to produce Medical Rubber Glove. since 1991. The family together with some neighbors moved to Rayong in 1957 and brought some rubber seedlings. That is contributable to our success. For more than three decades. raw and roasted Coffee Bean. Luckchai's grandfather held when he emigrated from China to Nakhon Si Thammarat 80 years ago.com/) Thai rubber latex corporation (Thailand) Public company limited. Original formed in 1985 under the name of THAI HUA RUBBER COMPANY LIMITED by the family KITTIPOL together with some close relatives. Thai Rubber Latex Corporation is a leading manufacturer and exporter of latex concentrate. extruded rubber thread. talcum coated rubber thread. Thai Rubber Latex Corporation has stably become one of the most recognized concentrated latex producers in Thailand and gained numerous reputations within rubber industry worldwide. and spontaneous customer services. the company was rank as one of the largest rubber producer and exporter in Thailand. rubber wood Kitchenware.P a g e | 45 The big competitors such as Thai Hua Rubber Public Co.Ltd Planting para rubber was the first job that Mr.. (Source:. the company changed its name to THAI HUA RUBBER PUBLIC COMPANY LIMITED.thaihua. Our core competitiveness is derived from consistency of supply. China. and various rubber products. disposable rubber glove. Ltd head office is situated in Bangkok. auto Tyre.com/) . high-quality products. In 1996..thaitexgroup. The company has 11 production plants in different region of Thailand and 1 branch office in Shanghai.
This is the largest rubber company in China. our rubber processing.7 billion Yuan registered capital of 800 million Yuan. most with 54 % of the export value of rubber. A clear target groups and analyzed the characteristics of the possibilities.3. 130.. The target customers that will lead to success in direct sales in the analysis. Of capital than 2.S. the area planted in rubber production to 1. all of Thailand. Therefore.260 million. followed by rubber smoked sheets (26%) and latex (19%) for the information. In Yunnan province is one of the 10 major industrial facility of the county by the year 2004 the company Yunnan Nong Ken Group Co.000 tones per cent. Ltd in association with Yuntian Hua Group Co. Ltd was at Kun Ming City. and the prospects salesman match has to be divided clear market that can be measured quantitatively and easy access because consumers all potential customers may not always and if there is no market segmentation is difficult to analyze the needs of actual customers until they are not able to offer in the form of satisfaction to their customers. China is the country of the world's largest rubber volume of use is 25 per cent of the amount of rubber in the world in the last 5 years.5 million square meters per year. Interest of the rubber market in China is as follows. we see that China is to be a good customer in the export business.2 Customer Analysis Customer Analysis is determined by target customer or we have to offer sales and services to customers where that the analysis of target groups (Occupants) allows to know the behavior in the purchase and use of the actual target group.. $ 3.P a g e | 46 3. . the demand for rubber in China is rapidly increasing average 10 percent per year until the top importing countries rubber largest one of the world in 2007 China imported rubber worth U. Ltd established Yunnan Natural Rubber Production Co.. Thailand's largest rubber exports to China. Increased 8 percent compared with the year 2006 with a market share of Thailand is also number one export market.1.
Bargaining power of supplier Crisis. The rubber farmers of more than 15. Bargaining power of buyer Aggregation of rubber sales not only benefit from the purchase was also the bargaining power of customers further reduced by this method uses the price of goods up within the group is treated the same price. The profitability of other it's the technique that can each store from which some without prejudice to the agreed price. The help given the . the company turned to new interests and rubber production increased because of the importance of rubber and to demand more.forces model for the competitive Rubber in Chiangrai. Resulted in land price increase from 3000-3500 baht per rai per rai is almost ten thousand Baht and if thinking about buying a rubber plantation grown then. Make money flow into the economy of Chiang Rai. The Phaya Meng Rai has big capitalists to buy about 1 thousand farm to plant rubber.P a g e | 47 3. Threats of new entry Rubber is currently increasing need in the market. production and cost the same. Customers will not be able to negotiate a trade because the price out of each stores the same. the decline in rubber prices during the year 2534 to year 2535 continued to rubber farmers have suffered and demanding the government come. The Rivalry among Existing competitor Now in Chiangrai has private investors from the South of Thailand the major buy a lot of rubber cultivation and the Chiang Rung. Considered a source of rubber cultivation is important. If not satisfied with the price I have to buy it because the other stores selling the same price. Khun Tan.Chiang Khong Wiang Chai entertainment section has a factory finish. Therefore.1. about 10 million Baht.000 families are planting more than 350. Especially in Chiang Rai. The use of rubber processed and used in many benefits and its growing cluster what are our company’s major competitors ago.3 Competitive Analysis The Five .000 acres and is about to open another cut hundreds of thousands of farm This will generate revenue to rubber farmers in the future. This can be done very easily because the supply of goods.000 acres and rubber tapping rubber to open no less than 5. We have been promoting and expanding rubber cultivation area to the north. Rubber demand exceeds capacity.3. I need to add more to the old rubber thousand baht per rai per year.
" There are also issues about the relationship between the price of rubber in the market AFET and the price of rubber in the international market is likely to become possible in the same direction. It is one way the government aims to develop a system of rubber market. Result in charges pay market prices and margins in each level resulted in farmers selling at a low price for rubber tire market in Thailand is having problems as well. The market is vulnerable lack of bargaining power and do not get their fair due from the sale of tire dealers be purchased including assessment quality rubber than the reality because most poor farmers have to sell products to the market as well as the immediate livelihood Rubber multi-level dealers. The rubber has important role in determining the price of rubber. these are all things affecting the basic rubber. The price of rubber has a close relationship with the oil price in world market simply means "to oil the tires up.P a g e | 48 structure of the Thai rubber market appeared to look like a buyer's market or a few buyers market the rubber farmers. both domestic and foreign countries to be effective. Yang lack of markets to free competition. Since replacement of the rubber product is a synthetic rubber by-product is distilled from crude oil. The majority of small rubber planters established central rubber market. . Rubber products have quite a vehicle and industrial rubber products. Threats of substitute product and service Threat of substitute products and services for business expansion plans are to the relatively high. because the sender used the method of direct trade between producers and users.
) 3.2 STP analysis 3.P a g e | 49 3. India. . China. we segment market by using the country that wants to import the rubber to be the base for segmenting market. We want to kwon what country suitable for exports our products. German etc Figure 3-2 Rubber consumption in the world USA China Japan India Korea German Malaysia Thailand Turkey Other (Source: Geojit Comtrade Research Desk. Our target is a China-market specialization following in the table.2.2 Market Target Thai-North is having only main one target focus. Korea.Geojit Comtrade Ltd. Natural Rubber: Will the Rally Contnue?. So we have many countries in the international rubber market to export such as USA.2. Japan.1 Market segment Our company planned to export products.(2010).
with 54 percent of the total export value and followed with Smoked Rubber Sheets (RSS) to responding growth of automobile industry in China. demand for rubber is increased continuously and become a product shortage that make demand of smoked rubber sheets(RSS) and Block Rubber are continuous. Vol.2 No. (Source: Export-Import Bank of Thailand) Figure 3-2 Increasing in demand of rubber in China annually 4000 3500 3000 2500 2000 1500 1000 500 0 2754 2743 3043 3353 :1000Tons ・・#" ・・ "# ・・#" ・・ "# (Source: Association of Natural Rubber Producing Countries. we have policy to production with higher quality and try to develop standards and quality of basic processing rubber to meet the needs of Chinese industry. while today China cannot produce rubber to enough their demand. Thailand export block rubber to China most. Monthly Bulletin of Natural Rubber Trends & Statistics.P a g e | 50 EXHIBIT 3-1 Market Specialization US Rubber Smoked Sheet (RSS) CN JP IN KR DE MY TH TR Block Rubber China is a country that import rubber largest of the world.7 July 2010) . The rapid economic development in recent years in China. Moreover.
tires. STR5L. 3. Thai-North Rubber position is the export quality. etc. 2. EXHIBIT 3-2 Thai-North Rubber Position Export Quality Standard Rubber Smoked Sheets 1( Extra light color ) Rubber Smoked Sheets 1 Rubber Smoked Sheets 2 Rubber Smoked Sheets 3 Rubber Smoked Sheets 4 Rubber Smoked Sheets 5 Domestic’s quality Export’s quality - Block Rubber Divided into 4 categories are STR XL. automotive parts. Smoked Rubber Sheets (RSS) The split into 5 categories: Rubber Smoked Sheet 1. allow to product line we can rank with many grade to serve the variance of demand.P a g e | 51 3.. 4 and 5 classes by grading the quality of rubber is used as the basis for each disc as a raw material to production of goods such as water wheels. STR 5 and STR 5CV**. The products are divided into grades by using the ground base eye (Visually Grade) is divided into rubber smoked sheet. shoes. It is a product used as raw materials in manufacturing and other products like the Rubber Smoked Sheet (RSS) on the tire industry.2. .3Positioning Our production is for export quality.
Our positioning is EXHIBIT 3-3 Positioning of Our Company Standard Standard Thai Rubber XL Domestic’s quality Export’s quality - Standard Thai Rubber 5L Standard Thai Rubber 5 Standard Thai Rubber 5 CV** Standard Thai Rubber 10 Standard Thai Rubber 10 CV ** Standard Thai Rubber 20 Standard Thai Rubber 20CV** (Source:. conditions and standards required. The test results with high accuracy include of the transport process that ensures of all products delivered to customer’s needs.com/th/page/20_products2.sritranggroup.php ) .P a g e | 52 Block Rubber is begins with the selection of raw materials and strict control before entering the manufacturing process until it is completed and tested with lab standard quality.
Sheet farmers as raw rubber sheets and rubber at higher quality level 3 to level 2 and level 1. . when the plants purchased raw rubber sheets of these farmers to be rubber smoke with low quality. 3. Would achieve higher sales prices and increased profits. through the manufacturing process to reduce the size of a modern.3. However. We think that exporting rubber processing. Rubber process into the cooked temperature through the process of briquette weight to be prescribed through rubber packaging will be processed by the laboratory test standard. However. So that a primary processing plant of rubber latex rubber sheet Raw and smoked sheets will create added value for the rubber to meet processing products in China. The processing plant was established to help develop basic rubber tires standard.1. 3.3. We see that if the export rubber in latex. The raw rubber sheet becomes rubber at higher prices immediately. There are opportunities and possibilities in developing countries as a manufacturing center.1 Product Since Thailand is well equipped in terms of the raw material advantage with Competitors.To produce sheet rubber and rubber smoked for higher quality.1.3. China has a very high market demand in terms of rubber. it is difficult to transport. That it would be easier and more convenient in transportation. and send the basic process for quality products to meet the needs of users. Is there a way to make prices higher by introducing the steam or smoke. clean as determined by it. processing of raw rubber sheet at the present the farmers have production low quality.3 Marketing Mix Strategy 3. the raw rubber sheet. The test results with high accuracy.2 Quality Packaging Rubber production is a standard selection of quality raw materials.P a g e | 53 3.1 Variety Branding There are 2 type of product of rubber processing such a Rubber Smoked sheet (RSS) and Block Rubber to export in China. rubber farmers who produce poor quality.
The Company is divided into save cost price which price to purchase directly from agriculturist.3 Place 3. .P a g e | 54 3.3.3. And will comply with the demand of rubber in the industry and are buying that. According fact the amount of rubber agriculturist organizations or vendors to sell products and there are a lot of volume.1 Factory Our company choose Chiang Rai province to set up factory because it is the suitable for processing rubber. is sold with partners and using the global export prices.857 Rai. We are separated by price segment in which we will split the purchase price and export volume of purchase and the demand of consumers by period time. Based economic growth also .Save cost is the price to purchase directly from agriculturist. The major factor that made we choose that are raw material. On Export the company will focus on the world market. We use each day pricing. We will push the price of rubber to raise to the level of agriculturist tires a profit worth the investment and maintain the rubber price to be stable. as appropriate to the situation and possible price to buy and prices. 3. Surat Thani. We have many factors to choose this province. The company offers a low cost. Trang etc. Right now is extremely competitive. Of course. Using the global export prices overall rising trend.3. 347. Chaing Rai have trend to rubber plant across the 18 districts.3. Nakhkon Si Thammarat. Expected in the coming years Chaing Rai will be the top of rubber plant in the country subordinate of Songkhla. . Due to market products based on low. now that the company will be based on a range of rubber products to market but that price will be adjusted up or down. It is a major exporter. Companies are using strategies is pricing conjunction with the world market price. The concern the market should not worry because the information was reviewed currently Thailand’s rubber emphasis on export to China 39%. This has variance and based on the quality of rubber parts for each class of agriculturist.Price is sold with partners.2 Price The pricing of the companies will be priced based on the purchase price of domestic.
While the eastern part of the province is relatively flat river plains. former residence of the Late Princess mother (mother of the present king) Somdej Phra Srinagarindra. Chiang Rai is the northernmost province of Thailand.P a g e | 55 growth continued until we produce left behind to rest 4% of the country. Neighboring provinces are Phayao.aspx?NewsID=9530000131252) 3. the western part consists of the mountainous terrain of the Hills of Northern Thailand. Lampang and Chiang Mai. Geography The average elevation of the province is 580 m.3. the 1389 m high Doi Tung (Flag hill) is the most important hill.manager.1 General Information of Chiang Rai province. . Laos and Myanmar converge . Chiang Rai is the suitable that we will set up factory. The north of the province belongs to the so-called Golden Triangle. We expect that it will lower wage and save cost. Through the town of Chiang Rai itself flows the Kok River.3. In the north it borders Shan State of Myanmar and Bokeo of Laos. Thanks to her activities the hills were reforested. and the hill tribes changed from growing poppy to other crops. Currently Office of the Rubber Replanting Aid Fund is pushing to have more offices at the port of Chiang Khong to facilitate the export of rubber to China and South of China. While not the highest elevation of the province. Nearby is the Doi Tung royal villa.1.th/Local/ViewNews. at which the borders of Thailand. the Mae Sai and Ruak River to Myanmar. So we can employee from those countries.co. (Source:. Other factor is about employee Chiang Rai have the border near with Myanmar and Laos. The Mekong river forms the boundary with Laos. The Wat Phra That Doi Tung temple on top of the hill according to the chronicles dates back to the year 911.an area which was very unsafe because of the drug smuggling across the borders. At the same time Chaing Rai also has the ability to export to China via South Road R3A.
.1. notably Santikhiri. arts.P a g e | 56 Demographics The majority of the population is generally ethnic Thai.wikipedia. And we will do the same with warehousing.2 Inventories and Warehousing We will locate Inventories and Warehousing near the Factory because it will better to save cost of transport. We have plan to expanse to be located near the port for save cost of logistic but it up on the production and the profit that we will get. The region is home to distinctly different food. music. A minority are of Chinese descent.5% of the population belongs to the hill tribes. Chiang Rai is also a melting pot of hill tribes and their own unique cultures.org/wiki/Chiang_Rai_Province) 3. If we have high of return this project will follow. a minority in the North of Thailand. mainly descendants of the Kuomintang soldiers who settled in the region. but 12. way of life and even language. (Source:. The Inventories up on the demand of products we will management inventory to be value with space that we have. It will be close to the factory and not far to the port that we will ship the product.3. Medical Health Care The popular Chiang Rai hospitals are: Chiang Rai Regional Hospital Kasemrad Sriburin General Hospital Overbrooke Hospital Local Culture The north of Thailand's culture is Lanna in origin and the people are very proud of their northern roots.
Air All most shipping in early season of production that have a few products and high price to Airports in various major cities of China such as Airport City Kun Ming.P a g e | 57 3. Shanghai. Free area. Guangzhou City. Then change to freight ship small for transport to Nan Hai Pier. R9) is start from Nong Khai Province. Guangxi. In 2001Thailand has exported vegetables and fruits to amount of 100 tons or value of 3. Beijing and Xiamen Min. Laos to Vietnam and enters to China. The First routes. Go to central wholesale market of fruit imported Lee Sui. Transport by the Mekong River by start from port of Chiang Saen district or Chiang Khong district in Chiang Rai province. . Shipping to port of City Xishuangbanna in Yunnan Province or port of Nanning city. Guangxi.7 billion Baht. The First route(R 12. Four days for shipment. There are two routes that Thai can shipment to China. R8 and R13. Nanning City. Beijing etc. And distribute the goods to the following cities of Guangdong and other provinces such as Shanghai. Free area. Motor There are five routes but in present not widely used because of poor road conditions and construction was not completed.2 Location Logistic In the present there are three ways to shipments from Thailand to The People’s Republic of China. Then distribute the goods to the following cities. The Second routes. Ocean Now transport by ship is major transportation routes. Most of the freight route is start from Laem Chabang through the South China Sea to Hong Kong. Chengdu.3. Kakhon Phanom Province and Muk Da Han to Vientiane.3.
The Last route (R3A) is start from Honor district of Nan province to Laos through Checkpoint of Huaikorn. R3W) is start from Mae Sai district of Chiang Rai province to Myanmar side to Dan Tha Khi Lek through Chiang Tung City to Xishuangbanna in China with a distance of 253 kilometers. The Third route (R3B. Boten and Bohan and enters to Xishuangbanna in China with a distance of 254 kilometers. Yunnan province with a distance of 240 kilometers.P a g e | 58 The Second route (R3B. Boten. Namnegrn. Bohan and enters to Xishuangbanna in China with a distance of 300 kilometers. .R3W) is start from Mae Sai district of Chiang Rai province to Myanmar side to Checkpoint of Tha Khi Lek through Young City and enters to Xiamen Song City of China to Xishuangbanna. The Forth route (R3A) is start from Chiang Khong district of Chiang Rai province to Laos through Huai Sai in Luang Nam Tha.
The 5. technical issues and varying levels of enthusiasm among countries involved. with an additional section of track connecting it to Laos.P a g e | 59 Kunming-Singapore Railway Rail Kunming-Singapore rail link by 2015? The Associated Press reports that the Association Asian is of Southeast (ASEAN) US$15 connecting Nations a expecting billion railway with Singapore Kunming to be completed by 2015. (Source:. which is expected to dramatically increase the flow of people and cargo throughout the region. which is several years later than had been previously hoped.000 kilometer (3.000 mile) rail line's development has been hampered by a lack of funds.4 million in grants also being secured for the rail line. ASEAN secretary-general Ong Keng Yong told the AP that the Asian Development Bank has recently given Cambodia US$40 million in soft loans. The western branch will travel through Myanmar and the line's eastern branch will cut through Cambodia and Vietnam.gokunming.com/en/blog/item/27/kunmingsingapore_rail_link_by_2015 ) . passing through Malaysia. it is the two branches extending north from Bangkok that have proven more difficult. with an additional US$5. There is already an existing rail link from Singapore to Bangkok.
P a g e | 60 EXHIBIT 3-4 Trans-Asian Railway network (Source: The exhibitions show The exhibitions show will also introduce ThaiNorth Rubber and is still regarded as temporary sales channels with a low cost to deliver and demonstrate products to consumers directly.th/fruit-olympic/freetrade-thaichina.tu.mof. Department of Export Promotion (DEP) and Foreign Market Development Office in line of China.4 Promotion 3.4.ac.3. The show had to be coordinated on several issues. The trade show will be arrange meeting .htmand. The important.3.econ.th/ertc/php/) 3. we will work with government agencies of Thailand and China that help us to promote and support like The Oversea Trade Fair.or.
3. Thai-North Rubber © (Source: Website Marketing strategy is effective and cost-effective results to our most other one is. is will helps take the good image of Thai-North-Rubber to modern. We can track any information from such cooperation. Marketing online and one of the key elements of online marketing strategies for our business is web site. in the critical locations in economy throughout the year such as Bangkok.3.P a g e | 61 between entrepreneurs and those interested. Shanghai and Zhejiang.4. etc. And the price of goods down by reduce middleman which will increase competitiveness in the global market. cope.com/th/page/index. Promote by website will enhance the opportunity of our company from buyers all over the world.sritranggroup. and up-market of rubber. The web site also increase the revenue for us.php ) .
In the future North also increase produce of rubber follow age of rubber trees.698 1.4 Sale Forecast/Profit estimate Quantity Production Thailand has produced rubber high as number one in the world. Most of the country will be planted in the southern hemisphere and the second was the Northeast. Table 3-1 Quantity Production Zone South Central and East Northeast North 1: Rai Figure 3-3 Quantity Production in Thailand Quantity 11.660 2.com/statistic/stat_index. . It has space for planting more than 2 million hectares and harvest more than 70 percent per year.209 600.799.P a g e | 62 3.978.htm ) In the North area of Thailand has project plant 1 million of rubber.339. Growth rate will increase too.578 (Source:. In Chiang Rai has just 10% tapping rubber. Thailand has rubber cultivation in regions of the country.rubberthai.
725 326.566 2005 272.850 256.470 263.055 2004 253.608 225.763 209.272 176.867 245.523 245.754 304.921 214.214 278.656 251.967 210.168 169.208 338.729 240.474 264.481 214.418 175.763 297.381 257.473 264.323 265.070 187.930 2007 264.417 207.341 203.750 278.508 Per: Ton .044 268.871 299.835 247.509 236.323 219.239 210.317 234.172 231.220 218.291 250.423 199.179 279.522 216.492 235.569 264.882 231.223 291.907 220.299 214.305 Quantity 2006 254.413 258.357 242.397 264.634 220.494 218.061 243.P a g e | 63 Table 3-2 The export value of Thailand rubber in 2003 – 2009 Month 2003 JAN FAB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC 317.536 269.795 197.162 204.593 280.647 268.370 263.172 264.925 212.119 250.473 267.341 236.068 257.991 259.846 2008 285.282 212.020 220.253 188.871 249.393 276.099 201.993 319.418 271.283 244.397 277.113 2009 225.525 269.270 251.
167 2.398 2005 938.499 68.060 2.504 488.295.848 510.470 524.193 2009 322.297 2.176 2009 24.799.574 595.109.410 1.875 2.658.003.984 1.460 11.588 245. trap and produce in 2008-2009 Plan of rubber(Rai) 2008 North Northeast Central South 600.436 349.512.135 509.948 2.700 76.559 82.237 Per: Ton Table 3-4 Compare plant.905 129.632.510 950.259 Produce(Ton) 2008 3.977.063.051 2004 920.069.283 2008 694.345 555.132.549 1.327 488.204 9.578 2.536.628.116 2009 6.698 2009 693.418 11.917 364.489 105.375 165.514.590.339.724 2.710 154.972 1.550 417.675 36.771.381 .668 1.218 690.326 1.152 197.164 72.841 569.316.726.812 2.560 9.273.151 77.503 1.209 1.762 2007 796.564 77.P a g e | 64 Table 3-3 Category of rubber export Year RSS STR Latex Mix other Total 2003 1.097 2.675.990 Trapping of rubber(Rai) 2008 14.103.309 993.644.524 26.166 198.060 2.443 60.673 2006 861.236 2.984.
62 138.co.62 RSS 5 134.thainr.000 Filed Latex 132 - Songkhia Suratthani NakornSrithammarat 137.manager.th/Local/ViewNews. Export rubber price base on foreign market both cash and future market. trap and produce in 2008-2009 (Source: RSS Cutting 127.5 134.500 120.) 70.5 RSS bubble 133.aspx?NewsID=9530000131252 and 130.php?detail=stat-thai ) Tendency rubber price per year Traded domestic rubber price will base on auction price and quantity.) Rubber market RSS 13 138.P a g e | 65 Figure 3-4 Compare plant. Table 3-5 Rubber smoked sheet Price (Baht/KG.com/th/index.49 .62 RSS 4 137.16 Quantity (KG.62 135.
com/price/eng/price_eng. Price of RSS 3 is 142 and STR 138 Baht per Kg.htm ) North of Thailand has 4% area all of plant rubber but has around 10% can trapping rubber.P a g e | 66 Table 3-6 Cash market on offer price Country Thailand Indonesia Malaysia Type RSS 3 STR 20 SIR 20 SMR 20 Shipment JAN JAN JAN JAN US CENT / KG 485 485 479.8% of north rubber export to increase total sale every year. Our company assumes 0. In rainy season is decrease sale volume because it has affected to keep latex.6 480 Table 3-7 Future Market on AFET Month Jan-11 Feb-11 Mar-11 RSS 3 139.10 (Source:. We have account receive 30% from sale forecast. Table 3-7 Volume 2011 RSS 3 STR Per: Ton 125 203 2012 137 223 2013 151 246 2014 166 270 2015 183 297 .00 141.70 142.rubberthai.
877 231.509.129 Jul 648.461 307.67 10.445.717 299.024.461 307.574.885 Feb 772.67 10.939 501.45 7.23 114.30 6.574.024.99 4.456 1.260 1.366 449.994.43 11.99 4.305 2.730.603 733.870 1.017 473.43 11.99 4.99 6.49 Year 2011(Price) Product/Month RSS (Baht) STR (Baht) Total Jan 772.197 2.967 366.497.877 284.197 299.57 7.694 Nov 997.497.221.85 11.99 7.925 1.588 449.26 184.02 11.723 2.129 Aug 648.99 6.767.305 2.260 1.045 Dec 997.44 8.603 501.85 11.14 17.925 1.85 17.389 1.461 461.02 11.991.960 1.694 Oct 972.191 461.722.478 194.908 772.168 598.44 8.53 6.509.445.30 5.870 1.478 291.P a g e | 67 Table 3-8 Sale Forecast/Profit estimate.213 772.740.885 Mar 947.960 1.717 291.870 1.57 7.908 752.465 598.237 284.588 366.45 70.024.537.129 Sep 972.343 Apr 947.723 2. 2011 Year 2011(Quantity) Product/Month RSS (Ton) STR (Ton) Total Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Total 5.237 194.85 17.389 1.887 2.227 25.191 473.461 307.43 18.478 194.673.57 7.673.939 501.017 4.221.343 May 648.85 14.223 15.537.576.478 194.024.213 7.43 18.322 1.465 733.260 1.673.260 1.322 1.870 1.450 Year 2011(Account Receivable) Product/Month RSS (Baht) STR (Baht) Total Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Total 231.57 7.045 Total 9.14 17.85 14.366 307.994.887 2.456 1.135 .673.43 11.939 752.53 4.43 11.939 501.973.129 Jun 648.576.
725 Jul 548.415.P a g e | 68 Table 3-9 Sale Forecast/Profit estimate.725 Sep 1.29 Mar 7.73 12.203.435 8.57 20.29 Apr 7.26 125.055 1.86 6.395 2.435 849.097.28 10.86 6.57 20.494.449 Nov 1.415.15 Aug 3.395 2.29 Oct 7.57 20.831.29 Total 77.097.734.116 329.558 329.314.734.734.395 2.527 867.725 Aug 548.164 520.055 1.435 849.097.57 20.57 20.73 12.291.527 867.395 2.116 329.29 Dec 7.57 20.055 1.86 6.449 May 548.449 Apr 1.73 12.395 2.395 2.94 Year 2012(Price) Product/Month RSS (Baht) STR (Baht) Total Jan 1.831.717 424.197 1.717 424.159 260.435 849.28 10.097.055 1.116 329.055 1.116 329.734.831. 2012 Year 2012(Quantity) Product/Month RSS (Ton) STR (Ton) Total Jan 7.73 12.558 164.449 Oct 1.949 28.435 424.831.717 849.29 May 3.116 164.15 Jul 3.29 Nov 7.318 520.055 1.185 849.415.734.159 520.197 1.28 10.318 520.28 10.831.73 12.57 20.734.527 867.73 12.197 1.435 849.527 867.159 260.449 Mar 1.558 164.055 1.197 1.318 520.116 3.831.57 20.395 2.435 849.449 Dec 1.734.097.86 6.73 12.318 520.318 520.116 329.116 329.055 1.449 Feb 1.73 12.29 Feb 7.395 2.097.734.097.318 520.970.415.318 260.15 Sep 7.725 Jun 548.15 Jun 3.435 849.159 260.343.545 17.097.717 424.318 5.831.348 .558 164.449 Total 10.68 202.495 Year 2012(Account Receivable) Product/Month RSS (Baht) STR (Baht) Total Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Total 329.831.
557.32 Total 84.350 934.206.189 Jun 181.028 572.32 Nov 8.028 572.907.907.114.350 934.760 1.028 572.557.760 1.98 138.078.16 Aug 4.175 467.378 Dec 362.32 May 4.378 May 181.297 Aug 603.16 Jul 4.834 3.378 Mar 362.028 572.82 22.25 6.350 934.350 934.378 Apr 362.380 953.783 .907.50 13.344 31.206.297 Jun 603.189 Jul 181.189 Aug 181.760 1.50 13.82 22.82 22.028 572.280 5.378 Nov 362.760 1.114.380 953.114.594 May 603.834 3.350 934.16 Sep 8.014 286.50 13.32 Feb 8.91 11.50 13.50 13.834 3.723.028 572.32 Apr 8.944 Year 2013(Account Receivable) Product/Month RSS (Baht) STR (Baht) Total Jan 362.594 Total 12.50 13.82 22.380 953.32 Oct 8.067.014 286.378 Total 3.760 1.907.907.557.594 Feb 1.760 1.297 Sep 1.25 6.834 3.917 1.145.206.834 3.917 1.82 22.907.594 Oct 1.378 Oct 362.907.206.175 467.834 3.014 286.594 Dec 1.82 22.297 Jul 603.028 572.014 286.907.917 1.594 Mar 1.378 Feb 362. 2013 Year 2013(Quantity) Product/Month RSS (Ton) STR (Ton) Total Jan 8.350 934.189 Sep 362.343.206.32 Dec 8.028 572.82 22.760 1.917 1.91 11.834 3.350 934.594 Nov 1.114.82 22.206.P a g e | 69 Table 3-10 Sale Forecast/Profit estimate.620.503 9.25 6.114.350 934.600 19.114.114.50 13.91 11.206.91 11.114.594 Apr 1.25 6.834 3.23 Year 2013(Price) Product/Month RSS (Baht) STR (Baht) Total Jan 1.175 467.760 1.50 13.16 Jun 4.557.32 Mar 8.380 953.175 467.206.25 223.
28 Jul 4.115 314.585 1.56 Mar 9.098.908 Aug 199.027 Aug 663.618 3.618 3.713.436 2.049.56 Year 2014(Price) Product/Month RSS (Baht) STR (Baht) Total Jan 1.027 Jun 663.054 Feb 1.585 1.28 Jun 4.098.539 Year 2014(Account Receivable) Product/Month RSS (Baht) STR (Baht) Total Jan 398.436 2.21 24.713.309 1.098.35 15.67 7.426. 2014 Year 2014(Quantity) Product/Month RSS (Ton) STR (Ton) Total Jan 9.231 629.426.585 1.098.231 629.793 513.35 15.231 629.07 245.35 15.585 1.327.054 Apr 1.027.426.309 1.60 12.049.027.426.P a g e | 70 Table 3-11 Sale Forecast/Profit estimate.231 629.67 7.56 Total 93.35 15.718 1.585 1.426.327.816 May 199.816 Total 3.816 Mar 398.436 2.426.793 513.274.027 Sep 1.436 2.027.35 15.35 15.21 24.027 Jul 663.309 1.436 2.618 3.327.027.098.56 Dec 9.982.986.585 1.56 May 4.793 513.260.049.816 Dec 398.327.436 2.027.162 .21 24.585 1.816 Feb 398.115 314.67 7.231 629.054 May 663.098.56 Nov 9.48 152.35 15.67 7.295.115 314.21 24.179 34.054 Total 13.054 Mar 1.027.60 12.618 3.327.816 Oct 398.618 3.21 24.816 Apr 398.115 314.618 3.327.618 3.908 Sep 398.718 1.308 6.327.60 12.027.436 2.231 629.054 Oct 1.278.56 Feb 9.793 513.098.28 Aug 4.908 Jul 199.309 1.56 Apr 9.436 2.327.56 Oct 9.28 Sep 9.618 3.027.21 24.231 629.816 Nov 398.60 12.718 1.21 24.35 15.426.054 Nov 1.098.21 24.360 20.054 Dec 1.718 1.713.231 629.585 1.908 Jun 199.713.426.854 10.049.
P a g e | 71
Table 3-12 Sale Forecast/Profit estimate, 2015
Year 2015(Quantity) Product/Month RSS (Ton) STR (Ton) Total Jan 10.28 16.73 27.01 Feb 10.28 16.73 27.01 Mar 10.28 16.73 27.01 Apr 10.28 16.73 27.01 May 5.14 8.36 13.51 Jun 5.14 8.36 13.51 Jul 5.14 8.36 13.51 Aug 5.14 8.36 13.51 Sep 10.28 16.73 27.01 Oct 10.28 16.73 27.01 Nov 10.28 16.73 27.01 Dec 10.28 16.73 27.01 Total 102.83 167.28 270.11
Year 2015(Price) Product/Month RSS (Baht) STR (Baht) Total Jan 1,460,180 2,308,480 3,768,659 Feb 1,460,180 2,308,480 3,768,659 Mar 1,460,180 2,308,480 3,768,659 Apr 1,460,180 2,308,480 3,768,659 May 730,090 1,154,240 1,884,330 Jun 730,090 1,154,240 1,884,330 Jul 730,090 1,154,240 1,884,330 Aug 730,090 1,154,240 1,884,330 Sep 1,460,180 2,308,480 3,768,659 Oct 1,460,180 2,308,480 3,768,659 Nov 1,460,180 2,308,480 3,768,659 Dec 1,460,180 2,308,480 3,768,659 Total 14,601,796 23,084,797 37,686,593
Year 2015(Account Receivable) Product/Month RSS (Baht) STR (Baht) Total Jan 438,054 692,544 1,130,598 Feb 438,054 692,544 1,130,598 Mar 438,054 692,544 1,130,598 Apr 438,054 692,544 1,130,598 May 219,027 346,272 565,299 Jun 219,027 346,272 565,299 Jul 219,027 346,272 565,299 Aug 219,027 346,272 565,299 Sep 438,054 692,544 1,130,598 Oct 438,054 692,544 1,130,598 Nov 438,054 692,544 1,130,598 Dec 438,054 692,544 1,130,598 Total 4,380,539 6,925,439 11,305,978
P a g e | 72
Table 3-13 Sale Forecast/Profit estimate, 2016
Year 2016(Account Receivable) Product/Month RSS (Baht) STR (Baht) Total Jan 1,460,180 2,308,480 3,768,659 Feb 1,460,180 2,308,480 3,768,659 Mar 1,460,180 2,308,480 3,768,659 Apr 0 0 0 May 0 0 0 Jun 0 0 0 Jul 0 0 0 Aug 0 0 0 Sep 0 0 0 Oct 0 0 0 Nov 0 0 0 Dec 0 0 0 Total 4,380,539 6,925,439 11,305,978
P a g e | 73
3.5
Marketing Expend Budget
We anticipate the activity expenses mostly for covering the cost of additional staff to help facilitate the additional requirements for marketing activities. Table 3-14
Marketing Expense Budget, 2011 For year 2011 Marketing Expense Budget :
Item
Advertising Web marketing Production Web development Web ads/e-newsletters PR/Events/Promotion Trade show/Events Total
Jan
Feb
Mar Apr May
Jun
Jul
Aug
Sep
Oct
Nov Dec
Totals
1,000
1,000
1,000
1,000
1,000
1,000
1,000
7,000
500 200 200
500 400
3,000 0 0 0 3000 0 1000 1000
3,000 4000 1200 1000 1200
3,000 4500
9000 16,900
200 .000 4000 9000 13.000 200 0 200 4000 200 0 200 3. 2012 For year 2012 Marketing Expense Budget : Item Advertising Web marketing Production Web development Web ads/e-newsletters PR/Events/Promotion Trade show/Events Total Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Totals 500 500 500 1500 500 200 200 200 200 500 200 200 500 1500 1200 3.000 4000 200 0 200 3.P a g e | 74 Table 3-15 Marketing Expense Budget.
2013 For year 2013 Marketing Expense Budget : Item Advertising Web marketing Production Web development Web ads/e-newsletters PR/Events/Promotion Trade show/Events Total Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Totals 500 500 500 1.000 3500 9.500 500 200 200 200 200 500 200 200 500 2.000 3500 200 0 200 3.200 .700 3.P a g e | 75 Table 3-16 Marketing Expense Budget.000 200 0 200 3500 200 0 200 3.000 13.
000 13. 2014 For year 2014 Marketing Expense Budget : Item Advertising Web marketing Production Web development Web ads/e-newsletters PR/Events/Promotion Trade show/Events Total Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Totals 500 500 500 1.P a g e | 76 Table 3-17 Marketing Expense Budget.000 3500 9.000 200 0 200 3500 200 0 200 3.500 500 200 200 200 200 500 200 200 500 2.000 3500 200 0 200 3.700 3.200 .
000 3500 200 0 200 3.000 3500 13.000 200 0 200 3500 200 0 200 3.000 9.700 3.200 . 2015 For year 2015 Marketing Expense Budget : Item Advertising Web marketing Production Web development Web ads/e-newsletters PR/Events/Promotion Trade show/Events Total Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Totals 500 500 500 1.500 500 200 200 200 200 500 200 200 500 2.P a g e | 77 Table 3-18 Marketing Expense Budget.
P a g e | 78 Chapter 4 Technical Operation Feasibility Study .
1 Rubber Smoked Sheets (RSS) The rubber sheet made by applying more latex split second to capture the dirt and then with Ford Mick acid or acetic c. The screening must be highly skilled.1 Product Characteristic Rubber industry. Rubber Smoked Sheet. which can be processed to a 2-way. Class that make rubber smoked a 5-layer rubber layer is considered low. These rubber used in the manufacture of finished products such as vehicle tires include tire bicycle tire motorcycle tire rubber gloves. Rubber Smoked Sheet 1 Rubber Smoked Sheet 2 Rubber Smoked Sheet 3. because the quality of rubber smoked sheets will be compared to the bar in the rubber. Rubber Smoked Sheet 5. Rubber Smoked Sheet 4. The drying air temperature 45-65 ° C takes about 3-5days waiting for distribution packaging.. There are 2 mainly type of product to export in our company.1. By accessing hospital smoked Temperature of 50-60 degrees Celsius takes 4-10 days and then classified visually Packaging. and then to dry in the shade will be raw rubber sheets (Unsmoked sheet. rubber processing industry is initially brought tapping latex from rubber trees that are preserved in reasonable condition and ease of its use as a raw material in the manufacture of rubber products. condoms and rubber band rubber tubing. USS).So. . 2-3 mm thick. etc. They were made with massage and rolling machine rolling tire and rubber. Screening layer of rubber and screening rubber floor that day. A rubber sheet dry. 4. It will be your eyes and help to predict layer of rubber which will be standard.P a g e | 79 Technical Operation Feasibility Study 4.
Bubbles and dirt. .P a g e | 80 Standard rubber smoked sheets of Thailand Remove the rubber layer 3 on the criteria for judging. The rubber smoked this class is a quality equal Rubber TTR 20 quality rubber smoke better is considered a rubber on floor 1 or 2. 4. smoked cooked consistently good cohesive flexible points and no points other contaminants blamed as much as undesirable is a total of not more than 10 percent of the pages (like quality TTR 20). 1. 3. The use of water and sulfuric acid is part Considerations by separation of the rubber on its export standards following the Association of Traders rubber. The language of the selected layer of rubber called a point and points. Rubber Smoked Sheet rubber layer 3 is dried. The color and consistency of the color red does not mold. 2. between countries are as follows. No impurities. but if the quality worse than I consider it to be rubber.
. .1. . .without any blame.Clean 3.No contamination .without any blame. 2.Clean . . Have a little rust mold or dry wrapping a sheet of rubber.2 Rubber Smoked Sheets 2 (RSS2) 1. The properties of rubber.There is no point inflation .P a g e | 81 There are 3 types of Rubber Smoked Sheets (RSS) which are: 4. .A pin head size bubbles scattered around the plate.The spot of a small bark.no gravel .hard.Dry .Dry. . 2. but not more than 5% of the sample detected. Blamed acceptable . 3.There is no point inflation .1 Rubber Smoked Sheets 1 (RSS1) 1. The properties of rubber. .No contamination . hard. Price: 142 baht/kg 4. Blamed acceptable.1. Do not have mold or mold a little dry only the surface of the rubber sheet wrapping.no rust.no gravel .The spot of a small bark.1.1. . .A small bubble.
The properties of rubber.P a g e | 82 Price: 142 baht/kg 4.hard. Have a little rust. . 2.blamed acceptable.No contaminants . Price: 142 baht/kg . Mold or dry wrapping a sheet of rubber. . .1. but not more than 10% of the sample detected.Dry . .Have little spots .no gravel .There is no point inflation .3 Rubber Smoked Sheets 3 (RSS3) 1.a spot of little bark.1.A small bubble.
Is dried and then pressed into rectangular bar size 33. index of solid rubber. then dried and pressed into bar size 33. The waste tires must be included in the Tire and cut tank cleaning Honor and total iron bucket again into the machine through a crepe. Then small sub-rubber granules Rubber. Rubber Trade of Thailand. Amount of gel rubber outer layer of rubber STR 5L and STR XL stored for one year. viscosity etc.2 Block Rubber Materials was use in the production of block rubber and latex is required to build up before and the rubber handle.Use a rubber handle and then. Small rubber into be small pieces. of the rubber layer was different. and expected due to the oxidation of the rubber outer layer of rubber pieces. For raw rubber sheets can be cut and pressed into ingots and then bake it. were lower than in other parts of rubber.Use latex done by applying latex poured in the tank.3 kg. Because the outer layer of rubber is easy to abuse by oxygen and . such as the waste of raw rubber sheet rubber bottom cup The production process is different.3 kg . including the Tire and Rubber coagulation and cut into cubes. . including three STR 5L STR XL and STR CV60 is divided into three parts outside the central part in the three rubber samples revealed that the variance of STR 5L with the properties of processing most Examples of such properties of the process index oxidation.P a g e | 83 4. The food took over crepe.1.
Tire spins separation. While made of rubber and rubber to eliminate fat.1. Phil K New reaction sponsor of NRL action was done by changing variables as follows. the reaction of nitrogen rubber decreased significantly during the start of the reaction and gradually Decreased slowly. Rubber from latex. the concentration of sodium hydroxide and reaction time to get optimum conditions for preparing high-purity rubber. The results do try to express that possibly due to the slow sample degradation. In contrast. Assumed that due to chemical bonding.1 STR 5L Price: 138 baht/kg .2.Nitrogen content of the rubber is reduced as much as 0. Temperature change of the molecular motion (glass transition temperature) of the gel is higher than the soluble or the soul (sol fraction) of the structure and the structure branches of natural rubber during storage. After reaction for three to seven hours for every The concentration of base. The temperature of the reaction. Between functional groups active among the fatty chain length of phospholipid at the end of four lipid molecules of the rubber. Under conditions is low humidity. Of protein on the surface of rubber particles or May be due to the difficulty in removing the protein degradation and a very low volume. STR CV60 rubber gel content is quite constant in all parts of rubber from spinning tires and rubber separation of water through the removal of protein coagulation index of the rubber during storage increased significantly. From the rubber by centrifugation: 4. protein and fat removed and the coagulation index during storage is almost constant.P a g e | 84 ozone. 1-7 hours.02% after the reaction sponsor Phil K New Nation that the concentration of base was 7%. Rubber was removed from the protein structure of the resulting gels boosted after a stronger reaction. the reaction temperature of 70 ° C.
1.1.3 STR CV60 Price: 138 baht/kg (Source. .co.P a g e | 85 4.2 STR XL Price: 138 baht/kg 4.com ) .
300.2 2.300.818.019.800 1.000 Apr 44 75 3.268.000 Dec 40 75 3.468.000 May 22 98.000 Nov 44 75 3.300.000 Apr 31 75 2.300.121.700.000 Year 2012 Jun Jul 18 105 1.222.400 May 24 98.875.000 Year 2014 Jun Jul 22 22 105 101 2.000 Apr 40 75 3.600.300.310.000 Mar 31 75 2.000 Feb 48 75 3.700.600.376.000.000 2.000 Sep 32 75 2.000.062.600.944.000.600.000 2.000.890.475.020.520.325.000 Jan 44 75 3.600.000 Jan 36 75 2.600.964.600 Total 397 32.400.000 Feb 44 75 3. .000 Sep 44 75 3.160.692.300.000 Dec 44 75 3.200 May 18 98.000 Total 440 35.000 Oct 40 75 3.000 Aug 22 108 2. Then result to the quality has high demand.000.000 Sep 48 75 3.000 Mar 48 75 3.000 Aug 21 108 2.000 Nov 48 75 3.600.000 Feb 36 75 2.100.000 Sep 40 75 3.2 2.000 Nov 33 75 2. The price that following the demand.424.000.700.000 Aug 18 101 18 108 1.000 Mar 40 75 3.400.300.2 Cost of good Table 4-1 Cost of goods Sold Cost of goods sold Product/Month cost of latex (Ton ) Price (Baht/Ton) Total Product/Month Cost of latex(Ton) Price (Baht/Ton) Total Product/Month Cost of latex(Ton) Price (Baht/Ton) Total Product/Month Cost of latex(Ton) Price (Baht/Ton) Total Product/Month Cost of latex(Ton) Price (Baht/Ton) Total Jan 25 75 1.000 Jan 40 75 3.356.P a g e | 86 4.000 Jan 48 75 3.205.244.806.000 Sep 36 75 2.200 Total 361 29.000 2.160.000 Apr 48 75 3.2 1.475.767.000 Feb 25 75 1.000 Oct 32 75 2.000 May 21 98.000 Apr 36 75 2.000 Nov 36 75 2.000 Aug 24 108 2.000 Dec 48 75 3.000 Oct 48 75 3.000 Dec 33 75 2.2 1.000 Dec 36 75 2.000 Year 2015 Jun Jul 24 24 105 101 2.000 Nov 40 75 3.000.2 2.700.300.700.000 Aug 20 108 2.700.000 Total 328 26.000.400 Total 480 38.000 Feb 40 75 3.600 May 20 98.875.000 Oct 44 75 3.000 Oct 36 75 2.000 Mar 36 75 2.000 * This month (May-August) have the high price because this time is the rainy season.000 Mar 44 75 3.800 Year 2011 Jun Jul 21 21 105 101 2.325.000 2.000 Year 2013 Jun Jul 20 20 105 101 2.700.700.600.592.
07 101.38 101.3 Pricing product At office of central rubber market Songkhla Suratthani Field Field Latex Latex Rubber scraps (factory) Local (factory) 89.8 101.34 94.58 86.1 93.82 116.43 115.85 106.4 98.87 98.77 98.27 Nakhorn.88 97.08 102.18 93.93 97.47 82. (Source: 116.com/price/price_index.5 115.2 114.Rubber Market because the Southern rubber market is the big market.sritammarat Field Latex Local (factory) 90.44 104.42 83. ****The reason of the company brings a data office of Songkhla Central Rubber the stability of price.91 88. 104.13 115.93 96.56 95 101.87 110.08 101.19 103.P a g e | 87 4.44 110.09 Table 4-2 Pricing Product Our price cost.89 107.3 87 94.93 93.75 99.63 100.78 98.44 98.93 93.59 107.php.01 104.02 102.) .98 91.45 114.01 96.rubberthai.93 98. The company cannot fixed the price in the future because have change on every time.15 99.17 Year 2010 January February March April May June July August September October November December Local 91.5 102.75 90.76 87.36 98.83 97.8 100. In Chiang rai it not has the stability of price.87 102.58 80.21 85.04 81.34 97.53 96.99 109. Which this price medium Using the cost of local price to changing up and down constantly. Our price is 93 Baht.95 92.4 84.33 96.88 99.33 98.1 107.85 104.htm. we use the local price.35 97.68 103.08 97.5 107.8 97.71 98. Which we use the price to stability with the real price.68 104.51 99.88 100.08 85.04 100.th/menu5.77 98.
000 1.000 2.000 1.300 Total 223.344 Year 2012 Jun 10.000 1.15 80 1.674.240 Feb 24.000 982.841.16 80 1.522.674.080.314.01 75 1.56 75 1.000 1.664 Feb 27.000 1.000 811.928 Aug 12.99 80 1.240 Oct 24.000 959.000 1.000 1.344 Sep 17.000 1.412 .443 Jul 10.15 80 1.036 Oct 22.674.000 1.036 Mar 22.45 75 1.28 80 1.344 May 10.664 Apr 27.000 1.000 1.56 75 1.29 75 1.383.28 80 1.32 75 1.349.000 1.56 75 1.349.344 Aug 11.221 Aug 13.56 75 1.025.000 1.99 80 1.841.443 Jun 11.32 75 1.000 982.000 892.000 1.000 982.830 Dec 20.99 75 1.080.664 Dec 27.000 1.078 Oct 17.51 80 1.841.29 75 1.000 1.29 75 1.15 80 1.664 Sep 27.000 892.28 80 1.000 892.344 Jan 20.000 811.000 2.036 Dec 22.15 80 1.830 Mar 17.000 1.025.928 Jul 12.669 Dec 18.32 75 1.443 Sep 20.630 Total 245.753 May 11.841.240 Jan 24.841.000 2.000 892.240 Sep 24.753 Year 2013 Jun 11.522.025.664 Oct 27.000 1.51 80 1.522.94 Jul 11.000 2.01 75 1.025.221 May 13.56 18.01 75 1.025.11 20.000 1.753 Jul 11.000 1.528.01 75 1.841.664 Mar 27.000 2.000 1.99 80 1.486 Apr 20.56 75 1.344 Feb 20.000 1.036 Feb 22.000 959.45 75 1.32 75 1.000 1.29 75 1.56 75 1.01 75 1.000 1.674.23 16.965.01 75 1.928 May 12.528 15.036 Sep 22.423.000 982.01 75 1.000 1.314.30 75 1.664 Jan 27.000 1.000 1.522.16 80 1.01 75 1.240 Dec 24.53 75 1.928 Year 2014 Jun 12.000 811.830 Feb 14.080.28 80 1.16 80 1.32 75 1.000 1.000 2.221 Year 2015 Jun 13.078 Nov 18.56 75 1.29 75 1.000 811.221 Jul 13.076.025.99 75 1.000 2.000 1.29 75 1.000 1.669 Total 184.000 1.000 959.30 75 1.486 Mar 20.522.830 Nov 20.32 75 1.830 Oct 20.674.53 75 1.240 Mar 24.193 Total 270.025.753 Aug 11.32 75 1.036 Nov 22.674.674.443 Aug 10.29 75 1.674.51 80 1.32 75 1.000 1.49 14.522.P a g e | 88 Table 4-3 Pricing Product Year 2011 Product/Month Cost of material (ton) Price (Baht) Total Product/Month Cost of material (ton) Price (Baht) Total Product/Month Cost of material (ton) Price (Baht) Total Product/Month Cost of material (ton) Price (Baht) Total Product/Month Cost of material (ton) Price (Baht) Total Jan 14.841.383.072.99 80 1.664 Nov 27.51 80 1.080.000 1.240 Apr 24.000 1.56 75 1.036 Jan 22.830 May 11.000 2.29 75 1.830 Total 202.240 Nov 24.16 80 1.000 1.000 959.072.841.036 Apr 22.025.830 Apr 17.522.000 1.522.662.
000 Baht KVA Insurance Cost = Guarantee for debt power.000 Baht More than 200 A equal to 40.000 Baht High voltage meter.htm) . We estimate electric power in the factory.co.000 Baht More than 30 A equal to 20. System under 69 KVA Individual transformer.000 Baht 108.000 Baht 4 Baht per KVA but Under 50.th/th/services/services_fee_rates. We use system under 69 KVA**** Configuration Cost (Under 200 A) Inspection Cost (More than 30 A) Insurance Cost (assume 10 KVA) Total Cost per transformers Total Cost of fees for electricity 30.pea. Configuration Cost = The cost of providing meter installation and operation.000 Baht 4. Individual transformer think 4 Baht per KVA System more than 69 10.000 Baht = The cost of investment in the power transformer to provide power = The cost of send someone to check the wiring already in ther user’s (Source:. ****2 Transformers (1 KVA -1 MVA). Average Cost user that Light.1 Cost of request Electric and Water Electric Request the power from Provincial electricity authority.4 Preopening cost 4.000 Baht 20. Inspection Cost files. Do not think the average. EXHIBIT 4-1 The Free rate for electricity Average Cost(Baht) Insurance Cost (Baht) Configuration Inspection Cost (Baht) Cost (Baht) Under 200 A equal to 30.P a g e | 89 4. Request 2 transformers (1 KVA -1 MVA).000 Baht 54.000 Baht Under 30 A equal to 15.4. and officer.
From water meters to connection the pipe.500 2.000 15. User will receive a full deposit returned upon termination of water and no debt outstanding water bill. We estimate electric power in the factory. Deposit Cost = the applicant must pay for PWA on request install to be use in the survey location and estimating the cost of installation. When the PWA receives labor and equipment supply cost for installation already. plumbing and other devices that use to installing. .000 10.000 10.600 4.700 Total 4. EXHIBIT 4-2 The Free rate for using water Water Meter Size(Inch) ½ ¾ 1 1½ 2 2½ 3 4 6 8 Deposit Cost (Baht) Not collected Not collected 1. water meters cost.P a g e | 90 Water Request the water from the Provincial Waterworks Authority.500 4.000 Labor and Equipment Cost (Baht) 3.000 20. Request 1 water meters. PWA will return the deposit cost immediately.000 1.100 5. About installing water meters is not over Diameter ¾ inches and the distance from the main water distribution pipes less than 10 meters will pay the price including VAT already.000 4.700 Expense estimates. Labor and Equipment Cost = There are labor cost. Deducted by estimate cost that user paid already.500 3.000 20.000 5. This doesn’t include pipe and equipment after the water meters that applicant must be due by them self.000 Insurance Cost (Baht) 500 1.000 4.000 1.000 30. Insurance = PWA charged according to size water meters to secure the payment of water bill each month.000 21. and officer.
000 Baht each set.000 Baht 10.000.000. The rate is following Registration Rate from Department of Business Development.th/mainsite/index.000 Baht.500 Baht ******* Total Cost of request Electric and Water 132.000 Baht Registered capital of 100.co.000 baht equivalent).000 5.3 and No.pwa.000 500 250.P a g e | 91 ****1 Water Meters size 3 inch**** Deposit Cost Insurance Cost Labor and Equipment Cost Total Cost of frees for using water 5.000 Baht : According to No.000 Baht 110. Capital more than 50.4. Registered prospectus Incorporated company Total 10.go.dbd.000 Baht each set.000 .000 Baht 100.500 Baht ******** (Source:. EXHIBIT 4-3 The company limited registration Fee rate Description Registered prospectus: Capital not exceeding 1.500 Baht 24. (Fraction of the 100.000.000 Baht equivalent).4 of ministerial regulations The capital of all partners combined approximately 20.2 Prepare to be company limited For our business the first step we need to have a Memorandum.000.000 Baht Incorporated company: Capital not exceeding 1.000 Baht to 100.000 Baht Registered capital of 100. (Fraction of the 100.php?id=1638 ) Baht 500 50 25.000.th/service/newuser.html) 4.000 Baht 9. Capital more than 50.000 Baht (Source: Baht to 100.
The mortgage (If mortgages from financial institutions) Stamp Duty (Pay one between stamp duty or specific business) Specific business Duty (Don’t pay if holding more than five years) 1% of price (no less than at market prices commerce) 2% of market prices commerce or price of sell up on what price is higher 1% of value of the mortgages 200 Baht for 1 Baht of Stamp Duty(0.th/land-info-top-3.4.4.000 Baht 64.php?lay=show&ac=article&Id=538974919&Nty pe=19) 4.000 Baht 30.3 Fees for the establishment of the factory Following the factory act.450. 1992 Application for permit Permit Substitutes permit Fees factory operation (per year) Total 100 Baht 100.50%) following selling price but not less than market prices commerce) 3.000 Baht*** Corporate income tax Fee legal action The mortgage Stamp Duty Total Cost of Land Tax 64.co.500 Baht 32.4 Land Tax EXHIBIT 4-4 Charge at the Land Office if the Registrar Charges at the Land Office if the Registrar.000 Baht 131.3% of selling price but not less than market prices commerce) ***The cost of land is 6.500 Baht 129.land.com/index.thailandlawyercenter.asp) .250 Baht 290.250 Baht (Source: Baht (Source: Baht 1.P a g e | 92 4. Corporate income tax (withholding) Fee legal action (transfer fee).
No Thai characters .P a g e | 93 4.2.4.go.pdf) .5 Tax labels (per 500 square centimeters) EXHIBIT 4-5 Rate of Tax labels Style Thai characters are.000 square centimeters (120.thailocaladmin. Label changes to the label area of an image or mark some of the signs. Signs following .3 The case may be and pay especially the amount increased.000/500)*20 = 4. Already paid interest tax.800 Baht (Source:. Thai characters mixed with the foreign language/images/other marks. of Factory label 120.Have some Thai characters or All of Thai Character below or under foreign language. Label is under 200 Baht to pay 200 Baht instead 200 Baht Baht 3 Baht 20 Baht 40 Baht Size 4*3 M. which cause the signs and banners to increase the tax rate by 1.
000 Baht (Source: 24.go. 2004 Patent inventions Patent or petty patent Total 500 Baht 500 Baht 1.000 701. Following Ministerial on fees and fee waiver for a patent or petty patent Act.4.6 Trademark registration fee.000 131.P a g e | 94 4.th/ipthailand/index.650 .250 4.800 1.500 110.ipthailand.7 Total Cost of Pre Opening Cost Table 4-4 Total Cost of Pre Opening Cost Pre Opening Cost Cost of request Electric and Water Electric Water Prepare to be the Company limited Fees for the establishment of the factory Fees for requesting permission of the foreign business for investor Land Tax Tax labels Trademark registration fee Total Baht 108.100 32.php?option=com_content&task=view& id=817&Itemid=303) 4.4.000 290.
5.5. He sell for 600. Sainatee who is the owner by phone number 085-6664996.2 Building Thai-North Rubber will hire the constructer to design and advice us to build the factory. We choose to contract with Mr.com_fireboard /Itemid.3 Acers. (Source: baht.view/id.56/func. This land is located near the Chianhkhong’s friendship bridge 4th only 1-2 kilometers.com/component/option.000. . By refer the information from Department of Industrial Promotion.5 Operating investment cost /Operating expense 4.3 Acers (10Rai 3Ngan).000 Baht. He calculates for our investment 7.P a g e | 95 4.We will pay for land 6.000 Baht per Rai that all of we buy equal to 4.30261/) 4.450.68072/catid.baanok. And we contract with Mr.1 Land We decision to buy the land all of 4. Suvin who is the professional.
contact with customer. .3 Features and Dimension All of our areas are divided into two zones.5.1 Manufacturer zone Our production is provided into three parts which are Rubber Smoked Sheet (RSS) products.5.3. EXHIBIT 4-6 Total Areas of Company 4. We allocate to each zone because of comfortable for easy to service. there are the zone of manufacture and administrative zone. control and operation in production. Block Rubber (STR) products and Rubber Testing Lab. In all of Rubber Smoked Sheet (RSS) Product and Block rubber (STR) product are related in production together which makes we have production in the same area into this zone and one part for Lab testing.P a g e | 96 4.
5. 4. 6. Latex tank Latex bin Cutting machine Rubber bin Bar presses Crepe rubber machine 7. 3. 10. 13.P a g e | 97 EXHIBIT 4-7 Manufacturer Zone 1. 2. 11. 12. Vinyl rubber Bin to clean rubber Rubber rolling machine Gutter cleaning rubber Water tank Eauong mortar . 14.
And we have 3 people are lab staff and 2 people are maintenances.000 1 200.000 2 60.4 Operating investment cost In the production.060 Baht.800 Baht. . Item Picture Price (Baht) 14. All of this we can calculate the number of money with is 446.500 2 37. So.068.800 1 Eauong mortar as 50 pieces 4 2 Rubber rolling machine 8.000 5 Bar presses 200.500 8 68.P a g e | 98 4.diw. we use many of merchandise to take products.000 6 Cutting machine 25.000 1 25.th/I_Standard/Web/pane_files/Industry12. EXHIBIT 4-8 Merchandise Cost No.go.com/index.php?langtype=th&pageid=th_40 3 Crepe rubber machine 30.000 4 Vinyl rubber 18.yongfongthai.200 Amount Total (Baht) 56. we take money for their about 1.800 (Source:) Within the Lab room and production process are have many of equipment to concern.000 Total 446.
560** 156. In 5 years we will take for the set of test substance solution ZnO Easy Kit 1.psu. Laboratory state 100 1.900 8 Printer 1.000 Baht to pay for **we take 26 days for working in month. Item Picture Amount 1 Set of test substance solution TMTD Easy Kit Set of test substance solution ZnO Easy Kit.infinity-office.th/node/947 .690 6 Desktop PC(Lab staff 3) Air condition 27.900 1 13.000 1 25. 7 13.000 Baht to pay for (Source: sets.080*** 604.345 2 6.300 4 Desk set 3 seats(Lab staff 3) 25.ac.900 3 83.300 1 20. Firewood per month 2 10.com .560 sets.068.670 9.techno.560* 156.060 *we take 26 days for working in month.com) .800*** Total 1. a g e | 99 EXHIBIT 4-9 Equipments within Lab room Price (Baht) Total (Baht) No. * 2 100 1.670 1 1.kssfurniture.000 5 Desk 3.com . we will use 156. In 5 years we will take for the set of test substance solution TMTD Easy Kit 1. we will use 156.000** 3 20.
P a g e | 100 4.000 Baht 1. in 5 years we will pay for them which 7. They are working 8 hours in one day and take with 26 day per months.000Baht per year.5. Water Fee and From the information in Department of Industrial Promotion. Minimum wage in Chiangrai 166 Baht/Day or 4. Lab staff salary 2.000 per Month (Source: Department of Industrial Promotion) Worker Salary Our manufactory has workers with 30 people in every line of production.com/news/news_thailand_detail.768.aspx?c=2&d=117291&p=4) Electricity Fee. Maintenance staff salary 15.000Bah per year and Water free around 60.140. So.000 Baht×2 or 24.000 per Month 12.5 Production cost Lab Staff and Maintenance Staff Salary In the Lab room. (Source: Department of Industrial Promotion) . we can estimate the cost of electricity free around 120. We will pay money for them with 26 days working per months for 5 years.316 Baht/Month (Source: Baht 1. So. we will take money for all of salary in 5 years about 4.000 Baht×3 or 45.ch7. we have Lab staff 3 people and 2 of Maintenance staff.
000 Baht per year and cost of maintenance machine around 168. we can estimate the cost of maintenance building around 540.052Baht per year.P a g e | 101 Expense of maintenance building and machine From the information in Department of Industrial Promotion. (Source: Department of Industrial Promotion) Lubricant expense From the information in Department of Industrial Promotion.000 Baht per year. we can estimate the cost of maintenance building around 60. .
480 10.000 540.000 129.000 18.000 Nov 45.480 10.480 10.000 18.808 .000 Sep 45.000 250.000 24.000 18.000 129.484 14.000 24.000 540.000 Apr 45.000 60.480 10.004 5.000 5.000 5.000 250.484 Totals 540.000 24.000 250.000 Jul 45.000 129.004 5.553.760 120.000 24.000 250.004 5.000 129.000 129.484 14.000 250.000 5.P a g e | 102 Table 4-5 Operating expense in year 2011 Operating cost : Baht Expense Lab staff salary Maintenance salary Firewood Worker salary Electricity fee Water fee Maintenance building Maintenance machine Lubricant Total 14.004 5.000 Dec 45.000 5.545.000 3.004 5.048 60.000 24.000 129.000 250.000 288.000 Aug 45.000 5.000 24.000 129.484 14.484 14.000 24.000 250.000 18.000 250.480 10.000 790.000 216.480 10.000 24.000 5.480 10.000 5.000 5.000 5.000 129.000 250.000 Jun 45.480 10.000 129.484 14.000 18.480 10.000 24.000 18.000 24.484 14.000 18.000 250.004 5.000 18.484 14.004 5.000 24.000 250.000 1.000 129.000 5.484 14.484 Jan 45.000 168.000 Mar 45.000 May 45.000 14.480 10.004 5.480 10.000 Oct 45.000 18.000 Feb 45.000 5.004 5.000 18.000 5.484 14.000 18.000 18.000 129.004 5.004 5.480 10.484 14.004 5.000 129.000 24.
000 540.564 Totals 540.048 60.000 24.004 5.000 24.000 5.000 242.000 5.480 10.080 129.480 10.000 242.080 129.760 120.000 24.564 14.480 10.000 24.080 129.000 10.000 24.768 .553.004 5.080 129.000 Dec 45.004 5.480 10.000 10.000 Feb 45.000 242.000 24.000 10.000 5.480 10.080 129.004 5.000 Jun 45.080 129.004 5.080 129.564 14.000 Sep 45.564 14.004 5.000 242.000 24.000 242.080 129.000 5.000 Aug 45.000 10.000 242.000 Mar 45.000 242.000 242.564 14.000 120.P a g e | 103 Table 4-6 Operating expense in year 2012 Operating cost : Baht Expense Lab staff salary Maintenance salary Firewood Worker salary Electricity fee Water fee Maintenance building Maintenance machine Lubricant Total 14.000 10.000 10.000 5.480 10.000 10.450.480 10.000 10.004 5.480 10.004 5.080 129.000 242.000 60.000 5.000 5.004 5.000 242.004 5.000 24.480 10.000 5.000 10.000 168.000 May 45.000 24.000 14.080 129.000 Nov 45.564 Jan 45.000 5.000 Apr 45.000 24.564 14.000 540.000 3.000 24.480 10.564 14.000 5.480 10.564 14.960 1.080 129.000 Jul 45.080 129.004 5.000 242.000 24.000 5.564 14.480 10.000 288.004 5.564 14.000 5.000 10.000 10.000 10.000 782.564 14.000 Oct 45.
000 Mar 45.480 10.000 242.000 24.000 5.000 5.480 10.480 10.000 10.080 129.000 242.000 24.004 5.000 5.000 24.000 Aug 45.000 24.000 10.000 540.000 242.000 10.450.000 288.000 5.004 5.000 5.004 5.000 May 45.000 24.080 129.000 540.480 10.080 129.000 242.564 14.004 5.000 3.000 10.553.004 5.480 10.000 242.564 .000 10.080 129.048 60.080 129.480 10.000 24.000 Dec 45.000 Oct 45.000 242.000 Feb 45.000 168.000 242.000 24.000 Sep 45.564 14.000 Jul 45.004 5.000 242.080 129.080 129.564 14.480 10.000 5.P a g e | 104 Table 4-7 Operating expense in year 2013 Operating cost : Baht Expense Lab staff salary Maintenance salary Firewood Worker salary Electricity fee Water fee Maintenance building Maintenance machine Lubricant Total Jan 45.000 24.004 5.000 242.000 5.960 1.564 14.004 5.480 10.480 10.000 10.000 5.000 60.000 10.000 242.000 Apr 45.000 24.000 5.480 10.768 14.080 129.000 242.000 5.080 129.564 14.760 120.564 14.080 129.000 24.004 5.000 10.004 5.480 10.000 782.004 5.000 Nov 45.000 5.000 10.564 14.564 14.000 24.000 24.004 5.080 129.000 5.000 Totals 540.080 129.000 10.564 14.000 10.000 Jun 45.564 14.000 120.564 14.480 10.000 10.
004 5.000 5.000 10.080 129.000 Feb 45.080 129.004 5.564 14.000 May 45.004 5.000 10.000 24.480 10.768 .000 242.000 24.000 242.000 24.000 5.000 10.080 129.000 24.480 10.564 14.000 10.000 242.450.564 Jan 45.000 540.564 14.080 129.000 5.000 242.564 14.564 14.480 10.004 5.P a g e | 105 Table 4-8 Operating expense in year 2014 Operating cost : Baht Expense Lab staff salary Maintenance salary Firewood Worker salary Electricity fee Water fee Maintenance building Maintenance machine Lubricant Total 14.080 129.564 Totals 540.564 14.000 782.000 242.000 242.000 24.000 5.480 10.564 14.960 1.000 10.080 129.000 24.480 10.000 Dec 45.000 10.004 5.000 14.000 Sep 45.760 120.000 5.000 120.004 5.048 60.480 10.080 129.000 242.004 5.080 129.564 14.000 24.000 Nov 45.000 5.004 5.000 24.000 242.004 5.000 10.004 5.480 10.080 129.080 129.000 Jun 45.000 60.000 5.000 5.564 14.000 24.000 3.000 10.564 14.480 10.000 540.000 Aug 45.000 10.000 288.000 24.000 Jul 45.000 10.000 5.000 242.000 Oct 45.080 129.000 24.000 Apr 45.000 5.000 242.080 129.000 5.000 242.000 10.000 24.000 10.480 10.480 10.000 Mar 45.553.004 5.000 5.480 10.004 5.000 168.480 10.
000 5.480 10.080 129.564 14.000 10.480 10.000 5.000 24.480 10.080 129.000 5.000 242.000 10.564 14.564 14.000 10.000 5.553.000 242.000 Apr 45.004 5.004 5.768 .564 14.000 242.564 14.000 24.000 540.564 Totals 540.000 10.000 242.000 5.000 10.004 5.000 24.000 5.000 24.000 24.564 14.004 5.000 Nov 45.000 10.004 5.000 Dec 45.000 Mar 45.000 60.000 24.000 242.004 5.080 129.450.000 120.080 129.564 14.000 24.000 5.564 14.000 Aug 45.480 10.480 10.000 540.080 129.000 May 45.004 5.000 24.048 60.564 14.000 288.000 5.000 14.080 129.080 129.000 10.000 Jul 45.080 129.480 10.960 1.000 5.000 5.000 Feb 45.480 10.004 5.080 129.P a g e | 106 Table 4-9 Operating expense in year 2015 Operating cost : Baht Expense Lab staff salary Maintenance salary Firewood Worker salary Electricity fee Water fee Maintenance building Maintenance machine Lubricant Total 14.000 10.000 242.480 10.480 10.000 3.480 10.000 242.000 242.000 24.004 5.000 782.000 242.564 14.000 24.000 Oct 45.000 5.000 5.480 10.000 10.000 168.000 Sep 45.004 5.080 129.000 10.480 10.000 Jun 45.000 242.000 10.000 24.000 24.564 Jan 45.080 129.004 5.000 242.000 10.080 129.004 5.760 120.
It is including Latex. which party will pay on the transportation cost. Inbound: In domestic.6.P a g e | 107 4. It up on the agreement between the supplier and manufacture.1 Logistic Management We are also divided over the transport into two periods are inbound logistic and out bound logistics 1. . start from the supplier around Chiang Rai send the raw material to us.6 Logistics and Transportation cost 4.
Our company delivers when the goods pass the ship’s rail at the named port of shipment. Chiang Khong Port is situated on the bank of Mekong River. After that the Agent will inform to port know. (Source:. When the full amount and then close. This means that the customer has to bear all costs and risks of loss or damage to the goods from that point and responsible for all the costs incurred after the cargo has been loaded on board.port. Out bound: Our Company sends finished goods to customers in China. There are 3 group each group have 15 people for packing product in to container frame roof (CNTR). People's Democratic Republic of Laos. Goods will transport from the storage in a boat by using Fork Lift. Distance is 1-2 km.html) .P a g e | 108 2. The berth is width 24 meters and length 180 meters. Bor Kaew District. We transport from manufacture (A) to Chiang Khong Port (B). The front of the port is adjacent to the Mekong River opposite of Moueng Houy Sai. Start from transportation Rubber (Bale) from truck to store goods in storage. Chiang Rai Province.co. Fuel oil: Biodiesel. Loading: 21 tons. Our company has the condition with customer that international shipments typically use FOB or Free on Board. Transport by truck Diesel Tenwheel. Chiang Khong District. And loading on vessel.th/ckp/eng/dataset1/data2. On the back is the road linking Chiang Saen and Chiang Kong Districts.
574.Do not notify every run. Capital 1.659 Insurance: Our Company chooses deal business with Mittare Insurance Co. .Protection of the full year.686.831.801.015 849.145.061 1.495 1.982.th/product-th-353965-1647870 ) . .944 2.398.Does not cover products that are illegal or high risk.638.216 934.213 2..594 2014 34.260.perfect-broker.000 Baht or 10% of damage.449 2013 31.180. .539 2.740.114. Trainer protected container. .co.027.500 Baht/Year Detail: Cargo insurance in the country.435 2.768.500.593 2.Suitable for car truck tractor that runs offshore shipping.P a g e | 109 4.Unlimited number of flight.598 3.426.045 2012 28.6. The case of an accident condition: -10.000 per year.450 1.378 3. Cost: 17. -Do not notify the cabinet product. (Source: 772. Table 4-10 Total Taxes Year Sale Forecast (price) VAT 7% Withholding 3% Total Per: Baht 2011 25.238 1.054 2015 37.130.816 3.Consumer protection online. . Ltd.314. .2 Inventory management Taxes: VAT 7% and withholding of 3 % per Year.
500 3.500 2.084 Cost/Baht -13.114.449 17. So we don’t have any cost of relocation.045 17.132.500 3.P a g e | 110 Table 4-11 Inventory Service Costs Year Taxes Insurance Total Per: Baht 2011 2. (Source:. Our products are Block rubber and rubber smoked sheet don’t have any cost of obsolescence. We don’t have Relocation Cost because our company has only one warehouse near manufactory.159 Table 4-12 Warehousing Cost Description Capital Costs (opportunity cost of capital) Inventory Risk Costs Obsolescence Damage Cost Shrinkage Cost Relocation Cost Total Cost Per: Month Note: Capital Cost or Opportunity cost of capital is not including in accounting because it is not the real cost that we expense.594 17.000- .054 17.591.arch56.786.084 0 12.659 17.848.com/?tag=public-warehouse-cost) 0 10.545 2012 2.768.831.574.443.500 2.426.554 2015 3.500 3.949 2013 3.450.000 2.094 2014 3.
084 228.245 1.800 445 2.291 230.962 12.800 509 2.300 1.084 228.962 12.962 12.046 215.314 230.962 12.084 228.046 215.084 228.291 230.6.962 12.962 12.962 12.962 12.800 445 2.800 509 2.245 1.3 Total Logistic Table 4-13 Total Logistic Cost.346 230.351 230.356 Per: Baht .084 228.305 1.351 230.046 215.309 215. 2011 Description Inventory Carrying Cost Taxes and insurance Warehousing Subtotal Transportation Costs Motor Carriers : Truck-Local (Diesel Ten-wheel) Tariff of Chiang Khong Port Subtotal Logistics Administration Total logistics 230.962 12.300 1.962 12.309 1.084 228.268 1.084 228.P a g e | 111 4.084 228.084 228.046 215.291 1.962 12.268 1.800 445 2.800 500 2.046 215.046 215.800 468 2.046 215.962 12.084 228.291 230.800 500 2.356 230.046 215.046 215.084 228.305 1.046 215.046 215.046 Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Not Including 230.084 228.245 1.800 505 2.800 505 2.800 445 2.800 468 2.314 230.245 1.346 230.
800 528 2.328 1.723 251.084 249.800 528 2.824 251.800 528 2.412 12.496 1.496 237.328 1.412 12.412 12.496 237.084 249.412 12.496 237.723 251.496 237.800 426 2.496 237.084 249.412 12.084 249.800 528 2.226 1.412 12.412 12.084 249.824 251.824 251.723 251.496 237.412 12.800 426 2.412 12.824 251.328 1.084 249.328 1.800 528 2.328 1.226 1.496 237.800 528 2.496 237.824 251.084 249.226 1.800 426 2.800 426 2.412 12.084 249.084 249. 2012 Description Inventory Carrying Cost Taxes and insurance Warehousing Subtotal Transportation Costs Motor Carriers : Truck-Local (Diesel Ten-wheel) Tariff of Chiang Khong Port Subtotal Logistics Administration Total logistics Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 237.800 528 2.P a g e | 112 Table 4-14 Total Logistic Cost.496 237.824 251.084 249.412 12.412 12.496 237.328 1.328 Not Including 251.496 237.084 249.824 Per: Baht .226 1.824 251.084 249.800 528 2.723 251.328 1.
800 548 2.092 261.348 1.328 275.092 261.092 261.328 275.092 1.084 273.092 261.237 1.084 273.348 1.440 275.800 548 2.237 1.440 275.440 Per: Baht .008 12.800 548 2.092 261.084 273.008 12.440 275.008 12.800 548 2.084 273.800 437 2.084 273.800 548 2.800 437 2.328 275.008 12.800 437 2.008 12.092 261.237 1.084 273.008 12.237 1.800 548 2.348 1.084 273.008 12.084 273.084 273.348 Not Including 275.440 275.008 12.440 275.328 275.800 437 2.348 1.348 1.440 275.008 12.348 1.800 548 2.008 12.092 261.092 261.092 261.P a g e | 113 Table 4-15 Total Logistic Cost.008 12. 2013 Description Inventory Carrying Cost Taxes and insurance Warehousing Subtotal Transportation Costs Motor Carriers: Truck-Local (Diesel Ten-wheel) Tariff of Chiang Khong Port Subtotal Logistics Administration Total logistics Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 261.084 273.092 261.440 275.084 273.092 261.008 12.084 273.348 1.800 548 2.
963 12.084 299.084 299.P a g e | 114 Table 4-16 Total Logistic Cost.196 3.047 286.084 299.242 Per: Baht .196 1.084 299. 2014 Description Inventory Carrying Cost Taxes and insurance Warehousing Subtotal Transportation Costs Motor Carriers: Truck-Local (Diesel Ten-wheel) Tariff of Chiang Khong Port Subtotal Logistics Administration Total logistics Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 286.196 Not Including 303.600 596 4.248 1.084 299.295 301.047 286.248 1.295 301.600 596 4.047 286.047 286.196 3.047 286.800 448 2.242 303.600 596 4.248 3.242 303.242 303.963 12.963 12.963 12.600 596 4.047 286.047 286.047 3.963 12.242 303.963 12.800 448 2.196 3.963 12.084 299.084 299.242 303.047 286.800 448 2.248 1.084 299.047 286.963 12.295 301.963 12.047 286.242 301.800 448 2.963 12.196 3.600 596 4.196 3.084 299.084 299.963 12.047 286.196 3.295 303.600 596 4.242 303.600 596 4.084 299.963 12.600 596 4.084 299.
260 3.597 315.220 Not Including 331.513 12.600 620 4.513 12.600 620 4.800 460 2.513 12.513 12.817 331.600 620 4.084 327. 2015 Description Inventory Carrying Cost Taxes and insurance Warehousing Subtotal Transportation Costs Motor Carriers: Truck-Local (Diesel Ten-wheel) Tariff of Chiang Khong Port Subtotal Logistics Administration Total logistics Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 315.597 315.084 327.857 329.084 327.857 329.220 3.084 327.597 315.513 12.817 331.600 620 4.817 Per: Baht .084 327.600 620 4.800 460 2.513 12.800 460 2.P a g e | 115 Table 4-17 Total Logistic Cost.800 460 2.817 331.597 315.600 620 4.513 12.260 1.513 12.817 331.220 1.260 1.084 327.597 315.084 327.084 327.220 3.597 315.857 329.084 327.600 620 4.597 315.220 3.084 327.597 3.260 1.857 331.597 315.817 331.513 12.597 315.817 329.513 12.600 620 4.597 315.084 327.220 3.220 3.220 3.597 315.513 12.513 12.817 331.084 327.
th/ckp/eng/dataset5/data1.3.. The rates that we agree are Diesel Ten-wheel capacity 22 tons per times to be cost 1.co.P a g e | 116 4..Baht/Tonne/m3 (Source:.. Our company transportation goods by pass Chiang Khong Port (Port Authority of Thailand) We have cost of Tariff for transportation: 1.port. Ltd. Charges Against Shipowners. each month we separate to two times on second week and last week of month for transport the product to the Chiang Khong Port.Cargo Loading or Discharging Free Conventional cargo 3. Charges Against Consignees. Vechicles Adminission Fee .6.800 Baht. Consignors or Applicants .Baht/Unit 10.1 Transportation Costs of Truck-Local (Diesel Ten-wheel) For transportation. Our company deal with Golden lake Co.Baht 2. . Ship’s Agents or Applicants Vessel of over 100 GT 300.3.html) 4.6..2 Logistics Administration Cost of Logistics Administration is including with Administration Cost.Fee for vehicle loading or discharging within Chiang Khong Port 8-10 Wheel Truck 25.
P a g e | 117 4.7.7 Administration cost 4.1 Organizational structure Figure 3-4 Organization Structure .
co.000 20.000 20. living room.2 Administration Expense Employee salary 1 person 1 person 1 person 1 person 2 person (2*12.There are 1 housekeeper and 1 diver.th/uploads/Knowledge-Center-Thought- General Manager Office Manager Plant Manager Logistic manager Sale and Marketing department IT support department Logistic department Export department Accountant department Housekeeper Driver Security guard Total Leadership/Thailand-Salary-Guide/Adecco-Thailand-Salary-Guide-2011.000) 1 person 1 person 2 person (2*8.000) EXHIBIT 4-10 Wage rate for our organization 30.3 Administration Zone This is Administration zone there are 7 employees (there are 3 private rooms for executive included 4 employees).7.000) 2 person (2*12.7.000 12.adecco. and canteen In outside area there are 2 sentry boxes in front of entrance door and exit door.000 24.000 12.000 20.000 20.P a g e | 118 4.000) 1 person 2 person (2*12.000 231.000 17.000 8.000 24.000 (Resource:. .500) 4 person (2*5.pdf) 4. The administration zones have 1 small meeting room.000 24. Toilet.
155 .500 Amount Total (Baht) 206.976 Baht.520. All of this we can calculate the number of money with is 2.165 7 71.500 1 Desk 7 2 Desktop PC 10.P a g e | 119 EXHIBIT 4-11 Administration Zone Storeroom Storeroom Toilet Office equipments In the office. we use many of equipment to operation. EXHIBIT 4-12 Office Equipments Cost No. Item Picture Price (Baht) 29.
260 8 Printer 1.800 10 Set up cost(Air) 2.400 3 Telephone 4 4 Stationery 1.750 5 A4 paper 10 10 550 5.900 12.100 Amount Total (Baht) 12.000 1 15.600 10 66.000 15 Sofa 12.900 13 Loudspeaker 12.000 Projector 89. Item Picture Price (Baht) 3.200 1 12.789 17 Flower 120 4 480 .250 7 8.500 2 5.900 2 27.900 1 14 Microphone 6.670 2 3.200 16 Table 3.900 1 89.P a g e | 120 No.500 6 Ink 75 750 7 Receipt paper 105 12 1.340 9 Air condition 13.789 1 3.000 11 12 Table 15.
Item Picture Price (Baht) 440 Amount Total (Baht) 440 18 Carpet 1 19 Disk rack 1.990 1 3.125 21 Glasses 15 12 180 22 Table 5.600 23 Refrigerator 8.800 2 11.689 1 1.P a g e | 121 No.190 1 8.689 26 Mirror 680 1 680 27 Box 320 1 320 28 Sink 750 1 750 29 Douche 180 1 180 30 Shelf 650 1 650 31 Broom 250 1 250 32 Mop 650 1 650 .190 24 Sink 3.990 25 Lavatory 1.279 2 2.558 20 Disk 225 5 1.
000 Amount Total (Baht) 100.520.co.000 33 Vigo car 1 34 Van 1.000 Amount Total (Baht) 607.. Item Picture Price (Baht) 50. EXHIBIT 4-13 Guardhouse Equipment Cost No.800 Baht for.000 1 1.338.com/index. Item Picture Price (Baht) 607.976 Guardhouse equipment In the part of Administration zone are include with guardhouse in enter and exit way.P a g e | 122 No.800 103.th/products.cetechgroup. .000 1 Guard ready-made 2 2 Traffic cone Total 380 10 3. We choose to take the guard ready-made.000 Total 2.php.php?lay=show&ac=article&Id=573945&Ntype=2) .topvictorystar.800 (Source:. We will pay 103.
1 Administration Expense EXHIBIT 4-14 Administration Expense Description Employee Salary Telephone and Internet expense Electricity expense Water expense Stationary expense Gasoline Expense Car insurance Fire insurance Machine insurance Social security insurance 17.go.89/month 500/month 8.525/y 5.th) .tninsure.dpu.mwa.571.co.P a g e | 123 4.th : Water expense: : Car insurance: : Fire insurance: : Social security insurance: 3 month 5.sso.545/y 2.ac.600/y Base (Source: Telephone and Internet expense: 33.550/month 7.000/month 7.th/water_calculation.th/ : Electricity expense: : Machine insurance:.
622 Apr 231.000 8.545 2.572 500 8.372 Nov 231.600 90.000 33.000 261.750 5.000 17.000 17.000 261.750 5.372 May 231.228.372 Aug 231.550 7.000 60.000 17.572 500 8.550 7.572 500 5.000 17.000 17.572 500 5.545 2.000 17.000 7.000 17.750 5.133 .772.000 17.000 210.000 5.550 7.000 17.000 17.042 Jan 231.572 500 5.000 33.572 500 5.600 324.622 Mar 231.525 5.622 Jul 231.572 500 5.622 Dec 231.572 500 8.000 261.000 7.042 Feb 231.P a g e | 124 Table 4-18 Administration cost 2011 Administration cost Base Employee Salary Telephone and Internet expense Electricity expense Water expense Set up air-condition expense Stationary expense Gasoline Expense Car insurance Fire insurance Machine insurance Social security insurance Total 231.545 2.000 17.000 17.550 7.572 500 5.863 6.572 500 5.572 500 5.525 5.000 17.550 7.000 270.550 7.000 261.550 7.622 Oct 231.622 Total 2.622 Sep 231.550 7.572 500 5.000 33.622 Jun 231.525 5.000 7.572 500 5.600 324.000 261.550 7.550 7.000 261.600 3.000 35.750 5.550 7.750 5.000 8.000 270.550 7.000 261.000 261.550 7.000 270.
622 May 231.550 7.000 17.000 17.622 Aug 231.000 17.525 5.000 261.000 0 35.000 17.000 17.572 500 5.000 261.000 261.000 33.550 7.000 261.622 Dec 231.572 500 5.000 33.000 17.772.000 210.550 7.372 Jul 231.622 Mar 231.622 Nov 231.545 2.750 5.000 60.545 2.550 7.622 Sep 231.572 500 5.863 6.000 8.000 261.600 90.550 7.750 5.572 500 5.572 500 5.750 5.550 7.000 17.000 270.572 500 8.572 500 5.545 2.600 319.600 3.000 17.550 7.000 17.550 7.000 261.372 Apr 231.572 500 8.000 17.572 500 5.042 Jan 231.133 .000 270.223.000 261.000 33.550 7.000 17.550 7.550 7.000 7.550 7.525 5.622 Jun 231.750 5.622 Feb 231.000 7.525 5.550 7.042 8.000 261.000 270.572 500 8.572 500 5.372 Oct 231.P a g e | 125 Table 4-19 Administration cost 2012 Administration cost Base Employee Salary Telephone and Internet expense Electricity expense Water expense Set up air-condition expense Stationary expense Gasoline Expense Car insurance Fire insurance Machine insurance Social security insurance Total 231.000 7.572 500 5.572 500 Total 2.000 17.600 324.750 5.000 17.
550 7.572 500 8.572 500 Oct 231.000 17.750 5.622 May 231.P a g e | 126 Table 4-20 Administration cost 2013 Administration cost Base Employee Salary Telephone and Internet expense Electricity expense Water expense Set up air-condition expense Stationary expense Gasoline Expense Car insurance Fire insurance Machine insurance Social security insurance Total 231.000 261.000 17.572 500 8.042 Jan 231.000 33.000 17.042 5.572 500 Jul 231.863 6.750 5.600 324.372 5.000 17.750 5.000 270.000 17.622 Feb 231.000 210.000 17.550 7.372 5.000 261.750 5.600 90.550 7.622 Dec 231.622 Jun 231.000 17.600 319.550 7.525 5.000 17.000 261.000 0 60.000 17.622 Nov 231.622 Mar 231.572 500 5.550 7.572 500 Total 2.622 Sep 231.000 35.000 270.550 7.550 7.000 270.000 261.000 261.550 7.000 33.572 500 Apr 231.000 7.000 17.000 261.550 7.000 17.223.000 7.000 261.525 5.372 5.000 261.000 5.525 5.550 7.572 500 5.550 7.545 2.750 5.000 7.545 2.572 500 5.545 2.000 17.572 500 5.572 500 8.622 Aug 231.600 3.000 33.572 500 8.572 500 8.000 17.550 7.772.550 7.133 .
622 Aug 231.572 500 8.622 Dec 231.525 5.000 270.545 2.000 261.550 7.572 500 5.000 17.000 7.622 Sep 231.600 319.000 261.550 7.000 261.572 500 5.572 500 5.000 261.572 500 8.000 17.000 17.572 500 5.000 7.550 7.550 7.000 17.572 500 Total 2.750 5.133 .622 May 231.622 Jun 231.000 8.572 500 5.000 17.750 5.000 261.750 5.000 270.000 261.545 2.372 Apr 231.863 6.622 Feb 231.772.550 7.550 7.622 Nov 231.223.000 17.000 33.000 17.550 7.550 7.000 33.600 324.042 8.550 7.042 Jan 231.000 261.545 2.750 5.550 7.550 7.525 5.000 7.372 Jul 231.000 17.750 5.000 0 35.P a g e | 127 Table 4-21 Administration cost 2014 Administration cost Base Employee Salary Telephone and Internet expense Electricity expense Water expense Set up air-condition expense Stationary expense Gasoline Expense Car insurance Fire insurance Machine insurance Social security insurance Total 231.000 17.600 3.525 5.600 90.572 500 5.000 270.000 210.572 500 8.572 500 5.550 7.000 17.572 500 5.000 17.000 60.000 33.622 Mar 231.372 Oct 231.572 500 5.000 17.000 17.550 7.000 261.
000 60.000 17.550 7.000 33.000 17.622 Dec 231.000 17.042 8.772.622 May 231.000 261.000 17.042 Jan 231.372 Jul 231.525 5.622 Nov 231.622 Mar 231.550 7.000 17.545 2.000 270.000 17.750 5.572 500 8.572 500 5.572 500 5.572 500 5.000 8.550 7.572 500 5.000 210.372 Apr 231.600 319.372 Oct 231.000 261.000 17.750 5.000 270.525 5.000 261.P a g e | 128 Table 4-22 Administration cost 2015 Administration cost Base Employee Salary Telephone and Internet expense Electricity expense Water expense Set up air-condition expense Stationary expense Gasoline Expense Car insurance Fire insurance Machine insurance Social security insurance Total 231.000 17.622 Sep 231.622 Jun 231.000 7.600 324.600 3.000 261.550 7.550 7.000 17.572 500 5.550 7.000 261.550 7.000 17.622 Aug 231.600 90.550 7.550 7.550 7.000 17.000 261.000 261.750 5.000 17.750 5.572 500 Total 2.550 7.133 .572 500 8.622 Feb 231.550 7.000 33.545 2.000 270.863 6.572 500 5.572 500 8.000 7.525 5.572 500 5.223.572 500 5.750 5.000 0 35.000 17.572 500 5.550 7.000 33.545 2.000 7.000 261.
8 Depreciation cost Table 4-23 Depreciation cost 2011 Administration Office room Table Computer Telephone Printer Air Condition Meeting room Table Projector Loudspeaker Microphone Living room Sofa Table Canteen Refrigerator Disk rack Table Sink Amount 206.483 215 2.442 1.186 904 56 463 250 1.750 203 63 137 107 193 67 Nov 3.558 11.700 3.750 203 63 137 107 193 67 Feb 3.750 203 63 137 107 193 67 Sep 3.P a g e | 129 4.800 15.442 1.483 215 2.500 71.300 14.483 215 2.483 215 2.186 904 56 463 250 1.186 904 56 463 250 1.750 203 63 137 107 193 67 Jul 3.638 1.000 12.190 2.155 21.442 1.442 1.990 Jan 3.186 904 56 463 250 1.231 10.442 1.186 904 56 463 250 1.800 2.186 904 56 463 250 1.279 2.750 203 63 137 107 193 67 Jun 3.200 3.340 27.483 215 2.442 1.850 668 5.440 758 1.000 89.789 8.483 215 2.750 203 63 137 107 193 67 Mar 3.750 203 63 137 107 193 67 Dec 3.000 2.750 203 63 137 107 193 67 Aug 3.442 1.560 3.186 904 56 463 250 1.320 798 .483 215 2.483 215 2.186 904 56 463 250 1.750 203 63 137 107 193 67 Total 41.483 215 2.900 66.186 904 56 463 250 1.483 215 2.442 1.442 1.442 1.750 203 63 137 107 193 67 Oct 3.186 904 56 463 250 1.442 1.186 904 56 463 250 1.483 215 2.750 203 63 137 107 193 67 Apr 3.483 215 2.186 904 56 463 250 1.442 1.600 3.750 203 63 137 107 193 67 May 3.580 33.000 17.000 12.
117 10.941 23.667 2.941 23.667 121.667 2.117 10.941 23.230 1.000 287.941 23.made Total Amount Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Total 1.667 2.667 2.760 20.117 10.941 23.230 1.230 1.117 10.230 1.000 100.117 10.667 2.941 23.982 23.230 1.117 1.941 .117 10.338.667 2.230 1.667 2.667 2.P a g e | 130 Administration Toilet Lavatory Mirror Box Sink Douche Storeroom Shelf Office Transportation Vigo car VAN Guard ready.000 2.000 10.230 1.941 23.230 1.941 23.288 2.941 23.941 23.230 1.117 10.667 2.230 1.117 10.230 1.230 1.667 2.604.941 23.117 10.400 26.117 10.117 10.
186 904 56 463 250 1.750 203 63 137 107 193 67 Oct 3.300 14.750 203 63 137 107 193 67 Total 41.483 215 2.442 1.750 203 63 137 107 193 67 Jun 3.186 904 56 463 250 1.750 203 63 137 107 193 67 Aug 3.186 904 56 463 250 1.442 1.560 3.442 1.800 2.186 904 56 463 250 1.200 3.483 215 2.483 215 2.750 203 63 137 107 193 67 Apr 3.483 215 2.580 33.700 3.638 1.320 798 .483 215 2.000 12.750 203 63 137 107 193 67 Feb 3.440 758 1.442 1.789 8.186 904 56 463 250 1.000 17.186 904 56 463 250 1.990 Jan 3.750 203 63 137 107 193 67 Nov 3.442 1.442 1.750 203 63 137 107 193 67 Jul 3.442 1.750 203 63 137 107 193 67 Sep 3.231 10.850 668 5.P a g e | 131 Table 4-24 Depreciation cost 2012 Administration Office room Table Computer Telephone Printer Air Condition Meeting room Table Projector Loudspeaker Microphone Living room Sofa Table Canteen Refrigerator Disk rack Table Sink Amount 206.750 203 63 137 107 193 67 Mar 3.900 66.000 12.483 215 2.483 215 2.442 1.500 71.442 1.186 904 56 463 250 1.483 215 2.442 1.186 904 56 463 250 1.483 215 2.000 2.000 89.483 215 2.750 203 63 137 107 193 67 May 3.750 203 63 137 107 193 67 Dec 3.442 1.600 3.186 904 56 463 250 1.186 904 56 463 250 1.483 215 2.279 2.155 21.186 904 56 463 250 1.558 11.190 2.483 215 2.340 27.442 1.800 15.186 904 56 463 250 1.
941 23.117 10.982 23.230 1.230 1.000 100.117 10.230 1.338.667 2.941 287.400 1.230 1.667 26.000 2.230 1.941 23.941 23.667 2.117 10.117 10.230 1.117 10.000 2.117 10.760 20.230 1.667 2.230 1.941 23.941 23.230 1.230 1.941 23.941 23.667 2.667 2.117 121.667 2.941 23.667 2.667 2.117 10.230 1.117 10.117 10.941 23.117 10.941 23.230 1.288 .000 10.117 10.941 23.667 2.667 2.604.P a g e | 132 Administration Toilet Lavatory Mirror Box Sink Douche Storeroom Shelf Office Transportation Vigo car VAN Guard readymade Total Amount Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Total 1.
P a g e | 133 Table 4-25 Depreciation cost 2013 Administration Office room Table Computer Telephone Printer Air Condition Meeting room Table Projector Loudspeaker Microphone Living room Sofa Table Canteen Refrigerator Disk rack Table Sink Amount Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Total 206.000 12.231 0 668 5.442 1.442 1.483 215 0 203 63 137 0 193 67 3.483 215 0 203 63 137 0 193 67 3.789 8.558 11.186 0 56 463 250 1.186 0 56 463 250 1.320 798 .483 215 0 203 63 137 0 193 67 3.000 12.000 89.600 3.186 0 56 463 250 1.442 1.483 215 0 203 63 137 0 193 67 3.560 3.442 1.638 0 2.442 1.990 3.186 0 56 463 250 1.483 215 0 203 63 137 0 193 67 3.442 1.500 71.190 2.442 1.900 66.483 215 0 203 63 137 0 193 67 3.442 1.186 0 56 463 250 1.186 0 56 463 250 1.700 3.483 215 0 203 63 137 0 193 67 41.186 0 56 463 250 1.000 17.300 14.483 215 0 203 63 137 0 193 67 3.442 1.186 0 56 463 250 1.340 27.200 3.186 0 56 463 250 1.483 215 0 203 63 137 0 193 67 3.483 215 0 203 63 137 0 193 67 3.186 0 56 463 250 1.800 2.442 1.442 1.186 0 56 463 250 1.580 0 2.186 0 56 463 250 1.483 215 0 203 63 137 0 193 67 3.483 215 0 203 63 137 0 193 67 3.440 758 1.442 1.155 21.800 15.
172 20.230 2.667 1.172 20.667 20.117 10.172 20.000 2.172 20.400 1.P a g e | 134 Administration Toilet Lavatory Mirror Box Sink Douche Storeroom Shelf Office Transportation Vigo car VAN Guard readymade Total Amount 1.172 20.230 26.172 20.117 10.117 10.000 10.117 10.117 10.230 2.667 1.604.230 2.000 2.230 2.667 1.230 2.172 20.117 10.172 242.230 2.172 20.338.117 10.667 1.230 2.117 10.117 10.667 1.230 2.230 2.667 1.172 20.117 10.760 100.667 1.667 1.069 .000 1.667 1.230 2.982 20.230 2.667 1.172 20.172 20.117 121.667 1.117 10.
186 0 56 463 250 1.483 215 0 203 63 137 0 193 67 41.186 0 56 463 250 1.300 14.483 215 0 203 63 137 0 193 67 3.990 3.638 0 2.483 215 0 203 63 137 0 193 67 3.320 798 .200 3.000 12.186 0 56 463 250 1.483 215 0 203 63 137 0 193 67 3.186 0 56 463 250 1.558 11.186 0 56 463 250 1.900 66.442 1.186 0 56 463 250 1.440 758 1.186 0 56 463 250 1.442 1.000 17.500 71.442 1.442 1.155 21.000 12.580 0 2.700 3.483 215 0 203 63 137 0 193 67 3.P a g e | 135 Table 4-26 Depreciation cost 2014 Administration Office room Table Computer Telephone Printer Air Condition Meeting room Table Projector Loudspeaker Microphone Living room Sofa Table Canteen Refrigerator Disk rack Table Sink Amount Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Total 206.190 2.000 89.340 27.186 0 56 463 250 1.442 1.483 215 0 203 63 137 0 193 67 3.442 1.800 2.600 3.800 15.442 1.789 8.560 3.442 1.231 0 668 5.
680 28 28 28 28 28 28 28 28 28 28 28 28 Lavatory 336 680 11 11 11 11 11 11 11 11 11 11 11 11 Mirror 136 320 5 5 5 5 5 5 5 5 5 5 5 5 Box 64 750 13 13 13 13 13 13 13 13 13 13 13 13 Sink 150 180 0 0 0 0 0 0 0 0 0 0 0 0 Douche 0 Storeroom 650 11 11 11 11 11 11 11 11 11 11 11 11 Shelf 130 Office Transportation 607.667 1.172 20.667 1.117 10.000 2.230 2.172 20.230 2.667 1.667 1.230 2.667 1.000 10.230 2.172 242.982 20.172 20.117 10.230 2.230 2.069 .117 10.117 10.117 10.117 121.117 10.400 Vigo car 1.172 20.760 VAN Guard ready100.667 1.667 20.172 20.667 1.230 2.230 26.338.172 20.117 10.172 20.667 1.230 2.667 1.230 2.000 1.230 2.172 20.604.000 made Total 2.667 1.172 20.117 10.117 10.172 20.117 10.230 2.172 20.117 10.667 1.P a g e | 136 Administration Amount Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Total Toilet 1.
483 215 0 203 63 137 0 193 67 Jun 3.186 0 56 463 250 1.442 1.483 215 0 203 63 137 0 193 67 Total 41.800 15.190 2.186 0 56 463 250 1.320 798 .442 1.442 1.442 1.500 71.442 1.483 215 0 203 63 137 0 193 67 Sep 3.340 27.560 3.186 0 56 463 250 1.442 1.300 14.186 0 56 463 250 1.483 215 0 203 63 137 0 193 67 May 3.186 0 56 463 250 1.483 215 0 203 63 137 0 193 67 Nov 3.638 0 2.186 0 56 463 250 1.483 215 0 203 63 137 0 193 67 Aug 3.900 66.200 3.186 0 56 463 250 1.483 215 0 203 63 137 0 193 67 Oct 3.186 0 56 463 250 1.000 12.186 0 56 463 250 1.000 17.442 1.P a g e | 137 Table 4-27 Depreciation cost 2015 Administration Office room Table Computer Telephone Printer Air Condition Meeting room Table Projector Loudspeaker Microphone Living room Sofa Table Canteen Refrigerator Disk rack Table Sink Amount 206.442 1.155 21.789 8.580 0 2.442 1.483 215 0 203 63 137 0 193 67 Mar 3.483 215 0 203 63 137 0 193 67 Feb 3.186 0 56 463 250 1.186 0 56 463 250 1.186 0 56 463 250 1.000 12.000 89.231 0 668 5.442 1.483 215 0 203 63 137 0 193 67 Jul 3.483 215 0 203 63 137 0 193 67 Apr 3.600 3.440 758 1.442 1.442 1.990 Jan 3.558 11.483 215 0 203 63 137 0 193 67 Dec 3.800 2.700 3.
667 1.117 10.667 1.667 1.000 2.117 121.667 1.230 2.230 2.760 100.117 10.667 1.667 1.604.172 20.667 1.230 2.230 2.230 2.P a g e | 138 Administration Toilet Lavatory Mirror Box Sink Douche Storeroom Shelf Office Transportation Vigo car VAN Guard readymade Total Amount 1.117 10.172 20.172 20.230 2.230 2.172 20.230 2.667 1.069 .667 1.172 20.172 20.117 10.000 2.172 20.117 10.172 20.000 10.117 10.230 2.230 2.230 2.117 10.172 20.667 20.117 10.117 10.400 1.338.117 10.172 20.982 20.172 242.667 1.117 10.000 1.230 26.172 20.667 1.
first is the direct purchase the field latex from the agriculturist and purchase the middleman to purchase from the agriculturist. We emphasize the high export the STR block rubber are 40% and Rib Smoked Sheet are 30% . We think is the trade route will can to be able to have the high possibility in export the rubber process to the best outcome.The trade route of company to using is emphasize save a time and save cost . For the expense . In the process for our step. Domestic purchase price hold the price of central rubber market is purchase from the agriculturist and sale price for export. contact the export data and testing the possibility for export. seek the data for setting the factory. process in production of the Rib Smoked Sheet or RSS and STR block rubber. This is following the data of company. In the export department. The companies have the data for ready to export. For the located or stand the factory. We using the predict price of before market follow the world price. Second lead to the factory for process in the step such as measure the quality of the latex it have the level quality to how the difference. Far the Chiang Khong district in the distance is 2 kilometer. We think the rubber process is interesting. The company fixed price follows the purchase price and sale price. Which using price from the appropriate of production and the capability of purchase for bring the process.Including seek the location to export near the production located. equipment for purchasing. Which was beginning plant in the various areas on Chiang Rai province? Our company’s “Thai North Rubber Industry” has interesting to rubber process for export. Third. Our divides the categories of product bring to process are rubber process is the Rib Smoked Sheet or RSS and STR block rubber. We have the location near with the ChiangKhong district in Chiang Rai province.9 Conclusion Technical Feasibility Conclusion In now the rubber are the most popular. first we seek the location can to support and ready to purchase our product. In the part of management the company have the operation from the step is the seek the location.P a g e | 139 4.
The employee has the high effectiveness in the future. preoperational cost. logistic. .P a g e | 140 of all operation. Ready to cooperation with the product export company and increase the responsibility to work. which separate is operation cost. Which have the detail to differences for our customer we emphasize to the employee have the high skill.
P a g e | 141 Chapter 5 Financial Analysis .
435.776 6.000 446.514.1.860 .068.514.860 2.060 8.1 Total requirement Table 5-1 Total requirement Total requirement Description Preopening Cost Operating Investment Administrative Investment Land Cost Inventory purchasing Operating Expense Administrative Expense Total funding requirement Baht 596.650 8.1.794.000 6.1 Total requirement and the source fund 5.450.553 71.794. There are 24.800 1.822 24.1 Financial Statement 5.P a g e | 142 Financial Analysis 5.000.774 The table shows above represents the total funding requirement of the beginning of this project.624.1.774 Baht of Total requirement Table 5-2 Operating Investment Operating Investment Production machine Testing Lab Equipment Building Total Baht 7.112 101.
445.000 1.000 2.994.520.000 6.325. So we want the money to operation within these 3 months.875.776 Inventory purchasing. Table 5-4 Inventory purchasing Inventory purchasing January February March Total Baht 1.885 2.000 Table 5-5 Operating Expense Operating Expense January February March Total Baht 1.875.112 .624.435.885 1.800 2.P a g e | 143 Table 5-3 Administrative investment Administrative investment Office equipments Supply Total Baht 2.976 103. Operating Expense and Administrative Expense. we use first 3 months of 2011 because we have the condition about Account Receivable for customers must to pay money within 3 months.075.994.343 6.
P a g e | 144 Table 5-6 Administrative Expense Administrative Expense January February March Total Baht 23.000 Baht.000. So. The investor will get refund faster.941 23. 3. The length that we have pay loan are only 10 years. The condition that the investor will be following: The interest not more than 15% per year of the loan amount following the law of Thailand. The reasons that make investor invest with us: 1.941 71. The interest rate of our company more than average interest rate of commercial banks.000. The investor not have risk with net income of our business if the business loss the investor not responsible with us. .822 5.7791% and Average of Foreign Bank Branches is 7.2 The source of fund Our company will borrowing fund from investor who interest this project and want to invest with us.1.941 23. Interest will be 12% per annum. 2. Total requirement is 25. Minimum loan rate of Daily interest rate of commercial banks have Average of Commercial Banks registered in Thailand is 6. So.1.000 Baht within 10 years of repayment. We will continue pay the money that we loan and the interest too.5417%. the interest loan rate that we have 12% more than 3-4% of commercial banks. a loan amounts of 25. According to the Daily interest rate of commercial banks from Bank of Thailand.
P a g e | 145
5.1.2 Income statement
Thai-North Rubber Industry Company Income Statement For Year Ended December 31, 2011(Baht)
Period Starting: Sales Sales Total Sales Less Cost of Goods Sold Materials Operation expense Logistic Total Cost of Goods Sold 1,072,344 242,564 230,314 1,545,222 449,663 0 324,042 701,650 13,760 57,791 1,097,243 -647,580 250,000 1,072,344 242,564 230,314 1,545,222 449,663 0 261,622 57,792 319,414 130,249 248,913 1,314,486 242,564 230,346 1,787,396 657,947 0 261,622 57,792 319,414 338,533 247,816 1,314,486 242,564 230,346 1,787,396 657,947 3,000 270,372 57,792 331,164 326,783 246,707 959,344 242,564 230,291 1,432,199 240,930 0 261,622 57,792 319,414 -78,484 245,587 959,344 242,564 230,291 1,432,199 240,930 1,000 261,622 57,792 320,414 -79,484 244,456 959,344 242,564 230,291 1,432,199 240,930 1,000 270,372 57,792 329,164 -88,234 243,314 959,344 242,564 230,291 1,432,199 240,930 4,000 261,622 57,792 323,414 -82,484 242,161 1,349,078 242,564 230,351 1,821,992 687,701 1,200 261,622 57,792 320,614 367,087 240,995 1,349,078 242,564 230,351 1,821,992 687,701 1,000 270,372 57,792 329,164 358,537 239,819 1,994,885 1,994,885 1,994,885 1,994,885 2,445,343 2,445,343 2,445,343 2,445,343 1,673,129 1,673,129 1,673,129 1,673,129 1,673,129 1,673,129 1,673,129 1,673,129 2,509,694 2,509,694 2,509,694 2,509,694 Jan Feb Mar Apr May Jun Jul Aug Sep Oct
Table 5-7 Income Statement, 2011
Nov
Dec
Totals
2,574,045 2,574,045 1,383,669 242,564 230,356 1,856,589 717,456 1,200 261,622 57,792 320,614 396,842 238,630
2,574,045 2,574,045 1,383,669 782,564 230,356 2,396,589 177,456 4,500 261,622 57,792 323,914 -146,458 237,429
25,740,450 25,740,450 14,076,528 3,450,768 2,763,898 20,291,194 5,449,256 16,900 3,228,133 701,650 13,760 693,505 4,653,947 795,308 2,925,827
Gross Profit Operating Expenses Selling administration expense Pre opening expense Supplies expense Depreciation Total Operating Expenses Operating Income Interest income (expense) Income (Loss) Before Taxes Income Taxes Net Income (Loss) Cumulative Net Income (Loss)
-897,580 0 -897,580
-118,664 0 -118,664
90,717 0 90,717
80,076 0 80,076
-324,071 0 -324,071
-323,940 0 -323,940
-331,548 0 -331,548
-324,644 0 -324,644
126,092 0 126,092
118,719 0 118,719
158,212 0 158,212
-383,887 0 -383,887
-2,130,519 0 -2,130,519
-897,580
-1,016,244
-925,527
-845,451
-1,169,522
-1,493,462
-1,825,010
-2,149,655
-2,023,563
-1,904,844
-1,746,632
-2,130,519
0
Note: Tax: According to our company is company limited. So, we must to pay the tax in rate of 30% per annual equal to 2.5% each month following the Revenue Department.
P a g e | 146
Table 5-8 Income Statement, 2012
Thai-North Rubber Industry Company Income Statement For Year Ended December 31, 2012,130,519 200 319,042 0 13,760 57,791 390,793 424,232 236,217 188,015 -6,892 194,907 0 261,622 0 57,792 319,414 495,611 234,992 260,619 -6,892 267,511 200 261,622 0 57,792 319,614 495,411 233,756 261,655 -6,892 268,547 4000 270,372 0 57,792 332,164 482,861 232,506 250,355 -6,892 257,247 200 261,622 0 57,792 319,614 -209,929 231,245 -441,173 -6,892 -434,281 0 261,622 0 57,792 319,414 -209,729 229,970 -439,699 -6,892 -432,807 200 270,372 0 57,792 328,364 -218,679 228,683 -447,362 -6,892 -440,470 4000 261,622 0 57,792 323,414 -213,729 227,383 -441,112 -6,892 -434,220 200 261,622 0 57,792 319,614 495,411 226,070 269,341 -6,892 276,233 0 270,372 0 57,792 328,164 486,861 224,744 262,117 -6,892 269,009 200 261,622 0 57,792 319,614 495,411 223,405 272,006 -6,892 278,898 4000 261,622 0 57,792 323,414 -48,389 222,052 -270,441 -6,892 -263,549 13,200 3,223,133 0 13,760 693,505 3,943,597 2,475,343 2,751,024 -275,681 -82,704 -192,977 782,564 251,824 2,556,425 275,025 15,423,300 3,450,768 3,021,487 21,895,555 6,418,940 2,831,449 2,831,449 2,831,449 2,831,449 2,831,449 2,831,449 2,831,449 2,831,449 1,415,725 1,415,725 1,415,725 1,415,725 1,415,725 1,415,725 1,415,725 1,415,725 2,831,449 2,831,449 2,831,449 2,831,449 2,831,449 2,831,449 2,831,449 2,831,449 28,314,495 28,314,495 Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Totals
-1,935,612
-1,668,101
-1,399,554
-1,142,307
-1,576,589
-2,009,396
-2,449,866
-2,884,086
-2,607,853
-2,338,845
-2,059,947
-2,323,496
0
Note: Tax: According to our company is company limited. So, we must to pay the tax in rate of 30% per annual equal to 2.5% each month following the Revenue Department.
P a g e | 147
Table 5-9 Income Statement, 2013
Thai-North Rubber Industry Company Income Statement For Year Ended December 31, 2013 ,323,496 Jan 3,114,594 3,114,594 Feb 3,114,594 3,114,594 Mar 3,114,594 3,114,594 Apr 3,114,594 3,114,594 May 1,557,297 1,557,297 Jun 1,557,297 1,557,297 Jul 1,557,297 1,557,297 Aug 1,557,297 1,557,297 Sep 3,114,594 3,114,594 Oct 3,114,594 3,114,594 Nov 3,114,594 3,114,594 Dec 3,114,594 3,114,594 Totals 31,145,944 31,145,944
1,674,240 242,564 275,440 2,192,244 922,351 200 319,042 0 13,760 53,107 386,109 536,241 220,686
1,674,240 242,564 275,440 2,192,244 922,351 0 261,622 0 0 53,108 314,730 607,621 219,306
1,674,240 242,564 275,440 2,192,244 922,351 200 261,622 0 53,108 314,930 607,421 217,912
1,674,240 242,564 275,440 2,192,244 922,351 3500 270,372 0 53,108 326,980 595,371 216,505
892,928 242,564 275,328 1,410,820 146,477 200 261,622 0 53,108 314,930 -168,453 215,083
892,928 242,564 275,328 1,410,820 146,477 0 261,622 0 53,108 314,730 -168,253 213,647
892,928 242,564 275,328 1,410,820 146,477 200 270,372 0 53,108 323,680 -177,203 212,197
892,928 242,564 275,328 1,410,820 146,477 3500 261,622 0 53,108 318,230 -171,753 210,732
1,674,240 242,564 275,440 2,192,244 922,351 200 261,622 0 53,108 314,930 607,421 209,252
1,674,240 242,564 275,440 2,192,244 922,351 0 270,372 0 53,108 323,480 598,871 207,758
1,674,240 242,564 275,440 2,192,244 922,351 200 261,622 0 53,108 314,930 607,421 206,249
1,674,240 782,564 275,440 2,732,244 382,351 3500 261,622 0 53,108 318,230 64,121 204,725
34,288,431 3,450,768 3,304,835 23,721,233 7,424,712 11,700 3,223,133 0 13,760 637,294 3,885,887 3,538,825 2,554,052
315,555 24,619 290,936 2,032,560
388,315 24,619 363,695 -1,668,864
389,508 24,619 364,889 -1,303,975
378,866 24,619 354,247 -949,728
-383,536 24,619 -408,155 -1,357,884
-381,900 24,619 -406,519 -1,764,403
-389,400 24,619 -414,019 -2,178,422
-382,485 24,619 -407,104 -2,585,526
398,168 24,619 373,549 -2,211,977
391,113 24,619 366,493 -1,845,484
401,172 24,619 376,552 -1,468,931
-140,604 24,619 -165,223 -1,634,155
984,773 295,432 689,341 0
Note: Tax: According to our company is company limited. So, we must to pay the tax in rate of 30% per annual equal to 2.5% each month following the Revenue Department.
426.426.526.054 3.470 1.108 326.054 3.221 242.980 200 261.622 0 53.221 242.098 449.461 3.054 3.664 782.108 314.155 200 319.543 1.109 0 261.713 533. .295 1.846 57.462 475.462 455.713.351 57.426.828 1.887 1.108 314.813 -323.054 3.426.038. we must to pay the tax in rate of 30% per annual equal to 2.930 3500 261.608.927.662.426.189 37.117 25. So.080 -618.132 513.086 -25.054 3.027 1.078 8.565 -311.079 186.768 3.664 242.462 469.302 715.890 526.618 723.462 391.295 1.564 303.470 1.036 57.260.038.630.713.108 323.054 34.634.462 466.578 -1.108 318.5% each month following the Revenue Department.462 -387.316 -323.574 2.242 2.841.933 -777.486 57.564 301.221 242.969 723.930 3500 270.744.282 191.185 723.854 201.584 1.516.619 -131.584 1.327 522.760 637.872 -127.242 2.108 314.200 4.235 -238. 2014 Oct Nov Dec Totals 652.289 57.133 0 13.917 180.242 2.664 242.622 0 53.372 0 53.426.664 242.108 318.474 -127.054 3.426.470 1.680 3500 261.470 1.462 -382.630 723.664 242.426.027 1.426.054 3.713.841.470 1.564 303.391 -1.107 386.024 536.108 323.498 -330.275 -4.426.470 1.713.713.038.526.038.713.193 3.426.221 242.387.027 1.654 200.470 498.664 242.462 -380.564 301.564 303.054 3.622 0 53.622 0 0 53.450.042 0 13.372 0 53.222 0 Note: Tax: According to our company is company limited.260.027 1.251 57.713.387.295 1.387.622 0 53.006.213 -442.930 0 261.584 18.230 11.700 3.782 195.564 303.564 303.426.054 3.584 1.622 0 0 53.308 2.584 982.387.841.038.668 -324.539 Jan Feb Mar Apr May Jun Jul Aug Sep Table 5-10 Income Statement.841.654 186.584 1.079 186.737 57.948 1.223.108 314.885.948 982.622 0 53.564 303.930 0 270.079 186.387.079 186.387.604 198.372 0 53.631.564 303.433 144.564 301.462 -62.982 196.732 193.841.242 2.295 1.242 2.354 185.054 3.054 3.622 0 53.730 200 270.038.224 57.664 242.298.539 34.526.948 982.564 301.242.130 57.104 -911.027 1.038.475 203.584 1.480 200 261.654 190.054 3.470 1.854 57.664 242.594 57.352 57.054 1.294 3.027 1.526.108 314.054 3.564 303.713.841.230 200 261.760 53.387.242 2.387.476 689.108 314.462 -380.242 2.762 523.027 3.948 982.332.462 464.462 479.426.054 3.060 711.P a g e | 148 Thai-North Rubber Industry Company Income Statement For Year Ended December 31.104 188.841.730 200 261.254 -136.426.426.027 1.) 1.242 2.841.426.584 1.
P a g e | 149
Table 5-11 Income Statement, 2015
Thai-North Rubber Industry Company Income Statement For Year Ended December 31,) 200 319,042 0 13,760 53,107 386,109 0 261,622 0 0 53,108 314,730 200 261,622 0 0 53,108 314,930 3500 270,372 0 0 53,108 326,980 200 261,622 0 53,108 314,930 0 261,622 0 53,108 314,730 200 270,372 0 53,108 323,680 3500 261,622 0 53,108 318,230 200 261,622 0 53,108 314,930 0 270,372 0 53,108 323,480 200 261,622 0 53,108 314,930 3500 261,622 0 53,108 318,230 11,700 3,223,133 0 13,760 637,294 3,885,887 3,768,659 3,768,659 3,768,659 3,768,659 3,768,659 3,768,659 3,768,659 3,768,659 1,884,330 1,884,330 1,884,330 1,884,330 1,884,330 1,884,330 1,884,330 1,884,330 3,768,659 3,768,659 3,768,659 3,768,659 3,768,659 3,768,659 3,768,659 3,768,659 37,686,593 37,686,593 Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Totals
2,025,830 242,564 331,817 2,600,212
2,025,830 242,564 331,817 2,600,212
2,025,830 242,564 331,817 2,600,212
2,025,830 242,564 331,817 2,600,212
1,080,443 242,564 329,857 1,652,864
1,080,443 242,564 329,857 1,652,864
1,080,443 242,564 329,857 1,652,864
1,080,443 242,564 329,857 1,652,864
2,025,830 242,564 331,817 2,600,212
2,025,830 242,564 331,817 2,600,212
2,025,830 242,564 331,817 2,600,212
2,025,830 782,564 331,817 3,140,212
20,528,412 3,450,768 3,973,968 27,953,148
1,168,448
1,168,448
1,168,448
1,168,448
231,466
231,466
231,466
231,466
1,168,448
1,168,448
1,168,448
628,448
9,733,444
782,339 183,465
853,718 181,713
853,518 179,943
841,468 178,156
-83,464 176,351
-83,264 174,527
-92,214 172,686
-86,764 170,826
853,518 168,947
844,968 167,050
853,518 165,134
310,218 163,198
5,847,557 2,081,995
598,874 94,139 504,735
672,005 94,139 577,866
673,575 94,139 579,436
663,312 94,139 569,173
-259,815 94,139 -353,954
-257,792 94,139 -351,931
-264,900 94,139 -359,039
-257,590 94,139 -351,729
684,571 94,139 590,432
677,918 94,139 583,779
688,384 94,139 594,245
147,020 94,139 52,881
3,765,562 1,129,669 2,635,893
-25,222
479,513
1,057,379
1,636,815
2,205,988
1,852,034
1,500,104
1,141,065
789,335
1,379,767
1,963,546
2,557,791
2,610,672
0
Note: Tax: According to our company is company limited. So, we must to pay the tax in rate of 30% per annual equal to 2.5% each month following the Revenue Department.
P a g e | 150
5.1.3 Balance Sheet
Table 5-12 Balance Sheet, 2011
Thai-North Rubber Industry Company Balance Sheet December 31, 2011 (Baht)
Beginning ASSETS Current Assets Cash Accounts Receivable Total Current Assets Non-current Assets Land Operations asset Administration asset Total non-current assets Total Assets LIABILITIES Long Term Liabilities Long Term Debt Income Tax Payable Total liabilities EQUITY Retained Earnings Total Equity Total Liabilities Equity
JAN
FEB
MAR
APR
MAY
JUN
JUL
AUG
SEP
OCT
NOV
DEC
8,346,958 8,346,958 6,450,000 7,598,060 2,604,982 16,653,042 25,000,000
6,800,026 598,465 7,398,492 6,450,000 7,564,210 2,581,041 16,595,251 23,993,743
6,030,925 1,196,931 7,227,856 6,450,000 7,530,358 2,557,101 16,537,459 23,765,315
5,334,969 1,930,534 7,265,503 6,450,000 7,496,507 2,533,160 16,479,667 23,745,170
5,225,729 2,065,671 7,291,400 6,450,000 7,462,655 2,509,219 16,421,875 23,713,275
4,942,887 1,969,144 6,912,031 6,450,000 7,428,804 2,485,279 16,364,083 23,276,114
4,794,182 1,737,480 6,531,662 6,450,000 7,394,952 2,461,338 16,306,290 22,837,953
4,636,727 1,505,816 6,142,543 6,450,000 7,361,101 2,437,397 16,248,498 22,391,042
4,253,358 1,505,816 5,759,174 6,450,000 7,327,249 2,413,457 16,190,706 21,949,880
4,068,591 1,756,786 5,825,377 6,450,000 7,293,398 2,389,516 16,132,914 21,958,290
3,875,274 2,007,755 5,883,029 6,450,000 7,259,546 2,365,576 16,075,122 21,958,150
3,700,956 2,278,030 5,978,986 6,450,000 7,225,695 2,341,635 16,017,330 21,996,315
3,234,307 2,297,335 5,531,642 6,450,000 7,191,843 2,317,694 15,959,537 21,491,180
25,000,000 25,000,000
24,891,323 0 24,891,323
24,781,558 0 24,781,558
24,670,697 0 24,670,697
24,558,726 0 24,558,726
24,445,636 0 24,445,636
24,331,415 0 24,331,415
24,216,052 0 24,216,052
24,099,535 0 24,099,535
23,981,853 0 23,981,853
23,862,994 0 23,862,994
23,742,947 0 23,742,947
23,621,699 0 23,621,699
0 25,000,000
-897,580 -897,580 23,993,743
-1,016,244 -1,016,244 23,765,315
-925,527 -925,527 23,745,170
-845,451 -845,451 23,713,275
-1,169,522 -1,169,522 23,276,114
-1,493,462 -1,493,462 22,837,953
-1,825,010 -1,825,010 22,391,042
-2,149,655 -2,149,655 21,949,880
-2,023,563 -2,023,563 21,958,290
-1,904,844 -1,904,844 21,958,150
-1,746,632 -1,746,632 21,996,315
-2,130,519 -2,130,519 21,491,180
P a g e | 151
Table 5-13 Balance Sheet, 2012
Thai-North Rubber Industry Company Balance Sheet December 31, 2012
3,261,126 2,393,862 5,654,988 6,450,000 7,157,993 2,293,754 15,901,747 21,556,735
3,378,631 2,471,083 5,849,714 6,450,000 7,124,142 2,269,813 15,843,954 21,693,668
3,495,935 2,548,305 6,044,239 6,450,000 7,090,290 2,245,872 15,786,162 21,830,402
3,677,911 2,548,305 6,226,215 6,450,000 7,056,439 2,221,932 15,728,370 21,954,585
3,591,814 2,123,587 5,715,401 6,450,000 7,022,587 2,197,991 15,670,578 21,385,979
3,505,917 1,698,870 5,204,787 6,450,000 6,988,736 2,174,050 15,612,786 20,817,573
3,411,071 1,274,152 4,685,223 6,450,000 6,954,884 2,150,110 15,554,994 20,240,217
2,896,457 1,274,152 4,170,609 6,450,000 6,921,033 2,126,169 15,497,202 19,667,810
2,666,265 1,698,870 4,365,135 6,450,000 6,887,181 2,102,228 15,439,409 19,804,544
2,427,523 2,123,587 4,551,110 6,450,000 6,853,330 2,078,288 15,381,617 19,932,727
2,197,331 2,548,305 4,745,636 6,450,000 6,819,478 2,054,347 15,323,825 20,069,461
1,930,761 2,548,305 4,479,066 6,450,000 6,785,627 2,030,406 15,266,033 19,745,099
23,499,239 -6,892 23,492,347
23,375,554 -13,784 23,361,769
23,250,632 -20,676 23,229,956
23,124,461 -27,568 23,096,893
22,997,028 -34,460 22,962,568
22,868,321 -41,352 22,826,969
22,738,327 -48,244 22,690,082
22,607,033 -55,136 22,551,896
22,474,425 -62,028 22,412,397
22,340,492 -68,920 22,271,572
22,205,220 -75,812 22,129,408
22,068,595 0 22,068,595
-1,935,612 -1,935,612 21,556,735
-1,668,101 -1,668,101 21,693,668
-1,399,554 -1,399,554 21,830,402
-1,142,307 -1,142,307 21,954,585
-1,576,589 -1,576,589 21,385,979
-2,009,396 -2,009,396 20,817,573
-2,449,866 -2,449,866 20,240,217
-2,884,086 -2,884,086 19,667,810
-2,607,853 -2,607,853 19,804,544
-2,338,845 -2,338,845 19,932,727
-2,059,947 -2,059,947 20,069,461
-2,323,496 -2,323,496 19,745,099
596 6.171.155 18.062 18.245.234 15.682 14.484 -1.450.567 4.686.718.450.306 2.318.818 20.363 .274.737 6.135 5.335.198 20.171.789 6.634.337 1.796 21.684.415 1.135 5.931 -1.803.709.010.353 6.477 21.785.845.135 4.505 2.293.129.367.544 15.025.467 73.294 98.000 6.092 20.192 5.248 4.657.602.620.536.934 1.178.390.788.494 20.764.668.053.386 19.864 -1.588.129. 2013 (Baht) JAN ASSETS Current Assets Cash Accounts Receivable Total Current Assets Non-current Assets Land Operations asset Administration asset Total non-current assets Total Assets LIABILITIES Long Term Liabilities Long Term Debt Income Tax Payable Total liabilities EQUITY Retained Earnings Total Equity Total Liabilities Equity 2.122.922.756 1.739 18.000 6.468.975 20.889. 2013 Thai-North Rubber Industry Company Balance Sheet December 31.043 -1.841.450.663 2.813 20.172.602.143 1.669 147.634.000 6.757 3.256 1.370 2.000 6.450.657.505 6.975 -1.200 14.450.508.848.803.510 14.000 6.510.352 1.079 1.955 21.403 -1.654 6.502 6.027 14.102 2.223 21.032.357.913 -1.420.303.450.585.855 14.628.352 -1.450.450.871.752.947.775.106.032.526 -2.655.364.710 20.840 1.949.472.128.603 24.567 3.062 15.845.840.592.135 4.977 -2.977 18.518 0 20.011.420.803.982 -2.272 1.955 19.338 14.555.789.560 19.821 1.014 1.290.043 2.785.350 2.441 6.719.793.791.585.450.560 -2.764.728 -949.800.178.536.672 -2.717 15.788.716 21.757 4.415 -1.526 18.602 20.076.313.000 6.490 2.681.950 1.102 -2.596 1.097 21.990.000 6.000 6.663 -1.728 20.734.929.885 1.211.450.858 21.067.484 19.401.401.518 -2.232 49.930.606 2.155 -1.055.450.997.603.653.955.864 20.000 6.239 21.931 19.325 21.073.274.650.524 20.363 FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC 21.000.954.909.574 20.969.606 -1.193 20.385 21.219.208 1.808.625 6.925.252.025.243 196.372 14.772 21.067.392 20.619 21.335.624.668.293.335 21.786.868.129.401 1.997.633.894.606.692 2.473 2.170 18.913 2.824 6.828.350 -949.869.868.456.000 6.468.640 6.522.609 1.771.489 2.708 2.695.609 -1.487.211.489.000 6.159.700 123.818 221.303.724.982 2.278 19.922.847 19.P a g e | 152 Table 5-14 Balance Sheet.684.803.419 6.422 19.597 2.403 19.946 5.357.884 -1.000 6.318.471 21.450.422 -2.189 172.884 20.743.283 20.423.672 2.212.926 19.889 15.946 4.899 246.471 270.
321.641.870 402.566.028.256.768.541.724 1.462 20.165 14.448 5.450.448 5.309 19. 2014 Thai-North Rubber Industry Company Balance Sheet December 31.898 6.361.978.083.233 19.000 6.956 2.083.402.691.156.712 -1.599.789 1.416 19.189 18.335.238.416.026 57.046 18.476 14.000 6.352 287.546.448 4.632 4.785 517.632 4.524 19.450.708.778.982 1.132 1.361 172.328 2.121 -1..156 2.055.488 0 18.771 19.614 14.820 14.991.450.189 -442.189.848 19.000 6.397 2.346.000 6.565 -777.378.569.083.391 18.450.433 19.156 37.466 1.726 574.081 19.561.707.841 2.222 -25.918 1.667.235 20.266 .132 -25.708.080 19.387.753 2.450.574.540 4.955 2.000 6.086 37.942 18.712 2.814 6.824.061.345 18.592.519.531 1.553 19.575.121 2.619 19.467.830.647.269 13.213 -911.004 1.131 14.000 6.006.225.316.522.203.055.242.488 -1.565 19.357.111 1.161 459.898.258.000 6.308 20.729 -442.086 19.240 -238.381 6.200 19.150.467.747 19.303 14.794.000 6.958 14.978.363.917.126.373 3.450.632 18.450.445 18.387.820.876 6.573 4.495 6.093.924 20.450 3.578 -618.984 18.876 18.529 6.000 5.644.578 19.192.824.606.861.092 19.574.240 2.000 6.728 6.176 1.155.000 6.097.525.103 19.469.966 632.687.220.120.163.357.291.144.266.222 18.314 2.196.235 144.450.747.006.189.152.648 14.005 19.324.061.726.626.329.990.484 3.102.083.722.856 18.768 18.030.386 20.104 -1.104 18.131 3.161 1.724 4.541.724 3.979 114.061.448 5.505.011 4.569.586.450.896.337 2.346.786 14.327 -1.343.592.903 19.061.088.088.729 2.933 6.327 18.314 144.000 6.847.993 14.488 20.489.242.853 1.029 6.047 1.706.995.961 6.005.261.822 6.450.727.687.157 19.595 1.433 -311.450.803 2.660 1.450.157 229.928 344.080 -238.152 1.P a g e | 153 Table 5-15 Balance Sheet.044.581 -618.213 18.391 -1.540 5.266 20.441 14.102.812.159.581 2.161 -777.580 6.211.246.310.337 -311.019.699 19.695 19.321.660 18.343.753 -911.661 19.
141.611 17.034 1.632.500.275 94.304.695.023 3.830.897 4.023 1.000 5.624 789.798 19.791 2.779..104 1.741.454.046.027 .344.379 1.452.968 2.815 1.704 1.065 1.234 13.183 1.131.735.000 5.414 17.418.366 19.205.311 188.450.549 6.082.513 18.083 3.792 3.230 4.826.000 5.027 18.885.693 1.458 3.157.065 18.988 20.465.141.062 13.174.672 2.619.628 1.698.450.578 564.065.797.011.752 13.826.139 18.938.582 18.505.809 2.962.932.034 19.791 19.437.739 6.735.665.114.695.951 1.256 16.734.735 753.049.647.314 2.354 2.672 18.601 6.988 2.775.764.863.370 1.151 18.096 13.014 20.450.000 5.896.384.000 5.927 2.437.660.391.890 13.335 789.948 6.057.380.450.557.876 6.589 17.734.586 6.957.405.530 17.989.705.847 16.391.963.474 18.391.155 2.832.239.379 19.929.968 1.894.870.230 19.200 13.556 18.932.494 6.636.806.314 3.354.355.994.793 5.450.425.122 19.599 3.104 19.306 1.902.000 5.335 18.445.744.450.687 6.793 6.485.672.278 18.513 479.906 19.183 3.196 5.834 17.834 1.635.458 1.289.505.567.560 16.822 1.494 5.035.319.196 5.241 1.546 19.725.355 0 16.355 479.171.423 17.379.577 282.545 13.364 16.815 19.566.P a g e | 154 Table 5-16 Balance Sheet.513.579 13.927 1.913.217.718 6.372 13.809 3.182.412 17.552 6.399.057 2.913.624 3.450.124.262.268.435 1.103 3.934 6.205.513.695 17.727 3.744.564 1.924 13.450.523 2.460.767 1.767 18.882.994 17.620.599 1.793 5.586 658.793 6.038 1.886 1.005 847.546 1.217.265.186.333.354.599.417 18.337 18.333.833.379.775.112 17.526.418.717 13.450.516 3.057.815.055 376.510.000 5.418.391.852.453 2.731.500.516 1.012 5.258 19.251 17.768 16.557.636.552.155 1.894 3.757 1.450.360 3.499 1.097. 2015 Thai-North Rubber Industry Company Balance Sheet December 31.923.690 18.000 5.610.963.407.973 17.852.000 5.407 13.610.364.590 6.450.450.261.239.261.000 5.896 6.000 5.882.324.728 470.390 17.124.897 5.000 5.223.438.378 941.
212 383.791 1.707 249.1.875.438.026 6.913 248.092 118.819 165.707 246.835 244.752 231.161 24.792 34.401 - 585.360 237.085 250.068.972 243.693.969 57.587 245.792 659.942.548 324. 2011 Thai-North Rubber Industry Company Cash Flow Statement December 31.717 80.564 4.592.664 90.275 57.254 598. 2011 897.429 237.730 96.958 7.465 57.859 4.719 158.792 169.360 238.985 6.887 5.456 209.995 173.465 57.969 5.527 57.951 3.458 270.816 247.137 57.222 242.727 4.225.456 244.971 3.071 323.633 .000 250.792 54.484 231.000 1.956 3.913 410.301.059.158.704 248.792 42.792 345.792 266.925 5.630 184.995.792 74.700.729 5.092 57.630 238.819 239.030.664 57.076 324.995 240.407 5.274 4.035 240.580 118.346.358 4.969 57.591 4.389.270 19.188.182 4.4 Cash Flow Statements Table 5-17 Cash Flow Statement.940 331.254 8.337 - 733.602 247.612.268 4.647 5.816 337.584.152.636.887 Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 598.233.161 242.P a g e | 155 5.910 239.587 75.429 107.404 4.314 201.334.792 135.644 126.792 2.253.094 - 67.692 4.424 6.427.603 57.794.800.437 245.664 57.305 57.278 246.852 - 250.792 250.314 243.
201 2.331 2.892 57.506 540.217 385.383.970 229.200 223.263.854.911 3.907 Feb 267.549 - 96.814 3.126 3.794 2.611 - 82.221 6.744 119.666.864.495.505.233 Oct 269.378. 2012 Thai-North Rubber Industry Company Cash Flow Statement December 31.950.434.320 .245 272.744 224.892 57.440.786.134 226.992 476.070 128.424.704 .052 .756 233.073.892 57.792 83.992 234.892 57.748 227.308 233.496 3.506 232.124.809 .547 Apr 257.937 3.255.491 229.717 6.982 3.148 - 6.221 6.717 4.591.247 May .804 234.254 236.434.071 3.523 2.898 Dec .683 263.226 - 6.189 - 77.217 236.792 35.245 231.792 41.527 6.717 6.470 Aug .511 Mar 268.595 228.917 3.424.810 - 424.416 57.807 Jul .892 57.104.427.791 149.024.581 3.892 57.281 Jun .424.383 227.317 222.737. 2012 194.307 3.792 242.717 6.892 57.717 6.346.052 222.265 2.261.896.130 .769.653 3.717 6.612 232.792 308.792 97.405 223.155.585 .036.457 3.432.336 - 424.892 57.831 3.942 224.147 - 424.683 228.781 3.567.970 272.P a g e | 156 Table 5-18 Cash Flow Statement.411.070 226.279 - 77.197.405 139.792 .234.935 4.182 3.486 2.756 475.619.009 Nov 278.892 57.792 241.631 3.892 57.677.383 .220 Sep 276.588 231.936 2.792 .792 42.
044 2.252 193.274 207.432 53.673 24.145.686 504.317 220.889 Apr 354.249 213.264 204.974 467.408.108 357.785 2.984 215. 2013 290.189 24.467.397 467.189 24.473 3.377 .619 53.167 219.197 212.686 220.585 2.487.293.467.108 431.732 .412 .844 2.467.414.840 3.407. 2013 Thai-North Rubber Industry Company Cash Flow Statement December 31.405 1.165.556 1.435.306 219.936 Feb 363.619 53.786.107 283.732 210.943 24.969 .493 Nov 376.041 1.652.129.652.306 3.489 2.108 138.725 204.619 53.223 - 84.619 53.647 352.252 209.619 53.108 136.189 24.912 217.479 2.189 44.108 183.645 2.897 24.197 343.076.108 130.155 Jun .247 May .930.118.108 .019 Aug .549 Oct 366.256 2.611 209.912 575.758 184.083 351.168.789.597 2.943 24.725 388.647 213.619 53.108 7.249 206.339 2.150 213.189 24.158.329.771.719 - 84.P a g e | 157 Table 5-19 Cash Flow Statement.708 2.517 212.094 2.152.761 467.505 648.934 210.789 2.479 - 84.758 207.293.108 22.619 53.596 2.182 216.943 24.108 15.307 295.761 2.934 2.954.313.913 .510.306 575.104 Sep 373.370 2.619 53.108 356.386 206.406.505 216.619 53.083 215.552 Dec .274 217.519 Jul .869.505 3.836 53.793.695 Mar 364.177.800.189 24.128.619 53.
561.106 185.959 - 93.156.917 293.234 689.681 - 191. 391.713 Sep 475.254 195.722.462 53.462 53.956 2.794.828 Feb 464.665 57.152.829 190.619 430.908 57.917 186.686 .438 57.357.513.618 188.908 57.081.813 Aug .474 198.200 865.450.004 2.254 439.387.462 53.162 196.450 2.108 .000.543 2.108 72.543 53.462 53.162 513.200 185.127 198.108 680.131 2.034 2.484 3.759 53.238 513.462 53.618 254.108 566.382.513.302 262.462 53.872 439.634 201.270.185 612.514.462 53.234 2.108 236.498 Jul .261.108 106.152 2.060 200.524 1.969 78.908 57.830.143 .518 195.324 1.155.060 683.920.908 57. 2014 Thai-North Rubber Industry Company Cash Flow Statement December 31.619 193.480 200.715.620.462 53.108 483.513.908 57.668 May .630 201.632 186.980 513.302 190.552 .890 Oct 469.304 2.284 2.908 87.474 764.894 - 93.252.144 1.308 - 93.864.854 2.108 242.108 65.132 Apr 455.264 57.108 481.969 191.462 53.926.275 - Dec 62.641.438 57.185 203.151 2.328 2.380.803 2.438 57.343 203.061.505.762 Mar 466.024 Nov 479.316 Jun .075 193.841 3.006 188.712 2.107 408.674 .515.108 243.490 1.462 53.P a g e | 158 Table 5-20 Cash Flow Statement.955 2.189.397 3.174 2.380.630 683.872 196.
826 33.108 358.5 Loan Loan Principal Amount Annual Interest Rate Year Now MlR =7.200 3.399.354 3.404 2.129.223.947 168.432 583.139 53.360 2.1.424.958 5.131.849 1.954 351.108 172.514.465 183.901 94.156 894.108 1.894 3.031 3.758.380 565.139 53.727 565.198 163.143 172.576 176.038 3.108 217.193 170.420 565.713 181.139 53.381 168.299 94.943 179.139 53.108 353.735 577.199 102.510.139 53.567.139 53.173 353.527 535.615 565.134 382.523 3.686 172.050 167.299 94.351 534.881 Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 102.436 569.782 94.299 94.777 165.103 4.050 332.000.139 53.044 179.664 181.037 1.373 1.75 % Loan Period in Years Monthly Payments 25.512.795 53.669 53.470 3.157.331 102.000 12.299 135.108 623.686 526. 2015 Thai-North Rubber Industry Company Cash Flow Statement December 31.235.453 3.351 176.107 549.00% 10 358.869.134 165.527 174.246.729 590.855 1.925.735 3.465 732.398.139 53.37 .656 3.507 94.943 803.108 204.581.490.065.677.139 53.713 804.931 359.947 341.327 167.P a g e | 159 Table 5-21 Cash Flow Statement.620.299 94.131 3.405.533.792 3.715 3.779 594.174.139 53.592 565.983 163. 504.826 170.979.657 183.057 3.482 565.571 2.108 165.156 178.436 3.866 579.245 52.108 716.516.039 351.108 622.114.046.198 1.108 360.782 94.704 3.727 2.844 178.943 174.782 94.299 94.
699.053 2.937.762 NOV 4.688 NOV 3.919 JUL 2.699.523.198 JAN 2.090.503 4.117 5.688 Sale.768.559 2.333.009.381 JUL 2.537.452 JUN 2.689.304.045.106 5. 2015 Cash Accounts Receivable Total Sale JAN 4.875.940 1.576.263.824 4.582 1.516.116 892.263.688 DEC 3.940 1.844 JUL 1.090.106 5.381 AUG 2.276 MAY 2.033.004.791 755.546.940 1.839 MAY 2.937.229 6.661.510.131.791 755.082.482.827.582 1.057 FEB 3.372.768.203.887 2.349.344.559 2.510.537.887 2.523 1.875.970 830.372.452 SEP 3.940 1.106 5.347.827.534 1.336 2.510.093 1.523.106 5.939 3.349.063.689.689.336 2.033.175 1.937.009.537.106 5.263.976 3.762 OCT 4.887 2.582 1.534 1.767 913.528 AUG 1.116 892.661.762 MAR 4.229 6.263.344.510.057 APR 3.349.537.699.117 5.256 1.839 FEB 4.559 2.057 MAR 3.009.970 830.614 3.537.338.546.523.528 SEP 3.827.004.761.057 DEC 3.952 6.053 2.875.678 Table 5-22 Total Sale of 5 years NOV 3.033.381 JUN 2.057 Sale.875.661.537.952 6.768.057 OCT 3.688 MAY 1.198 8.510.090.576.229 6.875.116 892.614 3.537.839 OCT 4.689.970 830.827.336 2.976 3.1.516.516.203.263.534 1.940 1.688 FEB 3.534 1.875.791 755.004.839 APR 4.827.080 Sale.117 5.461. 2012 Cash Accounts Receivable Total Sale JAN 3.033.349.523.827.974.123.767 913.6 Total Sale Sale.919 JUN 2.183 4. 2014 Cash Accounts Receivable Total Sale JAN 4.762 FEB 4.256 1.582 1.937.661.131.614 3.523 1.057 MAY 1.510.117 5.333.559 2.919 SEP 4.510.974.689.117 5.699.117 5.952 6.827.057 NOV 3.009.090.090.080 DEC 3.534 1.452 AUG 2.761.839 MAR 4.688 APR 3.063.116 892.090.263.661.974.678 OCT 3.824 4.528 JUL 1.887 2.123.462 FEB 2.582 1.462 MAR 3.944 1.944 1.523.452 JUL 2.082.263.229 6.761.689.131.229 6.009.009.461.381 SEP 4.131.952 6.117 5.875.043.976 3.875.762 DEC 4.045.844 JUN 1.338.952 6.523.106 5.534 1.033.276 APR 3.P a g e | 160 5.919 AUG 2.082.762 APR 4.528 JUN 1.336 2.944 1.183 4.768.839 NOV 4.839 DEC 4.689.082.944 1.791 755.582 1.347.043.699.045.534 1.614 3.229 6.093 1.033.767 913.582 1.053 2.839 .887 2.887 2.767 913.106 5.053 2.762 MAY 2.974. 2013 Cash Accounts Receivable Total Sale JAN 3.940 1.940 1.537.688 MAR 3.952 6.699.344.090.090.106 5.762 Sale.033.229 6.844 SEP 3.175 1.304.887 2.033.844 AUG 1.939 3.970 830.117 5.523.503 4.887 2.940 1.761.516.534 1.582 1.699.661.827.699.952 6.523.009.510.263.952 6.229 6.688 OCT 3.976 3.482.344.009. 2011 Cash Accounts Receivable Total Sale Beginning 8.045.689.661.661.004.
while money available today can be invested and grow.3.797 NPV > 0 This project we can accept. Consider both magnitude and timing of cash flows Indicates whether a proposed project will yield the investor’s required rate of return Disadvantage Many people find it difficult to work with a dollar return rather than a percentage return (Source:. because inflation erodes the buying power of the future money.2 IRR Internal rate of return (IRR) is a rate of return on an investment. IRR = 2 2 > 0.2.2 Investment Criteria 5.1 NPV (net present value) 5.P a g e | 161 . A dollar today is worth more than a dollar in the future.investopedia.1 NPV Net Present Value (NPV) is a way of comparing the value of money now with the value of money in the future.2.com/study-guide/cfa-exam/level-1/corporatefinance/cfa13.275.asp) 5.12 This project can be accept . The IRR of a project is the discount rate that will give it a net present value of zero. Advantages and Disadvantages of the NPV Method: Advantages Consistent with shareholder wealth maximization: Added net present values generated by investments are represented in higher stock prices. NPV = 128.
investopedia.2.asp) 5.pdf) . The IRR does not distinguish between a lending (investing) or a borrowing (borrow and invest) situation.edu.3 Payback period The payback period is both conceptually simple and easy to calculate.P a g e | 162 Advantages and Disadvantages of IRR Advantages People feel more comfortable with IRR Considers both the magnitude and the timing of cash flows Disadvantage Multiple internal rates of return with unconventional cash flows any change in sign (+.-) in period cash flows produces as many IRR’s as there are changes in the cash flow directions of the investment. It is also a seriously flawed method of evaluating investments.com/study-guide/cfa-exam/level-1/corporatefinance/cfa13. whereas the NPV clearly points out the negative aspects of the borrowing strategy (Source: year Advantages Measure of risk and liquidity Useful for evaluating small projects Disadvantages Ignores the time value of money Ignores cash flows after the payback period Objective not consistent with shareholder wealth maximization (Source:. Lending or borrowing. PB = 0.kfupm.sa/FINEC/mfaraj/fin301/notes/Ch7.
38 .00 62.00 75 80 67.00 138.00 1.P a g e | 163 5.00 63.12 1.29 1.00 58.19 1.2.4 Break-event point Table 5-30 Breakeven Point Break-even point Sales price RSS Sales price STR Low Cost High Cost Low Profits RSS Low Profits STR High Profits RSS High Profits STR Low Break-event point RSS Low Break-event point STR High Break-event point RSS High Break-event point STR Price per Unit 142.
P a g e | 164 Chapter 6 Risk Management .
All problems can be solved. If we look at those matters. Integrity Risk.1 Human resource Risks occur at any time. knowledge and education. The company can solve immediate problems correctly. and Technology Risk. For achieve the company's business. Our company operates by separate following characteristics of the risk. talent. we will be able to manage it. In terms of personal selection employee. There are Human Resources Product Development Efficiency Capacity Product / Service Failure Health and Safety Manufacturing Equipment Modernization Development of New Produces Changing in Business Practices The risks are often internal on the company such as 6.Risk Management 6. So the companies will be able to solve these risks is encouragement of the staff. Experience in working or through training before working. most of the risk occurs within the company. It must be developed and improved over time. it also therefore the Thai North Rubber company have the human resource management to more value in the organization. in this section we cannot know that how employees come to work such as Person Competency.1 Internal Analysis P a g e | 165 Risks within the Thai North Rubber company. So when we select the personal to working we cannot predict what is happening or will happen with each employee.1. The company has the Operating Risk. The . For this reason the company has difference the department. we can control but how risk can happen?. This is the most important of the reason.
Which may have Knowledge and ability to work according to plan or goal to the company successfully but to the various activities will be faced with the changes always on time? Under changing conditions changes to the new environment may be violent that exceeds the capabilities of the executives .1. Good the Weather and pollution. The last can make a job well. Along with maintaining equipment and care the equipment and related safety equipment for such as all of employees will receive health care.1.2 The limits of the employee All employees in the company would have limited the ability in the internal environment. That will lead to failure at any time in the practice these jobs. Therefore the executives should be interested in some details of the employees is important.4 Health and Safety The company operates for confidence to good health. 6. and has been helping.P a g e | 166 company's welfare when they get these things. and the employees themselves. a training seminar. Therefore. He will be expressed in terms of working in a better way. Risk management organization that will certainly have to face another variation is to change the economic. 6. social and political environment that may lead to failure as well. Each the positions are different mutual benefit. use of equipment to secure the places. Build the confidence to the employee and customers. Conditions of operation of the company to success or failure depend on the environment on economy.1.It would risk performing their duties. 6. the company has been certified safe. And get maximum satisfaction to the company. society and politics. including medical employees.3 Changing operating environment. which have to changing on always time. .
with exports accounting for more than two thirds of gross domestic product (GDP).P a g e | 167 6.2.th/businessnews.10 percent in March of 1998.co. Sometime a majority interest may be vested in the company's operators are foreigners (Host Country Enterprises) more than the business operators who area (Home Country Enterprises).php?id=409693) 6. For example. and generally pro-investment policies. From 1993 until 2010.10 percent in September of 1993 and a record low of -5.20 percent in the third quarter of 2010 over the previous quarter. Thailand's average quarterly GDP Growth was 0.2. in the last 20 years.2.1 Political Factor According to the form of politics has the potential to become important to the general business environment and domestic political institutions and political changes frequently and security instability that often cause no rules changes and most changes are often affected lack a stable image of politics in the support and plug pressure policy of government to channel the business sustainable. Thailand has changed the Prime Minister from the political party differences and how they are the party in the country at different so business in Thailand will need to review and analyze that thing happened and what will follow in the policies that affect both direct and indirect business organizations and their very often. Generation to make trade operators will also need to study and attention to factors that regulates international trade agreements such as to make free international trade and agreements are often the leading economic countries than any other segment. (Source:. Well-developed infrastructure. The economy of Thailand is an emerging economy which is heavily export-dependent.2 External Analysis 6.arip.2.1 Economic growth THAILAND GDP GROWTH RATE The Gross Domestic Product (GDP) in Thailand contracted 0. a free-enterprise economy. made Thailand one of East Asia's best .2 Economic Factor 6.97 percent reaching an historical high of 7.
Office of National Economic and Social Development Board) Gross domestic product at current market prices valued at 2. Exhibit 6-1 GDP Grow Rate Country Interest Rate Growth Rate Inflation Rate Jobless Rate Current Account Exchange Rate Thailand 2. This page includes: Thailand GDP Growth Rate chart.1 billion baht.80% 1. eroded investor and consumer confidence.20% 2. After deducting 153.4 billion baht in 2Q2010. historical data and news. After incorporated net factor income and net . However. 2010.8% in real terms. rising at the rate of 6.25% -0.7 billion baht.3 billion baht of net factor income from the rest of the world.494.341.P a g e | 168 performers. the gross national product (GNP) registered at the value of 2.0300 Figure 6-1 QGDP Grow Chart (Source: Gross Domestic Product: Q2/2010. Balance of trade and services at current market prices registered a surplus with the value of 158. overall economic growth has fallen sharply in 2008 and 2009 as global downturn and persistent political crisis stalled infrastructure mega-projects.20% 2909 31. published August 23.
producer price index and consumer price index increased by 9. As economic growth is measured as the annual percent change of National Income it has all the advantages and drawbacks of that level variable.8% in previous quarter. GDP implicit price deflator in 2Q2010 increased by 3. the amount of growth may be overstated once we take pollution into account. But people tend to attach a particular value to the annual percentage change.0 billion baht.e.3% compared to 12. i.3% and 3. The real GDP per capita of an economy is often used as an indicator of the average standard of living of individuals in that country.P a g e | 169 current transfer from the rest of the world. there are some problems in using growth in GDP per capita to measure general well being.8% compared to 4. Economists have developed mathematical tools to measure inequality. In economics. GDP per capita does not take into account positive externalities that may result from services such as education and health." which is caused by growth in aggregate demand or observed output. GDP per capita excludes the value of all the activities that take place outside of the market place (such as cost-free leisure activities like hiking). it should always be viewed merely as an indicator and not an absolute scale. such as the Gini Coefficient.0% and 3. and economic growth is therefore often seen as indicating an increase in the average standard of living. respectively. i. GDP per capita does not take into account negative externalities from pollution consequent to economic growth. or GDP. perhaps since it tells them what happens to their pay check. Thus. thus.GDP per capita does not provide any information relevant to the distribution of income in a country. current accounts showed a surplus with the value of 42. It is conventionally measured as the percent rate of increase in real gross domestic product. Economists are well aware of these deficiencies in GDP..e.5% in previous quarter. inflation-adjusted terms.)The flaws of GDP may be important . production at "full employment. "economic growth" or "economic growth theory" typically refers to growth of potential output. Growth is usually calculated in real terms. Economic growth is the increase in value of the goods and services produced by an economy. in order to net out the effect of inflation on the price of the goods and services produced. However. Meanwhile. There are also alternate ways of measurement that consider the negative externalities that may result from pollution and resource depletion (see Green Gross Domestic Product.
deliver. the differences in the annual growth from country A to country B will multiply up over the years. the second only by 80% A Factor of stable economic environment and impact on business opportunities and threats that include economic stability inflation interest rates of tax rates. the first economy would have grown by 165%.2.com/Economics/GDP-Growth. where the exponent is determined by the PPP annual GDP growth rate. services. Understanding the role that technology plays in enabling core business operations establishes the framework for understanding where relevant technology risks lie. Technology enables key processes that a company uses to develop.aspx?Symbol=THB) 6. and manage its products.3 Technological Factor Technology Risk Technology permeates the operations of an entire institution and therefore technology risk cannot be compartmentalized as a process that focuses on a particular area. and support operations.tradingeconomics. . and total revenue per household. a growth rate of 5% seems similar to 3%. GDP) because GDP is a factor that led to economic growth is and what impact the power consumption (Purchasing Power) of the population as a whole in any direction Entrepreneurs must understand that before the economic environment has the potential to be both positive and negative to which the company will success of failure of strategy of the company as well or used as a key business opportunities or obstacles. for the purposes of economic growth in the long run it tends to be a very good indicator. Policy changes and economic problems government policy to create economic stability (Including the policy to support export and import goods from foreign countries. however. income distribution. Thus. (Source:. follow Economic growth is exponential. There is no other indicator in economics which is as universal or as widely accepted as the GDP. Growth of the population labor market and unemployment rate.P a g e | 170 when studying public policy. but over two decades. Growth of the industry is important currency exchange rates between countries. For example. respectively) and that the majority of attention is products in the initial (Gross Domestic Product.
allaboutrisk. Once these risks have been identified. company management is in a better position to determine the relative importance of these functions and prioritize the systems. (Source:. an appropriate technology risk management strategy can be developed and implemented. Identifying vulnerabilities and threats provides company management with a view of the risks faced by the company given the enabling role of information technology. and data involved.P a g e | 171 By understanding the role that technology plays in supporting various business functions. Technology risks are present throughout the company and must be addressed as a whole.com/technology_risk/index.asp) . applications.
P a g e | 172 Chapter 7 Conclusion .
Chiangkhong district. Our project business is a factory of rubber which has many types for sale. We also provide with only Rubber Smoked Sheet and Block rubber product. political risk. are relate together. Thai-North Rubber also has policy to production with higher quality and tries to develop standard and quality of basic processing rubber to meet the demand as much. respond the higher demand in Chinese market.45% of 4% of North export in Thailand and increase 10% every year. there are 2 mainly zone which are administration zone and one for Manufacturing zone for production in all of 2 products. increasing in demand of rubber in China and growth rate of rubber plant in Chiangrai each year. mainly in higher class of rubber which are RSS1 (Extra light color).000.000 baht that we will offer the interest rate about 12% per year and will pay all of the interest rate at the end of year 5 that we guarantee the all of principal of the investor by we have the backup plan for the investor In the financial analysis that represent in 3 financial statement. Thai-North Rubber Industry have strong in the financial status that also represent in the ratio analysis. STR 5L. We found with many information can be support for market feasibility of this project like which the higher number of rubber export in Thailand. STR 5 and STR 5CV**. Thai-North Rubber Industry is register as the company limited according to the Department of Business Development. STR XL. Thai-North Rubber has a strong in the financial status that also represent in the ratio analysis. it can be acceptable because we also cope with this risk from using the risk management. We buy the land and need to build our building.. . RSS2. RSS1. And the sale forecast feasibility of the potential market. operating risk and etc.P a g e | 173 Conclusion Thai-North Rubber Industry is the rubber processing project that operates in Chiangrai province. although we have the many risk which is the economical risk. The North of Thailand is possible for this project to make a higher profit in rubber industry. We find out the source of funding from the investor 25. Thai-North Rubber Industry can generate sale 0. We focus our product directly to only one main target with China (Specialization Market).
asp Department of Local Administration.thailocaladmin..sa/FINEC/ mfaraj/fin301/notes/Ch7. Retrieved 4 Jan.d.bot. (n. Port Authority of Thailand.allaboutrisk. 2010.edu.) About Chiang Khong. (Oct 28.go. 2009) China Rubber Tires Market and Industry.co.kfupm.international.suite101.co. (n. Retrieved 27 Dec .) Technology Risk.th/english/statistics/ financial markets/interestrate/_layouts/application/interest_rate/IN_Rate.d) Tax labels Retrieved 27 Dec. 2011 Website:. Retrieved 16 Jan.co. Becoming No. 2010 Website:. (n.com/content/china-rubber-a163348 Chiang Khong Port. (n.) Chapter 7: Net Present Value and Other Investment Criteria.rubber. 2010 Website: www.) Tariff.manager. from Economic History Services Website:. Retrieved 5 Jan.th/ckp/eng/dataset5/data1. (31 Jan. Retrieved 4 Dec. Website:. (October 18. (n. 2010) the International Natural Rubber Market.port. Ltd.co.pdf . 4 in the Thai capital larger Thai-China prepare to set up processing plants. Retrieved 5 Feb. Retrieved 27 Nov. Retrieved 5 Dec.d.asp Bank of Thailand. 2011 Website:. Ministry of Interior.th/land-info-top-3. (n. Zephyr Frank (Stanford University) and Aldo Musacchio (Ibmec SãoPaulo) (February 1. 2011Website:. 2011 Website:. Retrieved 4 Jan .pdf Department of Lands. Retrieved 15 Jan.aspx CETECH Group Co.cetechgroup.html Chiang Khong Port.th/ckp/eng/dataset1/data2. 2010 Website: Anonymous.market Allaboutrisk. 2010) Rubber plantations through the city Peakun implying million hectares.Reference ASTV Managg Online.html College of industrial management. 1996) Deposit Rates for Individuals of Commercial Banks as of 17 January 2011.2010.) Cost/Detail of Sentry Box. (2006) Charges at the Land Office if the Registrar.land.th/Local/ViewNews.th/work/e_book/eb5/eb5_2/tax1. Port Authority of Thailand.d.php Chen Nanyang.d.port. 2010 Website:. 1870-1930.net/encyclopedia/article/ frank.co.th/products.2010 Website:.
) Rubber History. SMEs Retrieved 5 Feb . (n.d.2010 from Prince of Songkla University Website:. from eHow Contributor Website:. 2010.th/businessnews.2011 Website:. Retrieved 28 Dec .go.org/ loans/npv.html Economic Research and Training Center.2010 Website:. (September 3.org/public/activitiesrubberh. 2010.ac. (n.O.d. Retrieved 27 Dec. Retrieved 12 Dec.phtml .d.) Calculate Electric Expense. (n.etrma.ac. 2010.th/node/947 DPU International College.th/ertc/php/ FinAid.htm Elizabeth Pace.ehow.php?option=com_content&task=view&id=817&Itemid=303 Department of Industrial Works.) Rubber History. (n.) Trans-Asian Railway network Thailand. from THE RUBBER ESTATE ORGANIZATION Website:. Retrieved 4 Dec.econ. 2011 Website:. 2010 Website:. (n. 2010 Website: facts_6920005_history-rubber-manufacturing-industry-china.ac.reothai.go. 2006) TIP business management Resources and business environment.) Net Present Value. from European Tyre & Rubber manufacturers’ association Website:.) Fire Insurance.d.dpu.Department of Intellectual Property.th/ ipthailand/index.psu.) Rubber Industry.d. Retrieved 5 Jan.php Dhipaya Insurance Public Company Limited. Nattapol Nimmanpatchalin. Retrieved 6 Jan. Retrieved 28 Nov. SMEs the things that operators should focus in present no. 2010) History of the Rubber Manufacturing Industry in China.th Dr.) PSU researchers Rubber production test. Director of Analysis and Warning SMEs Sector Office of Small and Medium Enterprise (SME National Awards).co.arip . On fees and fee waiver for a patent or petty patent Act 2004. Retrieved 16 Jan.asp Dr.php?id=409693 ETRMA. (16 Oct.2010 Website: R. (2004) Ministerial. Retrieved 4 Dec. (n. Resolve the loss of plant products. (n.co.th/Para1.d.ipthailand. 2011 Website:. (n. Retrieved 28 Dec . Virairat Chevasattatam.diw.tu.th/I_Standard/Web/pane_files/Industry12.d.
Retrieved 4 Jan .2010 from ImportExport Website: on the free trade of fruits and vegetables.htm Metropolitan Waterworks Authority.d. Retrieved 11 Dec . 2011 Website:. (20 June.) Calculate Water Expense.Furniture Media Architects Inc.com/ Geojit Comtrade Ltd. Retrieved 5 Dec . 2010) Public Warehouse Cost.2010 from The China Post Website:.) Cost and Detail of Office Supply.2011 Website:. 2010 Website: www. (n. (n.2010 Website:. (n.d.) CFA Level 1 .valuenotes.th/fruitolympic/freetrade.thaichina. Retrieved 11 Dec .2010 Website:. (19 December.d. (n.) Cost and Detail of furniture. (n.th/water_calculation.asp Infinity Office Supply.Advantages and Disadvantages of the NPV and IRR Methods.investopedia. Retrieved 5Feb . Retrieved 5 Jan . (n.html Kasemsiri Furniture Ltd. Retrieved 4 Jan. 2010) Retrieved 5 Jan.d.mwa.) Rubber/Rss.or.com/en/blog/item/27/ kunmingsingapore_rail_link_by_2015 Investopedia.co.arch56.. (n.d.com/study-guide/cfaexam/level-1/corporate-finance/cfa13.d. ( 23 August.aspx?c=2&d=117291&p=4 Marketing Organization for farmers. 2010) Natural Rubber: Will the Rally Continue? (pp 2).techno.com/news/news_thailand_ detail. (13 January. 2010 Website:. Retrieved 11 Dec.2011 Website: KS Group the industrial service.2011 .2010 Website:.) Kunming-Singapore rail link by 2015?.th/office/import-export/rubber-rss.mof. 2010) Gross Domestic Product: Q2/2010.html Office of National Economic and Social Development Board. (n.co.ksgroup.. Retrieved 28 Dec .d.d) Cost and Detail of furniture.com/geojit/geojit_ RUBBER_13Jan10.pdf GoKunming. Retrieved 16 Jan. Ministry of Labor Economics and Commission wage.com/?tag=public-warehouse-cost Ministry of Labor. Retrieved 28 Dec. published.) Thailand .2011 Website: Logistics.
d) Product/Service.2010. And other fees associated with the partnership and limited company Act 1906.aspx?id=1034&content=00262 .th/menu5.org Website: Rubber Research Institute of Thailand.asp?id=287 Rubber Research Institute of Thailand. Retrieved 4 Dec . Retrieved 4 Dec . 2006) Ministry of Law. 2011 Website: Provincial Electricity Authority. 2011) Auction price and Quantity Retrieved 12 Dec.com/RWmarket_report. Request literature review .2010 Website:. 2010 from FarmKaset.(30 June.pwa. The registration fee. Deputy Minister of Agriculture (February 18.com/Rubber_Marketing_ Research_. 2009)Natural Rubber Supply and Demand forecast and price Outlook. (n.Office Of the Rubber Replanting Aid fund.com/statistic/stat_index.) Thailand rubber price.html Precha Lahapongchana.rubberworld. Retrieved 26 Dec. Insurance.perfect-broker.th/service/newuser. (8 May.th/th/services/services_fee_rates.rubber.co. Retrieved 27 Dec ._Asia Rubber World Magazine.d) Auction price and trading volume of rubber at central rubber markets.2010 Website:. Request a copy of the document with the guarantee.htm Rubber Research Institute of Thailand.) Rubber Marketing Research-Asia. (31 January. 2010 Website: Perfect Broker Ltd. (2010) Cost of request Electric and Water. Retrieved 26 Dec. 2010 from Department of Business Development Website:. (n.co.htm Provincial Waterworks Authority.pea.d. ( n.htm Supachai Posu. from Market report for the rubber industry Website:. Retrieved 4 Jan . (n.2010.) Thailand's natural rubber production.d.co.2010 From The applicant to install a new water supply must following Website:. Retrieved 26 Dec .com/ price/price_index.th/ mainsite/index.rubberthai.2010 ) Ministry of Agriculture believes in 2010 is the great opportunity of Thai rubber that regain following demand of world market. 2010 Website:. (n.php?id=1638 ResearchWikis. Retrieved 6 Dec. Retrieved 26 Dec . from Organizing The World’s Research Website:. (2010) Fees Rate for using water. 2010 Website:. Retrieved 12 Dec.
2011 Website: from Sri Trang Agro-Industry Plc. (n.Leadership/Thailand-Salary-Guide/Adecco-Thailand-Salary-Guide-2011. Retrieved 11 Dec .php Second Market Bannok.56/func.viriyah. (2 April. (28 September.com/component/option.php?detail=stat-thai Thai Hua Rubber Public Company Limited.view/id.adecco. Retrieved. 2010 Website: Social Security Office. Website:. 2009) Product.com/th/index. Retrieved 10 Dec .com/th/ page/20_products2. International Quality. Retrieved 4 Jan.d. (8 December.d. 2007) Thailand GDP Growth Rate.co.com_ fireboard/Itemid. The world’s largest exporter of latex concentrate.2010 Website: Website: Topvictorystar.thainr. Retrieved 4 Jan .) Thai Rubber Statistics.php Thai Rubber Latex Corporation Public Company Limited.com/ Trading Economics.tninsure.thaihua.d.2011 Website:. Retrieved 4 Jan .thaitexgroup.th/uploads/Knowledge-CenterThought. 2010 Website: Thailand Lawyer Center. 2011 Website:. . 2010) Sale Good land in Chiang Khong district.d.com/v4/en/corporate/corporate-profile. (n. (n.d. (n. Retrieved 28 Dec.tradingeconomics.2011 from Adecco Group Thailand Website: Website:. 1992) Factory Act 1992.topvictorystar.aspx? Symbol=THB .php?lay=show&ac=article&Id=573945&Ntype=2 The Viriyah Insurance.php?lay=show&ac=article&Id=538974919 &Ntype=19 Tidarat Kanchanawat. Retrieved 12 Dec. (2011) Thailand Salary Guide 2011. (n.2010 Website:. (n.68072/catid.) Machine insurance.d. Retrieved 4 Jan .) FBT Traffic Cone.SRITRANG Group.th/ Tninsure.baanok.d. Retrieved 10 Dec .) Welcome to Thaitex Group.) Car Insurance.) Social Security Insurance.) Corporate Profile. 2011 Website: The Thai Rubber Association. Retrieve27 Dec. (n. (January. Retrieved 4 Jan.
Retrieved 11 Dec.org/wiki/Chiang_Rai_Province Yong Fong Machinery Co.wikipedia. the free encyclopedia Website: from Wikipedia.org/wiki/People%27s_Republic _of_China#cite_note-Ref_b-14 Widipedia. (n. (n..) People’s Republic of China.doc&rct= j&q=analysis%20financial%20ratio%20.com/index.co. Retrieved 10 Dec .2011 Website:.) Cutting Machine.doc&ei=JlVATfC7EsOsrAfto7HPAg&usg= AFQjCNG0ijqAZ3nH-_q0kxPUQgyo-n_SwA&cad=rja Widipedia.) Technology. (n. Retrieved 5 Dec.) Financial analysis of business Statement. Retrieved 15 Jan .d..2010 from Info Comm Market Information in the commodities area Website:. Ltd.th/url?sa=t&source=web&cd=1&ved=0CB8QFjAA&url =http%3A%2F%2Fvictoryrisk. (n. the free encyclopedia Website: .2010 from Wikipedia. 2010 Website: VictoryRisk.d.yongfongthai.unctad.UNCTAD. (n.google.) Chiang Rai Province. Natural rubber (NR) processing into different rubber categories Rubber goods (RG) manufacturing.org/infocomm/ anglais/ rubber/technology. Retrieved 28 Dec.com%2Fimages%2FFinancial%2520Statements.
392.891.000 24.182 4.074.344 6.539 2.677 358.863.630.558 24.209.794.433 128.979.364 668.632 23.397 3.445.483.677 358.677 358.744 223.465 1.044 3.543 4.930.594 145.954 2.216.738.217 234.334.875.677 358.378.Appendix Table Loan Repayment Cumulative Cumulative Principal Interest 108.677 358.859 120.862 111.023 1.913 247.231.006.205.415 24.925.650.481 147.303 441.340.274 554.677 358.677 358.461 22.398 2.766.101 4.967 2.677 358.587 244.131.913 746.922 126.897.981.768 3.161 240.780 2.677 358.780.070 224.257.137.272 136.621.147 1.533 3.383 226.595 21.706 3.948 900.677 358.624.677 358.947 23.000 248.349.368 1.775.677 358.580 5.677 358.677 108.069.677 358.677 358.575 2.252 207.491.607 133.245 229.612.635.700 21.517 117.768 2.187 7.026.094.761 1.757 4.997.073.248 122.000.683 227.992 233.697 24.791.300 3.991 139.375.553.676.500.912 216.780.197 4.799 5.764 110.261.930 8.677 358.197 210.508.239 23.294 132.364.460 123.219.508 2.677 358.331.852 5.099.677 358.677 358.677 358.405 222.933 135.994 23.371 140.162.673 2.506 231.052 220.726.853 23.949 2.442 329.699 23.585 783.535 23.239.682 118.991 7.479 1.323 24.172 7.375.677 358.677 358.781.402.625 137.047 121.685 124.436 1.862.677 358.677 358.220 22.018.749.827 3.899 Payment Principal Interest 358.429 236.243 20.677 358.363 116.006 1.425 22.314 242.688.179 Year 1 Month 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 Balance 25.033 22.931.677 358.232 21.324.173 143.505 215.527.425 150.819.558.919 7.742.994 131.868.474.650 5.607.758 206.677 358.926.677 358.052 24.677 358.446 1.647 212.844 6.525.811 4.636 24.192.331 3.970 113.397.053 1.819 238.499.294 21.729 993.261 6.249 2 3 .189 20.707 129.659.454.670.002.428 250.395 5.816 246.037 3.221 115.677 109.554 23.732 209.250.624.301 1.968.083 213.467 21.756 6.925.030 146.321 22.677 218.327 22.972 2.000 498.306 217.630 237.677 358.945 149.124.551.919 152.677 358.677 358.529 250.765 142.818 20.603 21.679 2.449.686 219.538 6.171 127.028 22.456 243.707 245.090 114.794 1.995 239.513 4.116.299 4.208.792 3.068.726 24.669 21.677 358.677 358.756 232.970 228.405 3.224.492 22.
073.527 172.677 358.492 157.327 184.668 12.856 Cumulative Cumulative Principal Interest 4.467 10.785 18.965 10.627 193.677 358.047 158.779 9.717 12.283 12.735 16.117.231.306.483 14.375 14.034 6.089 8.578 17.730 191.215 231.728 17.488 18.318.588 138.021 5.124.479 197.423 7.198 161.046 13.875.677 358.159.677 358.514.407 136.677 358.271 222.005.416 205.105.994.058 166.717.834 16.173.400 13.785 13.488.680.885 10.543 13.671 13.414 8.351 174.965 178.171 14.510 13.424 165.731.377 9.241 12.847.677 358.159 14.748.299.677 358.727.653.677 358.316.525.969.870 19.840.734 180.408 201.274 6.002 144.026 20.545 14.618 186.485.278.547.581.156 11.240 11.522 182.976.507 233.677 358.677 358.228 12.050 165.677 358.079 9.806 163.677 358.677 358.272 7.677 358.994.580 211.686 170.677 358.023.582.629 11.806.946.166.909.793 215.474 196.992 187.200 183.979 131.463 127.471 20.005 16.927 13.090.941.847.228.677 358.184.677 358.619.811.677.434.171.720 15.715.474.928 19.512 6.176 14.677 358.836.434 199.839 6.319.719 8.445.799 12.190.156 176.179 11.677 358.943 178.917.677 358.644.698 226.172 149.462.511.005.526.260 8.212 176.861.267 10.931 12.111 15.803.930 218.809.060 198.513.921 15.149.312.138.878.311 17.725 203.677 358.422 7.677 358.615 12.739 14.157 19.677 153.090 220.882.481.185 201.252 9.665 12.872 195.230.397.700.244 159.732 129.577 17.894.122.465 181.282.361.619 191.677 358.677 358.843 5.505 209.544 195.355 15.275 17.756 10.086 14.329 11.903 8.822 204.294.122 11.802 10.082.681.429 14.452.926.980.261 10.072 5.286.274.269 157.638.677 358.278 11.519.097 147.852 189.450 207.677 358.426.842 11.575 5 49 50 51 52 53 54 55 56 57 58 59 60 6 61 62 63 64 65 66 67 68 69 70 71 72 7 73 74 75 76 77 78 .826 168.677 358.108.760 173.517 10.725 7.997 12.486.376 170.478 175.677 358.635.677 358.677 358.635.945 7.677 358.275 155.677 358.676 213.472.979 19.630 200.677 358.265 8.227 151.513 15.053.746.261 153.244 14.687.928.725.620.917 185.760 13.705.965.772 12.677 358.586 16.677 358.747 140.130 5.364.974 4.677 358.889 9.677 358.273 13.689 7.473 224.204 133.002.124 9.379.480.103.302 188.695 15.709 168.487 9.677 358.163.268.361 19.562 Payment Principal Interest 358.196.691 14.997 9.563.969 190.352 19.Year 4 Month 36 37 38 39 40 41 42 43 44 45 46 47 48 Balance 20.945 229.826.637.150 185.204 161.171 124.841 10.618 160.600 11.402 203.305 9.060 171.815.152.069 12.828.438 12.166 8.835.953 155.549 15.677 358.731.482 4.308.691.885 142.473.272.034.073 11.648 5.645 9.346.378 16.161 18.677 358.215 6.058.947 167.030.966 18.322.518 20.002 10.377.354 14.134 163.055 17.254 193.309 10.713 179.602.995 8.639 5.431.764 14.446 13.622 8.677 358.726 18.677 358.
478 17.111 268.653 17.851.047.415 17.721.814.902 20.677 358.677 358.677 358.677 358.641 43.491 324.997 10.173 19.733 18.597 17.201 92.963.450.677 358.761 78.445 24.683.927.521 40.294 16.549 7.677 358.141.550 17.269 17.467 17.451.876 17.403 16.990.899.689 253.476 266.003 14.156 117.036.036 315.733 6.786 58.707.294 23.950 100.537.222.236.292.731 15.549.868 263.294.242 16.547 1.960.579 5.714 18.794 17.677 358.035.682 348.349 17.960 17.641 8.143 3.269 344.118.119 14.484 2.677 358.724 27.421 19.545 337.218 84.453 23.798.408 13.677 358.736 355.100.525.935 17.677 358.164 13.503 81.298 8.797 16.892 299.952 296.790 49.807.941 13.233 334.971 30.725 61.176.633 17.644.727 258.677 358.947 312.580 11.019 15.927.269 9.677 358.705.020.160 291.442.888 308.548.818 52.758 8.581.171 16.042 293.087 10.420 13.463.206 250.772 271.677 358.704.037.370 70.152 11.312 19.821.380.836 11.369 37.948.418.160 238.823.984.677 358.192 10.195 255.032 20.427 18.174 276.134 4.076 16.817.718.881.381 15.952.666 18.397.264 24.471.890 341.688 5.251 2.272.677 358.517 120.677 358.470 16.201 16.677 358.000.352.517 67.195 73.771 115.866 20.685 282.625 17.634 3.530 8.413.040 7.551 Cumulative Cumulative Principal Interest 12.558 17.527.749 248.281.278.677 358.563 22.059 11.677 358.942 3.604 16.774.810 95.Year Month 79 80 81 82 83 84 Balance 12.030.520.000 15.469 18.677 358.921.135 24.677 358.634.026.081 4.973.953 331.285 8 85 86 87 88 89 90 91 92 93 94 95 96 9 97 98 99 100 101 102 103 104 105 106 107 108 10 109 110 111 112 113 114 115 116 117 118 119 120 .967.117 18.731 46.201.827 5.677 358.662.988.015.916 279.919 20.743.307 288.677 358.244.058 21.985 9.531 6.777.404.124 7.989 105.677 358.516 22.677 236.256.780 17.677 358.706 327.860 302.051.098 4.619.865 706.817 55.186 33.054.041.126 Payment Principal Interest 358.589.251 16.968 4.072.885.593 16.745 17.184 23.780.943.677 358.769 16.730.208 7.720.466.116 17.647.344.600.362 112.093 15.293.749 22.308 321.472.792 17.006.577 17.267 18.913 14.763.522 7.536.117 9.677 358.927 17.848 13.677 358.664.471 107.335.067 3.891.309 15.636 64.857 21.479.156 318.630.602.009.393 97.039.351.702 16.202.285 260.916.677 358.259.677 358.973.366 21.740 12.249 15.482 102.126 122.460 274.881 10.677 358.178.133 20.316 245.677 358.340.677 358.816 1.787 17.610 355.522 240.337.015 15.482 285.740.883 15.677 358.992 76.359 16.808 14.122 18.874 25.251.945.744.078.780 16.677 358.255.586.437 2.219.581.677 358.677 358.995 10.677 358.706 1.129 351.677 358.128.928 110.677 358.905 87.399.573 6.052.859 305.566 89.994 17.677 358.205 17.907 243.278.721.098 17.
6250 6.4000 7.5015 15.0000 15.5838 11.2500 6.0000 6.1000 22.8750 7.1638 6.6200 6.0000 7.5000 7.Daily interest rate of commercial banks Loan Rates Commercial Banks as of 17 January 2011 Bank Commercial Banks registered in Thailand Bangkok Bank Krung Thai Bank Kasikornbank The Siam Commercial Bank Bank of Ayudhya TMB Bank The Siam City Bank United Overseas Bank (Thai) Company Ltd.0000 24.7500 8.0000 25.0000 28.5000 6.0500 7.0000 28.6250 6.3750 6.0000 20.0000 28.5000 6.0000 7.5000 7.0000 7.0000 28.0000 35.0000 20.0000 12.3750 7.0000 6.1250 7.0000 20.0000 28.0000 18.0000 28.0000 28.7791 7.3750 MOR MLR MRR Ceiling Default Credit Card .1500 7.0000 20.0000 7.9800 6.0000 18.8750 28.0000 35.0000 28. CIMB THAI Bank Standard Chartered Bank (Thai) Thanachart Bank TISCO Bank Mega International Commercial Bank Kiatnakin Bank Land and Houses Retail Bank Industrial and Commercial Bank of China (Thai) The Thai Credit Retail Bank Average of Commercial Banks registered in Thailand 6.0000 18.0000 8.3750 11.3750 6.1000 7.0000 20.0000 20.0000 21.5000 6.2500 8.3700 6.3750 6.0000 7.0000 21.3750 7.9950 7.0000 8.7300 7.0000 28.0000 21.0000 7.5000 7.4800 7.0000 19.0500 19.1500 7.0000 28.7500 6.0500 22.0000 15.9000 7.0000 24.0000 6.9000 6.0000 22.5000 7.0000 21.5000 14.3750 7.5000 8.2971 20.6250 6.7500 8.0000 28.2500 6.0000 15.6300 6.0000 28.0000 28.
7639 25.2500 22.0000 25. JP Morgan Chase Bank Credit Agricole Corporate and Investment Bank Bank of America.0000 19.0000 13.0000 7.5000 13. 2005 Exclude Interest rates of Personal Loan under Supervision " .0000 50.aspx#) .5804 6.m.2500 8." means no service for this type of transaction.0000 20. RHB Bank Berhad Oversea Chinese Banking Corporation The Bank of China Mizuho Corporate Bank.0000 20.6300 15.5000 8.5000 7.2500 9.0000 7. Ltd.2500 7.8750 8.7500 8. MOR =Minimum over draft rate.0000 7.5000 9. BNP Paribas Average of Foreign Bank Branches MOR MLR MRR Ceiling Default Credit Card 10.2500 8.00 p.0000 7. MRR=Minimum retail rate (Source: 6. * Since July 1.0000 20.0000 8.0000 15.8087 20.bot.7500 8.0000 14. National Association Indian Overseas Bank The Royal Bank of Scotland N.0000 32.7500 8.0000 .0000 8.0000 9.8750 8.20.2500 6.0000 45.9900 14.0000 15.2500 10.5417 11.5000 8.0000 20.th/english/statistics/financialmarkets/interestrate/_layouts/application/interest_rate/IN_Rate.2500 8.0000 25.0000 11. MLR=Minimum loan rate.7500 7.5000 6.2500 25.0000 13.7500 50.2500 7.0000 7.0000 8.0000 Information as of 12.0000 14.0000 8.2500 7.0000 14.0000 8.0000 13.7500 21.7500 8.5000 7.2500 22.7500 10.7500 9.3750 8.2500 7.Bank Foreign Bank Branches The Bank of Tokyo-Mitsubishi UFJ Citibank Sumitomo Mitsui Banking Corporation HSBC Deutsche Bank AG.5000 8.0000 20.0160 25.0000 19.or.V.0000 19.0000 23.
199 261.435 5.030.939 6.622 358.512.432.498 4.786 752.896.346.000 270.847.645.724 3.000 261.680 1.505.230 2.781 2.11 Nov-11 Dec-11 Jan 1.040 200 261.396 3.015.199 1.622 358.015 849.727 Aug 1.425 4.677 Mar 1.622 358.000 270.677 2.831 772.622 358.787.016.760 Feb 1.956 3.000 261.908 6.255 2.589 1.200 261.396.253.622 358.801.518.591 Oct 1.1.182 Jul 1.435 6.935.887 Jun 1.677 3.786 752.908 6.425 270.331 752.834. 2012 Description Cash Account Receivable Total cash receive Cost Sale Administration expense Pre opening Loan Supply Expense Tax Total cash paid Total cash 3.372 358.104 3.171.695 5.787.015 849.052.695 2.677 Jul 991.856 1.982.360 1.677 Nov 1.939 6.016.650 13.000 261.000 270.396.016.495.289 3.042 358.435 5.636.698.432.930.926.028.717 5.026 Feb 1.165.234.000 261.265 2.677 May 991.821.498 4.255.132.306.622 358.419 598.445 5.353 1.924 2.234.385 1.098.015 849.432.443.500 261.435 5.677 2.396 261.346.056.425 200 261.539 3.622 358.704 3.015 849.677.007 424.062.040 4.917 1.826.419.306.419 598.435 5.339 3.794.622 358.939 6.875.425 200 261.044 1.351 6.016.222 261.622 358.942.088 3.411.261.492 4.372 358.956 Dec 1.388 3.213 6.622 358.197.478.717 5.425 261.016.248 4.545.498 4.677 2.743.875.407.521 6.700.199 1.677 2.016.171.189 2.677 2.222 324.677 Dec 1.742.924 2.007 424.711.213 6.677 2.196.677 2.190 501.256 1.427.717 4.315 1.432.636.190 501.523 2.982.969 Apr 1.677 2.925 Mar 1.378.603 7.761 .556.666.435 6.740 733.327.007 424.071 1.930.396.677 13.622 358.474 3.358 Sep 1.474 2.729 May 1.589 4.982.939 6.040 200 270.425 200 261.997 2.831 772.042 701.446 1.199 4.179.068.711.372 358.795 1.982.603 7.622 358.665 1.007 424.856.924 3.677 Aug 991.677 Apr 1.334.622 358.7 Source of Cash Source of Cash.677 2.083 1.677 Oct 1.306.171.995.859 2.677 2.327.992 1.958 Jan 1.309.622 358.225.760 358.435 6.636.677 82.377 1.175 1.016.821.943.015 849.800.171.677 2.307 2. 2011 Description Cash AR Total cash receive Cost Sale Administration expense Pre opening Supplies Expense Loan Total cash paid Total cash Beginning 8.677 Sep 1.982.274 3.213 772.432.982.622 358.982.040 261.911 1.649.969.190 501.756.740 733.545.015 849.935 2.000 270.591.190 501.425 200 319.636.636.425 4.908 772.700.339 2.042 3.457 2.926.384 2.372 358.465 9.814 1.126 2.303.756.274 Nov 1.677 Jun 991.072.435 4.992 1.372 358.200 261.982.354 2.015 849.372 358.717 5.053.645.465 8.021.622 358.631 2.015 849.975 1.307 Source of Cash.452.5.019 1.801.306.708.213 Otc.
470 200 319.677 2.152 3.490 Source of Cash.969 2.216 934.554 Sep 2.108 467.743 2.812.622 358.398.816 5.398.378 4.378 Nov-13 Dec-13 Jan 2.328.761 2.238 1.007.199.410.244 200 319.180.387.027.824.119 513.027.269.793 Jun 1.677 295.261.079 3500 261.238 1.677 Jul 1.543 2.106.505.216 934.119 513.470 3500 270.622 0 358.108 467.908 4.189 4.435 849.387.238 1.489 2.622 0 358.180.398.677 2.120 2.622 358.004 2.812.070 2.510.398.789.306 1.908 4.602.526.042 0 13.372 0 358.622 0 358.379 2.760 358.199.180.487.622 358.192.955 3.007.969 2.216 934.800.090.149.708 2.293.838.244 3.500 270.585.816 4.240.119 513.812.027.398.769 1.908 4.199.108 467.908 4.323.031.216 934.816 5.244 3.579 2.387.470 200 261.622 0 358.192.108 467.927.817.622 0 0 358.841 2.793.470 0 270.007. 2014 Otc 2013 Cash Accout Receiable Total cash receive Cost Sale Administration expense Pre opening Supply Ex lone Tax Total cash paid Ttotal cash 1954708 1789370 1252489.378 4.339 Oct 2.622 358.101 2.677 Nov 2.412 Feb 2.372 0 358.244 261.246.651.507.732.821.031 1.185 2.061.256 1.027.156.387.743 1.244 200 261.820 261.099 May 1.941.398.149 1.677 2.641.816 5.435 Nov-12 Dec-12 Jan 2.959 Jul 1.771.192.069.677 Mar 2.677 Dec 2.883.677 2.216 934.794.743 2.180.960.677 Oct 2.238 1.090.677 2.879 2.192.470 200 261.180.326 Aug 1.410.776 1.776.040.238 1.677 2.677 Aug 1.820 200 261.106 2.812 1.622 358.244 200 261.868.677 Feb 2.216 934.622 358.119 513.378 4.079 200 261.824.803 3.786.677 Jun 1.473 1.435 849.923 2.677 2.398.027.519 2.419 1.597 2.378 934.484 2.677 2.504 2.427.199.027.293 1.140 Mar 2.523 2.034.450 3.419 2.079.216 934.372 358.370 2.760 358.128.387.410.248 Apr 2.090.373 .622 0 358.622 358.620 2.816 5.969 2.812.079 200 270.930.965 Total cash receive Cost Sale Administration expense Pre opening Supply Expense Lone Tax Total cash paid Total cash 2.192.505 2.526.500 261.717 3.830.378 5.956 3.238 1.042 13.622 0 358.001 Nov 2.526.949.622 358.189 4.387.954.163.378 5.197.031.146.378 934.155.816 5.372 358.027.372 358.500 261.840 1.090.378 4.180.146.328 3.793 2.189 4.252.076.372 0 358.677 Apr 2.331 1.397 2.816 5.677 May 1.475 1.387.788.216 934.622 0 0 358.019 2.192.903.722.432 3. 2013 Otc -12 Cash Account Receivable 849.596 2.Source of Cash.180.378 4.470 0 261.244 270.561.189 4.816 4.329 2.131 934.398.180.155.572 2.470 3500 261.811.581.820 200 270.238 1.079 0 261.677 689543 4.027.192.357.320 2.474 2.526.677 2.410.238 1.677 2.820 3.298 2.114 Dec 2.244 200 261.020.677 2.677 Sep 2.016.007.470 200 261.332 1.934 2.378 5.625.173.293.
652.061 1.130.399.762 2.731.600.212 261.130.638.061 1.130.367 Sep 2.212 200 261.212 270.027.130.622 358.130.064 Oct 2.622 358.598 6.955 2.600.130.451.677 3.113 3.704 3.031 565.598 5.638.598 6.893.057 2.363 3.816 Nov-13 Dec-13 Jan 2.261 3.677 2.238 Mar 2.083 .816 1.600.279.319.500 270.864 200 270.622 358.131 1.622 358.638.212 3.652.212 200 319.Source of Cash.299 5.727 3.600.273.652.600.604 Apr 2.677 2.622 358.291.677 2.891 1.061 1.663 3.220.220.711 3.496.031 565.130.652.372 358.212 200 261.031 565.061 1.677 2.677 1.223.031 565.600.251 Feb 2.500 261.140.598 4.360 3.319.114.038 2.334.598 5.212 200 261.638.849.761 3.598 6.567.061 1.792 2.282.174.760 358.638.679 1.686 Jul 1.638.220.246.042 13.027.622 358.276.131.212 3.669 4.286.232.816 1.882.912.989.220.677 2.511 2.421 Jun 1.714 Nov 2.273.360.620.299 5.061.299 5.711 3.598 6.157.319.299 5.130.677 1.061 1.500 261.622 358.372 358.129.061 1.600.354 3.672.103 1.864 3.677 2.061 1.677 1.598 6.229.638.814 Dec 2.378.638.163 3.677 1.065.151 Aug 1.523 2.453 3.677 1.372 358.711 2.319.510.622 358.864 261.156.046.553 May 1.373 3. 2015 Otc 2013 Cash Account Receivable Total cash receive Cost Sale Administration Expense Pre opening Supply Expense Lone Tax Total cash paid Total cash 2.027.894 3.864 200 261. | https://www.scribd.com/doc/146678259/North-Rubber | CC-MAIN-2017-26 | refinedweb | 50,033 | 69.38 |
FL
AM
TE
Team-Fly®
Page i
Disclaimer:
This netLibrary eBook does not include the ancillary media that was packaged with the original
printed version of the book.
R&D Books
CMP Media, Inc.
1601 W. 23rd Street, Suite 200
Lawrence, KS 66046
USA
Designations used by companies to distinguish their products are often claimed as trademarks. In all
instances where R&D 2000 by Byte Craft Limited. Licensed Material. All rights reserved. Published by R&D
Books, CMP Media, Inc..
All other trademarks mentioned herein are property of their respective companies.
Page v
Acknowledgments
I would like to thank Walter Banks at Byte Craft Limited for dropping me head-first into the world
of embedded programming. Walter and Andre have provided copious expertise in the very finest
points of C programming and code generation.
I would also like to thank my parents, who went out on a limb and purchased that Commodore 64 all
those years ago. I hereby disclose publicly that I did not wash the dishes forever, as promised.
Page vii
Table of Contents
Acknowledgments v
Chapter 1 1
Introduction
Typographical Conventions 3
Chapter 2 5
Problem Specification
Product Requirements 5
Hardware Engineering 6
Software Planning 8
Software Architecture 9
Pseudocode 10
Flowchart 11
State Diagram 12
Resource Management 13
Testing Regime 14
Page viii
Chapter 3 17
Microcontrollers In-depth
Instruction Sets 20
The Stack 20
Timers 24
Watchdog Timer 25
Examples 26 26
Interrupt Circuitry 26
Multiple Interrupts 31
RESET 31
I/O Ports 32
Analog-to-Digital Conversion 33
Chapter 4 37
Design Process
Product Functionality 37
Hardware Design 38
Software Design 39
Software Architecture 39
Flowchart 40
Resource Management 42
Scratch Pad 42
Interrupt Planning 42
Testing Choices 44
Code Inspection 44
Chapter 5 47
C for Embedded Systems
Device Knowledge 49
#pragma has 49
#pragma port 51
Endianness 52
Mechanical Knowledge 52
Libraries 54
Chapter 6 57
Data Types and Variables
Identifier Declaration 59
Real Numbers 63
Pointers 63
Arrays 64
Enumerated Types 65
Structures 66
Unions 68
typedef 69
External Linkage 73
Internal Linkage 73
No Linkage 74
Chapter 7 79
C Statements, Structures, and Operations
Functions 80
Function Parameters 81
Control Structures 81
Initialization Functions 82
Control Statements 82
Decision Structures Y 82
Looping Structures 84
FL
Control Expression 84
AM
Chapter 8 91
Libraries
Creating Libraries 92
Chapter 9 99
Optimizing and Testing Embedded C Programs
Team-Fly®
Optimization 100
Pointers 105
Simulators 108
Emulators 109
Chapter 10 111
Sample Project
Appendix A 119
Table of Contents
Appendix A 123
Embedded C Libraries
Appendix B 163
ASCII Chart
Appendix C 165
Glossary
Index 171
Chapter 1—
Introduction
1.1—
Role of This Book
C is the language of choice for programming larger microcontrollers (MCU), those based on 32-bit
cores. These parts are often derived from their general-purpose counterparts, and are both as
complex and feature-rich. As a result, C (and C++) compilers are necessary and readily available for
these MCUs.
In contrast, designers who have chosen to use 8-bit controllers have usually resorted to hand-coding
in assembly language. While manual assembly programming for precise control will never go out of
style, neither will the push to reduce costs. There are advantages in compiling high-level C language
to even the limited resources of an 8-bit MCU.
•Automatic generation of code for repetitive coding tasks, such as arithmetic for 16-bit or longer
data types.
Page 2
•Intuitive treatment of hardware peculiarities. Reading from or writing to a serial flash memory
device can be represented in C as a simple assignment statement, although the store operation
requires some coding.
This text shows you how to use C to program an 8-bit embedded MCU. We hope you are familiar
with C, but require in-depth information about microcontroller programming.
The main example project in this text is a computer-controlled thermostat. From an initial
specification, we progressively refine and augment the device in the same manner as any other
consumer or control product. With software development as our focus, we make choices and trade-
offs that any designer will need to make.
1.2—
Benefits of C in Embedded Systems
You will not be overwhelmed by details. 8-bit microcontrollers aren't just small: microcontrollers
include only the logic needed to perform their restricted tasks, at the expense of programmer
''comfort". Working with these limited resources through a C compiler helps to abstract the
architecture and keep from miring you down in opcode sequences and silicon bugs.
You will learn the basics of portability. Embedded applications are cost -sensitive. There may be
great incentive to change parts (or even architectures) to reduce the per-unit cost. However, the cost
of modifying assembly language code to allow a program written for one microcontroller to run on a
different microcontroller may remove any incentive to make the change.
You can reduce costs through traditional programming techniques. This book emphasizes C
code that generalizes microcontroller features. Details relating to specific hardware implementations
can be placed in separate library functions and header files. Using C library functions and header
files ensures that application source code can be recompiled for different microcontroller targets.
Page 3
You can spend more time on algorithm design and less time on implementation. C is a high
level language. You will be able to program your applications quickly and easily using C. C's
breadth of expression is concise and powerful; therefore, each line of code written in C can replace
many lines of assembly language. Debugging and maintaining code written in C is much easier than
in code written in assembly language.
1.3—
Outline of the Book
Determining the goals of software development is the first step, and is covered in Chapter 2. It
includes embedded-specific commentary about the regimen of predesign documentation crucial to
effective software development.
Chapter 3 provides an introduction to 8-bit microprocessors for those who have not dealt with them
on a low level before.
With a good plan and in-depth information about the central controller, the design process (covered
in Chapter 4) finalizes what was previously estimated. The processor-specific details about
implementing the thermostat are introduced.
Chapter 5 details hardware representation in C. It catalogs all the required set up for your program
source.
Chapter 6 provides insight into embedded data. The near and far variable storage modifiers mean
different things on an Intel PC running Microsoft Windows and on an embedded processor running
your code.
Chapter 8 introduces libraries. Even in environments with a pittance of ROM and a very specific
task to do, libraries of prewritten functionality are a great help.
Chapter 9 provides insight into optimization, and helps you test your creation thoroughly.
Chapter 10 sums up with more information about the sample project. Though some information is
presented throughout the book, this chapter includes content not previously discussed.
1.4—
Typographical Conventions
Typography is used to convey contextual or implied information. The following examples provide a
guide to the conventions and their meanings.
Page 4
1.5—
Updates and Supplementary Information
If you are looking for more information on the thermostat project, please consult our supplementary
information via web:
Page 5
Chapter 2—
Problem Specification
The problem specification is the initial documentation of the problem that your device and software
will solve. It should not include any specific design questions or product solutions. The main aim is
to explain in detail what the program will do.
Of course, there are as many ways to conduct project planning as there are workplaces on the planet.
Even the most standardized phases are observed in different fashions or in a different order. The
following sections are included because they add information about the embedded software realm,
or they pertain to the sample project specifically.
2.1—
Product Requirements
Often, this document is written from the users' point of view, as a series of user requirements. In the
case of an embedded system designed for a single task, you can be quite explicit and certain of the
extent of the product's intended functionality.
General decisions about hardware form part of the problem specification, especially in embedded
projects in which the hardware will be well controlled.
Page 6
Results
•Program will count real time on a 12- or 24-hour clock, and display hours and minutes on a digital
display.
•Program will accept and store time settings for three daily usage periods.
•Program will switch between heating control and cooling control. Note that some HVAC experts
will see the need for occasionally operating both heating and cooling at the same time, but this
requirement more closely resembles traditional thermostat operation.
•Program will compare current temperature with settings for current time period, and turn on or turn
off external heating or cooling units as needed.
•Program will refrain from changing state of external units twice within a short period of time, to
permit the HVAC equipment to operate well.
•Program will accept manual override at any time, and immediately turn off heating or cooling unit.
2.2—
Hardware Engineering
This book does not deal directly with hardware, except for the example project. Nevertheless, the
target platform influences everything about the product. It determines the ease with which code is
generated by the compiler, and it determines some overall software design decisions.
If software developers are so lucky as to be involved in the hardware development process, the
opportunity to influence the design is too important to pass over. Wish-list items to ask for include
the following.
A Built-in Debug Interface Another method of field-programmability would also suffice. When a
device must be installed, customized, or repaired on site, a Flash-RAM part makes more sense than
an EEPROM or ROM device.
ROM Code Protection Embedded processors often provide protection against casual examination
of your ROM code. A configuration bit inhibits reading of ROM through the programming
interface. While there are sev-
Page 7
eral exploits against this protection, only a determined opponent will succeed in reading your
programming.
Rational Peripheral Interfaces The temptation to route circuits according to convenience can
overwhelm software performance quite quickly when it affects I/O organization. Does the desired
processor have bit-manipulation instructions to change port bits independently? Will multiplexed
interfaces require too much data direction switching?
Some peripherals can be replicated using generic I/O port lines and driver software. This saves
money but adds complexity to the programming challenge. Typically described as "bit-banging",
software must quickly and repeatedly write sequences of bits to port output lines, to imitate the logic
signals of a dedicated peripheral circuit.
Standard libraries, which might not contemplate a particularly-optimized hardware solution, can pay
for the added hardware cost in reduced software cost.
The central decision in hardware design is processor selection. The choice of a processor is a
negotiated decision, weighing factors such as the resources needed by the intended application, the
cost and availability of the part supply, and the development tools available. For an in-depth
treatment of microcontrollers, see the next chapter. Memory estimation does form part of our
problem specification, so estimation of RAM and ROM sizes is discussed in Section 2.3.5, Resource
Management.
Results
While we don't deal with hardware engineering in this book, we include some sample product
specification information for hardware to complete the information set.
•development board
Y
FL
2.3—
Software Planning
AM
The software plan should say something about the choice of programming language. With
embedded systems, there are three general choices of development language: machine language, C,
or a higher-level language like BASIC. Of the three, C balances two competing needs.
TE
The first step in the software plan is to select an algorithm that solves the problem specified in your
problem specification. Various algorithms should be considered and compared in terms of code size,
speed, difficulty, and ease of maintenance.
Team-Fly®
Page 9
Once a basic algorithm is chosen, the overall problem should be broken down into smaller problems.
The home thermostat project quite naturally breaks down into modules for each device:
•HVAC interface,
•keypad,
•LCD, and
•temperature sensor;
Working from the block modules, you can write traditional pseudocode. This helps form the
identifiers and logical sections you will implement in your code.
The flowchart begins to make the transition from natural language pseudocode to actual code. In
the flowchart, we can begin to speculate about the data that functions will accept and provide. Most
importantly, we can begin to plan library usage. Even if there are no prewritten peripheral or data
conversion libraries available, we can write original code in library form and much more easily re-
use it later.
It is likely that different states have been introduced into the plan. A state diagram maps the
transitions, as a complement to the flowchart.
From the pseudocode, we can build a list of variables and make estimates about RAM and ROM
needs. The restriction of memory resources will come as a shock to some. Programmers working
with modern desktop environments are comfortable with huge memory spaces. Great fields of RAM
are available to create large data structures or arrays that may never actually be initialized or used.
In contrast, microcontrollers sport only as much RAM and ROM as is projected to be needed for a
specific class of target applications. Vendors strive to provide a range of similar parts, each variant
contributing only a small increase in on-chip resources.
Results
2.3.1—
Software Architecture
The main architectural dilemma involves the use of interrupts versus polling. Part of this dilemma
will be resolved in part selection: some processor variants do not include interrupts at all. Other
choices include explicit
Page 10
support for interrupt-driven keypads, or timers that generate interrupts upon timeout.
A serious facet of an interrupt-based solution is the protocol for communication between the
interrupts and main-line code. Since interrupts and main line are as independent as possible (an
interrupt may occur during any main-line instruction), race conditions are one consequence.
We have chosen the simplest of several alternative algorithms: a clock/counter interrupt will
calculate time, request a display update and set target temperatures. The main line will loop to poll
the keyboard, to sample environment temperature, to update the display, and to switch the HVAC
machinery. This requires only a precise timing interrupt, which is essential for 24-hour timekeeping.
2.3.2—
Pseudocode
Pseudocode presents in natural language the imperative steps of the program. It is especially useful
in embedded programming because every aspect of execution can be planned together: there is no
need to account for operating system oddities.
In the following example, we assume that time is kept with a counter and
software.
1. Initialization
(c) Loop through the preset cycles. If clock is at or past the indexed cycle time, set target
temperature to that cycle.
3. Main loop
(2) If environment temperature is inside target temperature, turn off heat or cool.
(1) If key is pressed, wait for debounce period and check again.
2.3.3—
Flowchart
This diagram is basically a representation of the relationships between major and minor tasks in the
embedded software. The flowchart helps determine
Figure 2.1
Data flow for the algorithm
2.3.4—
State Diagram
The software will likely express different states, moving between them after processing external
interaction or internal events. This diagram illustrates these states and the stimuli that make it
progress through them.
Page 13
Figure 2.2
State diagram for the algorithm
2.3.5—
Resource Management
In the restricted environment of a microcontroller, one too many variables or constants can change
the memory requirements, and therefore the price, of the selected part. Features like multiple
language support can quickly boost the resource requirements to a new level.
It makes sense to explicitly plan out the resources needed. This is not terribly premature — we are
still talking about generic variables here, not specifics like page 0 access, serial ROM, or other
technical choices.
If you have written assembly language programs before, estimating memory demands is easier.
Without that experience, writing sample code and compiling it is the only way to forecast precisely.
Fortunately, using C helps conserve all that development effort.
2.4—
Testing Regime
•Code inspection.
Both hardware and software can benefit from early consideration of debugging needs. Especially in
systems with alphanumeric displays, software can communicate faults or other out-of-spec
information. This infor-
Page 15
mation is useful both to the tester and the end user, but it may prove a liability if the market will not
tolerate equipment that appears to fail.
In the absence of the panel, LEDs can signal meaningful states or events. Provision for run-time
diagnostic feedback should appear in the pseudocode and resource projections.
The first step in debugging requires you to inspect the assembly code generated by the compiler.
Embedded control applications on 8-bit CPUs are small enough, and the architecture simple enough,
that a developer can review the entire generated assembly language easily. A listing file, which lines
up C source fragments with the assembly they generate, provides the easiest navigation.
Beyond this first step, however, testing becomes a challenge: when the code in question implements
the most basic behaviour of the machine, in-system debugging becomes more difficult. A bug may
prevent any meaningful response from the embedded system at all, whereas desktop operating
systems can provide core dumps or other diagnostic aids.
To make in-system debugging possible, simulators and emulators peer into the embedded system.
Each tries to approximate different areas of the target environment while allowing you to inspect
your software's performance thoroughly and easily. Software-only simulators are best used to
examine algorithm performance and accuracy, in a situation in which you don't need or care about
the hardware. Emulators focus more on I/O and internal peripherals operating in the real world. You
will need access to at least an emulator. We bring it up now because tool selection is tied to the
hardware design process and processor selection.
Finally, placing a prototype device within a testing harness provides the most accurate proof of
working software.
Results
Our design will have an LCD panel. With this capability, the system can write debug messages to
the display. These can include a ''splash screen" on power-up, echoed keystrokes, or displayed status
messages.
The compiler must help in debugging. The generated assembly code needs to be available for
inspection.
Product choices should favour emulators that can perform source-level debugging, matching the
currently-executing machine code with the original C. For a thermostat, speed of emulation is not a
critical factor; the only time-dependent function is the real-time clock.
A test harness made up of a lightbulb and fan, switched by the controller and pointed at the
thermistor, is the simplest effective solution.
Page 17
Chapter 3—
Microcontrollers In-depth
This section reviews microcontroller features and outlines the options available in the 8-bit
microcontroller market. Some of the features you are used to seeing in central processors, such as
graphics enhancements or floating point support, are nonexistent here.
The most engrossing and charismatic part of computer hardware design is the choice of the central
processing unit. In the desktop world, processor choices revolve around compatibility with the Intel
x86 product line: those compatible with Intel, those nearly compatible, and those completely
divergent from it.
There is little such consistency in the embedded world, especially when talking about a new design.
The 8-bit controller market is very competitive, largely because of the focus on volume. There is
usually no brand name recognition; consumer product manufacturers want to protect users from
technical details. If users do care about the chip that drives their product, they are probably seeking
to surpass its intended use.
Finally, factors such as the life expectancy of the architecture should be considered. Using a C
compiler for generating device programming reduces the cost of changing controllers when the
preferred choice reaches the end of its product life cycle.
Central Processing Unit (CPU) The arithmetic and logic units of microcontrollers are restricted
and optimized for the limited resources present in such small architectures. Multiply and divide
operations are rare, and floating-point is nonexistent. Addressing modes are restricted in sometimes
infuriating ways.
ROM and RAM The 8-bit microcontrollers rarely address more than 16 lines (64Kb) of ROM and
RAM. If a chip's package exposes address or data buses at all, they provide only several kilobytes of
addressing space. Most often, MCUs (Microcontroller Units) contain small internal RAM and ROM
arrays. Because of the requirement to program the individual chips, ROM is often available as
electrically-programmable (or electrically-erasable) memory.
Timer Two kinds are common: counters and watchdog timers. Simple counters can respond to a
clock cycle or an input signal. Upon reaching a zero-point or a preset threshold, they can trigger an
interrupt.
That is, if the controller has interrupts at all. There is no guarantee that designers will include them
if the intended applications are simple enough not to need them.
Input and Output Most chips supply some I/O lines that can switch external equipment;
occasionally these pins can sink heavy current to reduce external components. Some varieties
provide A/D and D/A converters or specialized logic for driving certain devices (like infrared
LEDs).
Peripheral Buses Parallel peripheral buses reduce the "single-chip" advantage, so they are
discouraged. Because speed is not at the top of the
Page 19
list in embedded systems design, several competing standards for serial peripheral buses have
evolved. Using only one to three wires, these buses permit external peripheral chips, such as ROMs,
to interface with the microcontroller without monopolizing its existing interface lines.
The main consequence of the microcontroller's small size is that its resources are proportionally
limited compared to those of a desktop personal computer. Though all the qualities of a computer
are there — RAM, ROM, I/O and a microprocessor — the developer cannot count on having 8 bits
in an I/O port, for example.
Before settling on the perfect processor, you must consider the external development tools available
for your target. An embedded system is not self-hosting, like a personal computer. To develop
embedded software, your development tools must run on a desktop computer, and use at least some
very specialized hardware.
3.1—
The Central Processing Unit (CPU)
The number and names of registers vary among microcontrollers. Sometimes they appear within a
memory address space, and sometimes they are completely separate. Certain registers are common
to most microcontrollers, although the names may vary.
•The accumulator
Y
FL
•The index register
Direct access to the accumulator and index register in C is only occasionally desirable. The C
register data type modifier amounts to a "request" for direct access to a register: the compiler
may not actually use a register if it cannot do so optimally.
When it is desirable or necessary, however, another type of declaration can link a variable name
with a register itself. The Byte Craft compiler provides the registera type (and equivalents for
other registers). Assignment to a registera variable generates a load into the accumulator
register, but does not generate a store into memory. Evaluation of the identifier returns the value in
the register, not a value from memory.
Team-Fly®
Page 20
Direct access to the stack pointer or program counter is even less desirable. The whole point of
using C is to abstract the program logic from direct machine language references. Function calls and
looping, which will even out device-dependent stack manipulation and branching, are the best ways
to structure your code. If necessary, use the C goto keyword with a labelled target: the compiler
will insert the appropriate jump instruction and, most importantly, take care of any paging or setup
automatically.
3.1.1—
Instruction Sets
Where machine instructions for multiply, divide, table lookup, or multiply-and-accumulate are
expected on general purpose MPUs (Microprocessor Units), their 8-bit equivalents do not always
appear on each variant of a controller family.
A #pragma statement can inform the compiler that the target chip does have a certain optional
instruction feature, and that it can therefore optimize code that will benefit from the instruction.
These examples are present in the header file of the MC68HC05C8.
3.1.2—
The Stack
If your processor supports a stack in general memory, the space required to record the stack is
allocated from RAM that would otherwise be used for global variables. Not all stacks are recorded
in main (or data) memory: the Microchip PIC and Scenix SX architectures use a stack space outside
of user RAM.
It is important to check the depth of return information stored by function calls and interrupts. The
compiler may report stack overflow (meaning that your stack is too small), but your stack
declaration may be larger than necessary as well.
Beyond declaring an area as reserved for the stack, there is little else to worry about. Consider the
following stack from the Motorola MC68HC705C8. The stack is 64 bytes from address 00C0 to
00FF.
Page 21
Figure 3.1
MC68HC705C8 stack
Because stack sizes and configuration will change between processor families (or even between
variants within the same family), the declaration makes the compiler aware of exactly how much
space is available. Should you not need 64 bytes, you can reduce the size from 0x40 to a smaller
number.
The compiler can provide information on the depth of function calling. See the CALLMAP option in
Section 9.6, Debugging by Inspection.
3.2—
Memory Addressing and Types
Most small microcontrollers provide very little RAM. The feeling of claustrophobia caused by
absolutely running out of RAM or ROM is novel for desktop application programmers. Beyond the
cursory check for failed memory allocations, programmers can rely on megabytes of RAM and swap
files to almost always avoid out-of-memory errors.
The C compiler assists by reusing memory, wherever possible. The compiler has the patience to
determine which locations are free at any one time, for reuse within multiple local scopes. "Free", of
course, means not intended to be read by a subroutine until reinitialized by the next function call.
You will find that some typical programming techniques overwhelm the capacity of 8-bit
microcontrollers because of memory concerns. Reentrant or recursive functions, gems of
programming in desktop systems, assume abundant stack space and are practically impossible.
Page 22
3.2.1—
RAM and ROM
RAM and ROM are very permanently divided on a microcontroller. They may be part of different
address spaces.
Controllers with anything less than the full complement of RAM or ROM (most of them) leave parts
of the address space unimplemented. Instruction fetches or reads or writes to those areas can have
unintended or erroneous results.
Declaring available RAM and ROM instructs the compiler where it is safe to place programming or
data. The Byte Craft compiler requires all memory resources to be declared. The declarations can
simply declare the type, size, and location of available memory, or they may optionally assign the
area a symbolic name.
Named address spaces give you some control over the optimization process. If your processor has
faster access to a portion of memory (page 0 on the 680x, for instance), and you have a particular
scheme in mind, you can declare your variables as being in that memory area.
/* ... */
3.2.2—
ROM and Programming
Programmable ROM, or PROM, started as an expensive means to prototype and test application
code before making a masked ROM. In recent years, PROM has gained popularity to the point at
which many developers consider it a superior alternative to a masked ROM in a mass production
part.
Page 23
As microcontroller applications become more specialised and complex, needs for maintenance and
support rise. Many developers use PROM devices to provide software updates to customers without
the cost of sending out new hardware.
Fused ROM is the traditional PROM, with ROM cells that are programmed by selectively blowing
fuses in a memory matrix, according to bit patterns. Programmable only by external equipment.
EPROM (Erasable Programmable ROM) is nonvolatile and is read only. It must be erased by
exposure to ultraviolet radiation.
Flash Memory is an economical compromise between EEPROM and EPROM technology. Your
product can have a ROM-based configuration kernel, and application code written into flash
memory. When you want to provide the customer with added functionality or a maintenance update,
the hardware can be reprogrammed on site without installing new physical parts. The hardware is
placed into configuration mode, which hands control to the kernel written in ROM. This kernel then
handles the software steps needed to erase and rewrite the contents of the flash memory.
Depending upon the target part, EEPROM and Flash are programmable under program control. The
programming process takes some time, as the electronics must wait for charge transfer and work
slowly to avoid overheating the device.
3.2.3—
von Neumann Versus Harvard Architectures
von Neumann architecture has a single, common memory space in which both program instructions
and data are stored. There is a single internal data bus that fetches both instructions and data.
Page 24
Harvard architecture computers have separate memory areas for program instructions and data.
There are two or more internal data buses, which allow simultaneous access to both instructions and
data. The CPU fetches program instructions on the program memory bus.
Programmers need not dwell upon which architecture they write for. C compilers should
compensate for most of their respective drawbacks and quirks. Some of the more common
characteristics are explained here as an insight into the code generated by compilers.
•Code generation for von Neumann-archtecture machines often takes advantage of the fact that the
processor can execute programs out of RAM. Operations on certain data types may actually prime
RAM locations with opcodes, and then branch to them!
•Since Harvard machines have an explicit memory space for data, using program memory for data
storage is trickier. For example, a data value declared as a C constant must be stored in ROM as a
constant value. Some chips have special instructions allowing the retrieval of information from
program memory space. These instructions are always more complex or expensive than the
equivalent instructions for fetching data from data memory. Others simply do not have them; data
must be loaded by the side effect of a return instruction, for instance.
3.3—
Timers
A timer is a counter that is incremented or decremented at the fixed rate of a clock pulse. Usually,
an interrupt signals the completion of a fixed interval: the timer has counted to 0, has overflowed to
0, or has reached a target count.
Timers are a very competitive feature in microcontrollers. Timers or timing units of increasing
sophistication and intelligence are readily available. The different types of timers available give the
engineer lots of room to manoeuvre.
Programming the prescalar and starting the clock are tasks of the software developer. Knowing the
processor clock frequency, and choosing correct prescalar values, you can achieve accurate timer
clock periods.
The programmer's interface to a timer is several named control registers, declared with #pragma
port statements and read or written as variables.
If a timer interrupt is available, it can be declared with a #pragma vector statement, and
serviced by an associated interrupt service routine, written as a function.
Page 25
void TIMER_IRQ(void) {
/* IRQ handler code */
}
3.3.1—
Watchdog Timer
A COP (computer operating properly) or watchdog timer checks for runaway code execution. In
general, watchdog timers must be turned on once within the first few cycles after reset. Software
must then periodically reset the watchdog during execution.
If processor execution has gone off the track, it is unlikely that the watchdog will be reset reliably. It
is this exact state that needs to be fixed: an indirect jump to an unexpected address could be the
cause. A loop polling for external signals that are never received is also a possible cause.
The watchdog timeout can cause the processor to go to a known state, usually the RESET state, or to
execute an interrupt. The hardware implementation of watchdog timers varies considerably between
different processors. Some watchdog timers can be programmed for different time-out delays.
void main(void) {
while(1) {
/* ... */
RESET_WATCHDOG();
}
}
Page 26
3.3.2—
Examples
•National Semiconductor's COP8SAA7 has a 16 bit timer called T1, a 16 bit idle timer called T0,
and a watchdog timer. The idle timer T0 helps to maintain real time and low power during the IDLE
mode. The timer T1 is used for real time controls tasks with three user-selectable modes.
•The Motorola MC68HC705C8 has a 16-bit counter and a COP watchdog timer. The COP
watchdog timer is user-enabled, has selectable time-out periods, and is reset with two write
instructions to the COPCR register. Interestingly, the COP watchdog is dependent upon the system
clock; a clock monitor circuit resets the MCU if the clock stops, and thereby renders the COP
watchdog useless.
•The Microchip PIC17C42a has four timer modules called TMR0, TMR1, TMR2, and TMR3, and
a watchdog timer. TMR0 is a 16-bit timer with programmable prescalar, TMR1 and TMR2 are 8-bit
timers, and TMR3 is a 16-bit timer.
3.4—
Interrupt Circuitry
Microcontrollers usually provide hardware (signal) interrupt sources, and sometimes offer software
(instruction) sources. In packages with restricted pin counts, IRQ signals may not be exposed or may
be multiplexed with other I/O signals.
Interrupts that can be disabled are maskable; those which you cannot disable are nonmaskable
interrupts. For example, RESET is nonmaskable; regardless of the code currently executing, the
CPU must service a RESET interrupt.
Interrupt signals are asynchronous: they are events that can occur during, after, or before an
instruction cycle. The processor can acknowledge interrupts using one of two methods:
synchronous or asynchronous acknowledgement.
Most processors acknowledge interrupts synchronously: they complete the current instruction before
dealing with the interrupt. In contrast, with asynchronous acknowledgement, the processor halts
execution of the current instruction to service the interrupt. While asynchronous acknowledgement
is more prompt than synchronous, it leaves open the possibility that the interrupt code will interfere
with the instruction already in progress.
For instance, an interrupt routine updates a multi-byte value, which the main-line code reads
regularly. Should the main-line code read that value in
Page 27
a multi-byte fetch, and be interrupted part-way through, the loaded value becomes meaningless
without any notice.
The code obeys our suggestion (Section 4.4.2, Interrupt Planning) about reading and writing
variables one way, between interrupt and main-line code. To provide complete protection, the
compiler needs to use indivisible instructions, or to disable interrupts temporarily, to protect the
main-line code.
Synchronous acknowledgement is not a magic solution. This same problem affects processors with
synchronous acknowledgement, when a multi-byte operation requires several instructions!
3.4.1—
Vectored and Nonvectored Arbitration
There are two competing ways in which microcontrollers service interrupts. Vectored arbitration
requires a table of pointers to the interrupt service routines. Nonvectored arbitration expects the
first instructions of the ISR at a predetermined entry point. Most 8-bit microcontrollers use vectored
arbitration interrupts.
When the compiler generates code for the interrupt service routine (ISR), it places the starting
address in the appropriate interrupt vector within the ROM map, or relocates the code at the entry-
point location in ROM. The compiler may also automatically generate arbitration code: remember to
check for this when estimating ROM usage.
When an interrupt occurs, the processor will disable interrupts to prevent the service routine from
being itself interrupted. A vectored machine then reads the address contained at the appropriate
interrupt vector. It jumps to the address and begins executing the ISR code.
In contrast, a nonvectored system simply jumps to the known start location and executes what's
there. The ISR may have to test each interrupt source in turn to implement priority, or to simply
jump to a different location where the main body of the ISR resides.
Because of the extra handling in nonvectored systems, vectored interrupts are faster. In general,
nonvectored ISRs are feasible for microcontrollers with less than five interrupts.
Table 3.1 shows the arbitration schemes of the major families of 8-bit microcontrollers.
Page 28
The National Semiconductor COP8 uses a mixed scheme. All interrupts branch to a common
location in a nonvectored manner. At that location, the code must either execute the VIS instruction,
which arbitrates among active interrupt sources and jumps to an address from a vector table, or poll
the system for the interrupt condition explicitly and handle it in a user-defined manner. The latter
method may be useful, but has many disadvantages.
Table 3.2 shows the COP8 vector table, as required for the COP8SAA7 device. The rank is as
enforced by the VIS instruction.
3.4.2—
Saving State during Interrupts
TE
On all chips, the interrupt process saves a minimal processor state of the machine, usually the
current program counter. This is done to ensure that after an interrupt is serviced, execution will
resume at the appropriate point in the main program.
Beyond this, machine state preservation varies widely. In any case, it is up to the programmer to
provide code that saves as much extra state as is necessary. Usually, each interrupt handler will do
this before attempting anything else. The location and accessibility of the saved state information
varies from machine to machine.
Team-Fly®
Page 30
Many C compilers reserve some locations in data memory for internal uses, such as pseudo-
registers. Your compiler documentation should outline what code you must write to preserve the
information located in these memory blocks. If your compiler creates a pseudo-register for 16-bit
math operations, and your interrupt handler does not perform 16-bit operations that alter this
pseudo-register, then you probably won't need to preserve its state.
3.4.3—
Executing Interrupt Handlers
To minimize the possibility of an interrupt routine being itself interrupted, the microcontroller will
disable interrupts while executing an interrupt handler.
Masking interrupts manually is useful during timing-critical sections of main-line code. The
possibility of doing this is determined by your design; implementing it in C is easy. It doesn't take
much more effort to generalize the procedure, either.
For the Byte Craft compilers, some simple macros in a header file can create the appropriate
instructions. This code uses symbols defined by the compiler itself to choose the appropriate
instructions.
#ifdef CYC
#define IRQ_OFF() #asm < DI>
#define IRQ_ON() #asm < EI>
#endif
Page 31
#ifdef COP8C
#define IRQ_OFF() PSW.GIE = 0
#define IRQ_ON() PSW.GIE = 1
#endif
#ifdef C6805
#define IRQ_OFF() CC.I = 0
#define IRQ_ON() CC.I = 1
#endif
3.4.4—
Multiple Interrupts
One some machines, the CPU first fetches and executes a program instruction, and then checks for
pending interrupts. This guarantees that no matter how many interrupts queue up, the machine will
always step through program code: no more than one interrupt handler will execute between each
main program instruction.
On most machines, the CPU will check for interrupts before performing the next instruction fetch.
As long as the controller detects a pending interrupt, it will service the interrupt before fetching the
next instruction. This means it is possible to halt the main-line program by continuously sending
interrupts. On the other hand, it guarantees that an interrupt is serviced before any more main
program code is executed. This information is important for debugging: it can help explain why
main-line software will not respond.
How does the CPU decide which interrupt to service first? A hardware priority level should
determine this if two interrupts are signalled at the same time.
3.4.5—
RESET
Some simple chips support no interrupts except a RESET sequence. If its intended applications
require only a simple polling loop, or accept no input at all, there is no need for the extra hardware.
The only universal interrupting signal is RESET. A RESET can occur because of:
•initial power-on;
•a watchdog time-out;
•an instruction fetch from an illegal or unimplemented address, if your part implements protection
against this.
The RESET interrupt prompts the chip to behave as if the power has been cycled. Since it does not
actually cycle the power to the chip, the contents of volatile memory, I/O ports, or processor
registers remain intact.
Taking advantage of this is tricky, but possible. If the compiler supports a user-written initialization
function, you can check for particular values in memory, and decide to load default values or not.
This can be used to check if the RESET was cold (power was cycled — use defaults) or warm
(power was not cycled: preserve unaffected data).
There are conditions that upset this strategy. In the case of watchdog time-out, the data is electrically
valid (the same as before watchdog RESET) but logically questionable.
3.5—
I/O Ports
Input/output signals allow the microcontroller to control and read relays, lamps, switches, or any
other discrete device. More complex components, such as keypads, LCD displays, or sensors, can
also be accessed through ports. In this section, we talk about programming standard I/O lines. More
specialized peripheral devices like A/D converters and communication buses are dealt with in
subsequent sections.
Ports usually consist of eight switchable circuits, arranged in byte-sized I/O data registers. If a port
is capable of both input and output, it will also have an associated register that specifies which way
the port (or each individual bit of the port) is to operate. On many devices, this register is called the
DDR (Data Direction Register).
Ports often support tristate logic. Tristate adds a third useful configuration besides input and output:
high impedance. High impedance mode is the state of being undefined or floating. It's as if the port
isn't actually part of the circuit at that time.
Since microcontrollers are intended to replace as many devices as possible, ports often include
extras, such as internal pull-ups or pull-downs. These electrical features provide some noise
immunity.
Data direction, tristate control, and optional pull-ups or pull-downs are all at the control of the
programmer. As with desktop computer systems,
Page 33
ports and their control registers appear as memory locations or as special I/O registers.
•The COP8SAA7 has four bidirectional 8-bit I/O ports called C, G, L, and F, in which each bit can
be either input, output, or tristate. The programming interface for each has an associated
configuration register (determines how the port behaves) and data register (accepts data for or
presents data from the port).
•The Motorola MC68HC705C8 has three 8-bit ports called A, B, and C that can be either inputs or
outputs depending on the value of the DDR. There is also a 7-bit fixed input port called port D,
which is used for serial port programming.
•The Microchip PIC16C74 has five ports: PORTA through PORTE. Each port has an associated
TRIS register that controls the data direction. PORTA uses the register ADCON1 to select analog or
digital configuration. PORTD and PORTE can be configured as an 8-bit parallel slave port.
Ports and their associated configuration registers are not RAM locations, and as such are not
electrically the same. Either reading or writing to a port may be illegal or dangerous if not explicitly
permitted by the manufacturer. The compiler can watch for improper reads or writes by specifying
acceptable modes in the port declaration.
With the Byte Craft compilers, ports are declared to the compiler using #pragma statements.
The acceptable modes of use are specified with portr for reading, portw for writing, or portrw
for both.
3.5.1—
Analog-to-Digital Conversion
The science behind conversion, and the competitive environment of some analog disciplines like
automotive instrumentation or audio processing, ensures that there is a variety of approaches to
conversion, with tradeoffs in accuracy, precision, and time.
Page 34
Typically, the support routines for an A/D or D/A converter are prime candidates for packaging as a
library of C functions. It is important to note that the conversion process may take some time.
The Byte Craft compiler will support this type of peripheral in two ways.
•You can declare the control ports with #pragma port in the device header file.
•You can declare an interrupt raised by the conversion peripheral with #pragma vector and
service it with an ISR function. This is an intuitive way to handle conversions that take a long time.
Most microcontrollers use a successive approximation converter for A/D conversion. The
converter works with one bit at a time from the MSB (Most-Significant Bit) and determines if the
next step is higher or lower. This technique is slow and consumes a great deal of power. It is also
cheap and has consistent conversion times.
The Microchip PIC16C74 has an A/D converter module that features eight analog inputs. These
eight inputs are multiplexed into one sample-and-hold, which is the input into the converter.
A flash converter examines each level and decides the voltage level. It is very fast, but draws a
great deal of current and is not feasible beyond 10 bits.
3.6—
Serial Peripheral Buses
Single-chip microcontrollers of sufficient pin count can expose address, data, and control signals
externally, but this negates the benefit of single-chip design.
There are several standards for serial peripheral communication, using one to three external wires to
communicate with one or more peripheral devices.
Of course, serializing frequent ROM or RAM accesses impacts on execution speed. Serial
peripherals are not accommodated within the addressing range of a processor, so serial program
ROM is not possible.
The compiler can assist by making data access to serial peripherals more intuitive. The Byte Craft
compilers provide the SPECIAL memory declaration. Using it, you can declare the registers or
memory of the remote device
Page 35
within the memory map as the compiler understands it. You then write device driver routines to
read and write each SPECIAL memory area.
Accesses to variables or ports declared within the SPECIAL memory area receive special treatment.
Reading the value of a SPECIAL variable executes the associated read routine, and the value
returned is the result of the read. Assigning a new value to a SPECIAL variable passes the value to
the associated write routine. The read and write routines can conduct peripheral bus transactions to
get or set the variable value.
Bus standards and driver routines are prime targets for library implementation.
3.7—
Development Tools for a Microcontroller
Developing software in C requires the use of a desktop computer to run the cross-compiler. From
there, you can program and evaluate the target system in one of the following ways.
Simulators The developer loads object code into a software program that simulates the eventual
environment. This arrangement is best suited for examining complex programming on the fly.
Emulators The developer substitutes the microcontroller (or an external chip like a program ROM)
in the design with a special piece of hardware that emulates the device while providing a link to the
development platform. A well-designed emulator does not appear any differently to the target
system than a normal controller, but allows the user to spy into the controller's behaviour and to
examine the target platform's hardware at the same time.
Development tools are a factor in processor choice. A compiler can generate information to link the
original source with the object code that the simulator or emulator uses. Watch for products that are
compatible with your compiler.
Page 37
Chapter 4—
Design Process
The design process mirrors the problem specification, making concrete decisions about each general
point raised previously.
4.1—
Product Functionality
We can mirror the product requirements, the user-oriented checklist of tasks that the product should
perform, with some details about the device to be designed.
Results
•Program will measure current temperature. We will have to service and read an A/D converter
connected to a thermistor. To minimize part count, the A/D converter will be quite rudimentary.
•Program will count real time on a 24-hour clock. With a one-second timer interrupt, we should be
able to count minutes and hours. We won't bother with day/date calculations — no automatic
daylight savings time adjustment, but no year calculation problems either!
Page 38
•Program will accept current time settings and reset clock count. Library routines should help in
translating internal clock representation with a displayable format.
•Program will accept and store user-selected heating and cooling temperature settings, and time
settings for three daily usage periods. We will build in reasonable defaults, and then keep the current
settings in RAM. If the power goes out, the device won't put anyone in danger.
•Program will compare current temperature with settings for current time period, and turn on or turn
off external heat or cooling units as needed. This will require asserting an output line to actuate a
relay, one for both heating and cooling.
•Program will refrain from changing state of external units twice within a short period of time to
avoid thrashing. This means keeping a separate count of a five-second waiting period between
switching operations. Immediate shut-off should override this count, however.
•Program will accept manual override at any time, and immediately turn off all active external
units. Whether the keypad is polled or interrupt-driven, one or two keys for shutdown should be
responded to immediately.
4.2—
Hardware Design
As mentioned previously, hardware is outside the scope of this book. We include this hardware
information to justify the choices we make in the design of the thermostat.
The part of choice is the MC68705J1A, for its simplicity and small pin count. It has just enough pins
to control all devices.
•2 pins (1 from port b, 1 from disabled IRQ input) for the thermistor.
The j1a is the only chip needed; the rest are discrete parts.
Once the hardware is settled, the task moves to designing your program.
Page 39
4.3—
Software Design
4.3.1—
Software Architecture
Prepackaged libraries of functions for microcontrollers are available with C compilers for embedded
targets, but they are nowhere near as common as those for the general-purpose computer
programmer.
Libraries for microcontrollers should always be accompanied by their source code! Since safety of
the final product becomes a real factor in applications like machine control, libraries must be as
carefully inspected as the rest of the program.
To remain productive, your compiler and emulation environment should agree on a format for
extended debugging information. This allows the emulator to perform source level debugging with
your listing file.
The development environment is not discussed here in detail. A text on configuration management
Y
can best provide assistance on how to implement revision control and build automation, if either are
FL
necessary.
Results
AM
The compiler will be the C6805 Code Development System from Byte Craft Limited. It generates
Motorola, Intel, and part-proprietary binaries, and a listing file that places the generated assembly
TE
With the Byte Craft CDS, device-specific details are captured in a header file that uses common
identifiers to represent them. Ensure that the device header file 05j1a.h is present. When using an
EEPROM part, use the file 705j1a.h. To change the target part, simply change the header file.
stdio includes routines to get and put strings from displays and keyboards. This library relies on
others to do the actual input and output.
lcd includes routines to clear the display, move the hardware cursor, and write characters and
strings.
Team-Fly®
Page 40
port provides transparent access to the two parallel ports of the j1a part.
delay times communications with the LCD display, and debounces the keyboard.
A clock/counter interrupt calculates time, requests display update, and sets target temperatures. The
main line implements a loop that updates the LCD, polls the keyboard, samples environment
temperature, and switches the HVAC machinery.
4.3.2—
Flowchart
Now we can add some concrete information to the flowchart for the algorithm. This in turn will help
us lay out our source files.
Page 41
Results
Figure 4.1
Data flow for the algorithm (revised)
Page 42
4.4—
Resource Management
Now that we have some concrete information about the target platform, the development software,
and the way data will flow between parts of the software, we can begin to nail down resource usage.
4.4.1—
Scratch Pad
Many C compilers use some available RAM for internal purposes such as pseudo-registers. An
efficient C compiler will support scratch pads in data memory. A scratch pad is a block of memory
that can be used for more than one purpose. A pseudo-register is a variable used as the destination
for basic operations performed with larger data types. Your compiler documentation will detail the
size and purpose of scratch pad allocations.
For example, if you attempt a 16-bit math operation on a chip with no natural 16-bit register, the
compiler will dedicate a portion of RAM for 16-bit pseudo-registers that store values during math
operations.
If the scratch pad allocation strains your memory budgeting, you can consider reusing the memory
yourself. The only condition is that you must manage variable scope yourself.
For example, the Byte Craft compiler creates the 16-bit pseudo-index register __longIX. You can
reuse this 16-bit location with the following statement.
Should you store a value in myTemp, and then make a library call, the library software must not
perform any long operations or your data will be overwritten.
4.4.2—
Interrupt Planning
Unless you have delved into drivers or other low-level software development, you have probably
been shielded from interrupts. Embedded C helps by providing an intuitive way to structure and
code interrupt handlers, but there are some caveats.
•How will the main-line processor state be preserved? The processor registers might be saved
automatically on a stack, or simply shadowed in hidden registers, by the processor. You might easily
swap the main-line register values out if multiple banks of registers are available. As a last resort,
you could save the register values manually, and restore them before returning from the interrupt.
Page 43
The temporary registers used by compiler math functions also need to be preserved if calculations
within the interrupt might obliterate them. Preserving these registers will require multi-byte transfer
routines. The cost of these repetitive sequences within a frequently-called interrupt can add up.
•Will the tasks envisioned for the interrupt, including the previous save and restore operations, be
completed in time? The frequency of the interrupt calls, and the amount of work to be done within
them, need to be estimated.
If there is more than enough time to complete all operations, the speed of the processor could be
reduced to gain electrical benefits.
•How will the interrupt routine and main-line code interact? Beyond protecting critical sections of
the main line by disabling interrupts, there are broader synchronization conflicts to worry about,
especially in global data.
One general rule is to write global variables in one place only — main line or interrupt code — and
read them in the other. Make communication between the interrupt routine and main-line code travel
one way if possible.
Results
The C6805 CDS creates a 4-byte scratch pad called __SPAD. It also creates two pseudo-registers
for 16-bit operations. They are __longAC (2 bytes) and __longIX (4 bytes).
C6805 has support for local memory, so we can watch for economies in counter or temporary
variable allocation.
The j1a a part has a software interrupt, which may be used by the compiler as a fast subroutine
call. We won't use it explicitly. We will disable the IRQ input to use as a spare input pin.
The j1a also has a timer interrupt, which we will use to execute the time-keeping functions. The
interrupt will run about every 65 milliseconds, so we will need to keep the following items.
A Millisecond Counter Actually, the millisecond counter needs an extra digit of accuracy to agree
with the published specification, so we will keep tenths of a millisecond.
Page 44
A Second Counter We will display time in minutes, so this is just for internal use.
A Counter for Hours and Minutes We will explain more on this later.
Since we will need the external IRQ pin as an extra input, we cannot use the keypad interrupt
function associated with port A pins 0–3.
6805 interrupts cause the entire processor state to be preserved: accumulator, X register, PC, stack
pointer, and condition codes. Therefore, we don't need to write code for this. We may need to
preserve the pseudo-registers.
4.5—
Testing Choices
4.5.1—
Design for Debugging
With the processor selected, you can start to formulate a testing strategy. The processor may supply
some help, in the form of a hardware debugging interface.
Designing the software by grouping it in libraries is a good organizational technique. You can then
test each subsystem by writing small test programs that use one library apiece.
Modular testing solves an interesting quandary: a system with an LCD display can display human-
readable status codes or other debugging messages. But until the LCD display itself is operational
and reliable, it is of no help.
Focus directly on the configuration of the LCD display with a test program: it is one of the more
complex ''black box" devices, with a 4- or 8-bit interface, and enable, register-select, and read/write
lines that must be signalled according to timing tolerances. In our design, it is cost-effective to
multiplex the LCD data bus with the keypad. In your design, the LCD bus may be attached in even
more complex ways. You may need a test program just to drive the library as you customize it for
your hardware.
4.5.2—
Code Inspection
#pragma library;
#pragma option +l;
/* . . . */
#pragma endlibrary;
This causes the compiler to omit generating code for any function not referenced from the main
module, and to reproduce the library code within the listing file.
4.5.3—
Execution within a Simulator Environment
Software-based simulators enjoy great flexibility as a test environment. Although not physical, they
can be written or configured to match the specified programmer's model and hardware
characteristics exactly.
When running on a contemporary PC, speed of simulation is not an issue: a PC running at hundreds
of MHz can easily simulate events at the common MCU speeds of between 1 and 10 MHz.
4.5.4—
Execution within an Emulator Environment
There is a tradeoff that appears with emulators: they provide a physical base for testing, but may not
reproduce your specific physical configuration. They only present the success of the design to the
extent that they implement it.
Emulator host software should accept a debugging file format. Byte Craft's .COD file is such a
format. It includes extra information that would not normally be represented within the executable
data, such as source code line numbers for each section of generated code.
With this extra information, emulators can coordinate breakpoints within the source or listing file.
You can determine the context of the register values that the emulator host software reports.
4.5.5—
Target System in a Test Harness
After prototype hardware has arrived, it makes sense to move candidate software to it as quickly as
possible. The test harness can consist of simple components: switches, lights, small motors, or other
simple indicators. It should replicate the connections (and any feedback conditions) of the working
environment for which the unit is destined.
Page 46
For the programmer, the challenge lies in understanding the difference between the test harness and
the real world. Hopefully, you will not have to change important constants like prescalar values.
Results
For initial code inspection, we will use the C6805 listing file. The listing file includes numerous
reports that are useful both during code-and-compile cycles, and when doing code review on others'
work.
For an emulator, we will use the MC68HC705JICS product from Motorola. The emulator connects
to a PC using a serial cable, and uses a 6805C8 to recreate I/O ports and communicate with the host
system. The host system actually evaluates the j1a software. The emulator is non-real-time:
commands to change port bits, for instance, must be transmitted by the PC to the JICS board.
Chapter 5—
C for Embedded Systems
With a refined design in hand that takes into account the prospective hardware environment, you can
begin coding. Starting to code an embedded project is not much different from coding a desktop
application project.
Most significantly, the only software environment present is that which you establish, through
device defaults, global declarations, and setup routines. The main() function is indeed the main
function.
•mechanical knowledge.
5.1—
In-line Assembly Language
While not required by ANSI C, most embedded development compilers provide a means of
incorporating assembly language in C programs. One common way of accomplishing this is using
preprocessor directives.
The Byte Craft compiler uses #asm and #endasm directives to signal assembly language code
boundaries. Everything lying between the directives is processed by the macro assembler, which is
built into the compiler.
Page 48
The labels and variables used in C are available within included assembly, as well. However, the
compiler will not attempt to optimize such code. The compiler assumes that the user has a good
reason to avoid the compiler's code generation and optimization.
The following two definitions of the wait() function show the function written in C and the
equivalent function in Motorola 68HC705C8 assembly language.
/* C function */
5.2—
Device Knowledge
In the embedded world, one compiler, generating code for one controller architecture, must still
support a potentially endless array of slightly different processors: parts with varying amounts of
RAM and ROM, fewer or more ports, special features, and so on. Add to this the possibility of
customized parts (with mask-programmed ROM routines, for instance).
The standard C environment allows the definition of compiler-specific extensions with the
#pragma preprocessor directive. The preprocessor may deal with #pragma directives in your
source code, or it may be the compiler that acts upon these directives.
The #pragma directive is used most commonly in embedded development to describe specific
resources of your target hardware, such as available memory, ports, and specialized instruction sets.
Even processor clock speed can be specified, if it matters to the compiler. The following sections
describe #pragma directives needed by the Byte Craft compiler.
5.2.1—
#pragma has
#pragma has describes specific architectural qualities of the processor. The qualifiers of the
#pragma has instruction are dependent upon the processor family and the compiler.
Y
Most #pragma has statements will appear in the device header file. The following examples
FL
show the difference between code compiled with has MUL enabled and disabled.
AM
void main(void)
{
TE
Team-Fly®
Page 50
031F 81 RTS }
0320 B7 ED STA $ED /* multiplication subroutine */
0322 A6 08 LDA #$08
0324 B7 EC STA $EC
0326 4F CLRA
0327 48 LSLA
0328 59 ROLX
0329 24 05 BCC $0330
032B BB ED ADD $ED
032D 24 01 BCC $0330
032F 5C INCX
0330 3A EC DEC $EC
0332 26 F3 BNE $0327
0334 81 RTS
?
Page 51
031A 42 MUL
031B B7 EB STA $EB
031D 81 RTS }
5.2.2—
#pragma port
#pragma port directives describe the ports available on the target computer. This declaration
reserves memory-mapped port locations, so the compiler does not use them for data memory
allocation.
#pragma port directives indicate read or write access, or both. The electronics of I/O ports may
sometimes forbid writing to them or even reading from them. The compiler can report undesirable
accesses to a port if it finds a restriction in the declaration. Besides protecting the port register, the
declaration allows you to provide a useful mnemonic name for the port. You can then use the name
associated with the port to read or write its input or output state.
The following defines two ports and their associated data direction registers on the Motorola
68HC705C8.
The compiler is informed that two ports are available. The name PORTA refers to physical port A's
data register, which is available for reading and writing and is located at address 0x0000. The
name DDRA refers to physical port A's data direction register, which is available for writing only and
is located at address 0x0004.
It is then possible to write the value 0xAA (alternate bits high) to the port using the C assignment
syntax.
The resources for a specific part are best described through a header file that is brought in using
#include. ANSI C has one prescribed rule about #pragma directives: if a #pragma directive is
not recognised, the compiler ignores it. This ensures that unknown #pragma directives will not
affect your code.
5.2.3—
Endianness
One piece of device knowledge that the programmer must keep in mind is the endianness of the
processor. C does not deal directly with endianness, even in multi-byte shift operations.
In cases in which you will directly manipulate part of a multi-byte value, you must determine from
manufacturer's information whether the high byte (big end) or low byte (little end) is stored first in
memory.
With the restricted resources of microcontrollers, some quirks appear. The COP8 architecture stores
addresses in memory (for indirect operations) as big-endian, and data as little-endian. Addresses
pushed on to the stack do not appear in the same endianness as they do in registers or in RAM.
Compilers, when building their symbol tables, normally use the lowest (first) memory location to
record the location of an identifier, regardless of the endianness of the processor.
5.3—
Mechanical Knowledge
Techniques used in an embedded system program are often based upon knowledge of specific
device or peripheral operation. Modern operating system APIs are designed to hide this from the
application developer. Embedded C systems need first-hand control of peripheral devices, but can
still provide a healthy level of generalization.
One useful technique employed by the port library is to define the letters I and O to the appropriate
settings for port control registers that govern data direction. The letters cannot be defined
individually. They are defined in eight-letter sequences that are unlikely to appear elsewhere.
Applications may need to use a port both as input and output (for instance, driving a bidirectional
parallel port through software), and setting a port's data direction using these macros provides device
independence.
Page 53
#include <port.h>
/* port.h contains numerous definitions such as the following:
Low power operation can be achieved by repeatedly putting the processor in an inactive mode until
an interrupt signals some event. Processor families provide variations on the STOP or WAIT
operation, with different provisions for protecting the contents of processor registers and recovery
times. C duly expresses these as STOP() or WAIT() macros. If a hardware stop was not available,
the macro could be redefined to cause an infinite loop, jump to the reset vector, or perform another
substitute operation.
When a button is pressed, it "bounces", which means that it is read as several quick contact closures
instead of just one. It is necessary to include debouncing support to ensure that one keypress is
interpreted out of several bounces. When a first keypad switch is registered on a port, software can
call the keypad_wait() function to create a delay, and then check the button again. If the button
is no longer in a pushed state, then the push is interpreted as a bounce (or an error), and the cycle
begins again. When the signal
Page 54
is present both before and after the delay, it is likely that the mechanism has stopped bouncing and
the keypress can be registered.
5.4—
Libraries
Libraries are the traditional mechanism for modular compile-time code reuse. C for embedded
systems can make use of libraries as an organizational tool.
•The associated header file should declare the variables and functions within the library as
extern.
•The linking process is simpler than that for desktop software development. There is no need to
archive object files, and there is no dynamic linking to worry about.
•It is unacceptable in embedded software for unreferenced functions to be left in the object file
during linking. In the Byte Craft compiler, the #pragma library and #pragma
endlibrary bounding statements identify that not all routines within a library need to be linked
in. The ROM space saved is worth the extra effort on the part of the compiler to extract only
referenced routines.
•Peering into the code generated for libraries is as important as seeing the code for the main
module. The statement #pragma option +l; within a library causes the compiler to add the
source and assembly code from the library into the listing file of the final program.
5.5—
First Look at an Embedded C Program
Traditionally, the first program a developer writes in C is one that displays the message ''Hello
World!" on the computer screen.
In the world of 8-bit microcontrollers, there is no environment that provides standard input and
output. Some C compilers provide a stdio library, but the interpretation of input and output differs
from that of a desktop system with pipes and shell environments.
The following introductory program is a good "Hello World!" equivalent. The program tests to see if
a button attached to a controller port has been pushed. If the button has been pushed, the program
turns on an LED attached to the port, waits, and then turns it back off.
Page 55
#include <hc705c8.h>
/* #pragma portrw PORTA @ 0x0A; is declared in header
#pragma portw DDRA @ 0x8A; is declared in header */
#include <port.h>
#define ON 1
#define OFF 0
#define PUSHED 1
void main(void){
DDRA = IIIIIII0; /* pin 0 to output, pin 1 to input,
rest don't matter */
while (1){
if (PORTA.1 == PUSHED){
wait(1); /* is it a valid push? */
if (PORTA.1 == PUSHED){
PORTA.0 = ON; /* turn on light */
wait(10); /* short delay */
PORTA.0 = OFF; /* turn off light */
}
}
}
} /* end main */
Page 57
Chapter 6—
Data Types and Variables
Due to the restricted environment of embedded controllers, standard C variables and data types take
on new characteristics.
The most drastic change takes the default integer type to 8 or 16 bits. While quite acceptable from a
C point of view, programmers used to inexpensive 32-bit values need to adjust to the new
environment. By default, the Byte Craft compiler creates 8 bit ints, while a long or long int
data type is two bytes in size.
Embedded compilers expose standard C types, and several additional data types that are appropriate
for embedded development. The embedded world brings a new aspect to type conversion, too.
Casting is one task that is made easier by the compiler, but casting can more readily lose
information and interfere with values destined for use in a context such as peripheral control.
The other substantial change involves data types and variables with important side effects.
•Constants or initialized variables will consume a more significant proportion of ROM, as well as
RAM. Global variable declarations that contain an initialization will automatically generate machine
code to place a value at the allocated address shortly after reset. In the Byte Craft com-
Page 58
piler, one or more global variable initializations will generate code to zero all variable RAM before
assigning the initialization values to the variables.
•Variables of type register are available, but the scarcity of registers in the typical 8-bit
architecture makes them more volatile than usual.
•In the Byte Craft compiler, a simple assignment to or evaluation of a variable declared to be within
a SPECIAL memory area can generate a subroutine call. The driver subroutine that reads or writes
the value can take significant time to execute if it is communicating with an external device.
Beyond the built-in types, programmers can define their own custom types, as usual.
When the compiler comes across a variable declaration, it checks that the variable has not
previously been declared and then allocates an appropriately-sized block of RAM. For example, a
char variable will by default require a single word (8 bits) of RAM or data memory. Data type
modifiers influence the size and treatment of the memory allocated for variables.
Storage modifiers affect when memory is allocated and how it is considered free to be re-used.
•Some variables are meant to be allocated once only across several modules. Even previously-
compiled modules may need to access a common variable. The compilation units — libraries or
object files — must identify these as external symbols using the extern storage class modifier.
•Non-static variables that are of mutually-exclusive scope are likely to be overlaid. Embedded C
regards scope in much the same way that standard C does, but there is an extra effort to use scope to
help conserve memory resources.
•The compiler will reinitialize local variables, if appropriate, on each entry into the subroutine.
These variables are deemed to be declared as auto . Local variables declared as static are left
alone at the start of the function; if they have an initial value, the Byte Craft compiler assigns it
once, in the manner of a global initialization.
Embedded-specific interpretations of each of the C data type and storage modifiers are shown in
Table 6.1.
Page 59
6.1—
Identifier Declaration
As the compiler reads a program, it records all identifier names in a symbol table. The compiler uses
the symbol table internally as a reference to keep track of the identifiers: their name, type, and the
location in memory that they represent. Most compilers support identifier names of at least 31
characters.
It is sometimes necessary or desirable to direct the placement of variables. The Byte Craft compiler
interprets the @ operator and a number following the identifier as the location at which the variable
value should be stored. The @ operator is also used to associate port registers with identifiers in
#pragma port statements. These identifiers occupy the same name space as RAM and ROM
memory variable identifiers.
6.1.1—
Special Data Types and Data Access
Every bit of RAM is precious. Even if unused RAM on a peripheral device is not within the
immediate address space of the processor, subtle techniques can make it appear to be. Declaring a
memory space as SPECIAL requires you to write routines to read and write data to and from the
peripheral. The tradeoff is with performance.
Page 60
int eeprom i;
Accessing the variable declared to be within the special memory area will take some time, but the
compiler will allow the process to be transparent.
6.2—
Function Data Types
A function data type determines the value that a subroutine can return. For example, a function of
type int returns a signed integer value.
Without a specific return type, any function returns an int. An embedded C compiler provides for
this even in the case of main(), though returning is not anticipated. To avoid confusion, you
should always declare main() with return type void .
Y
Some other specially-named functions will have predetermined types; those that implement interrupt
FL
coding, for example, will be of type void unless there is some method for an interrupt to return a
value. The Scenix SX returns a value to support virtual peripherals, and so its interrupt handler will
have a function data type of int.
AM
Parameter data types indicate the values to be passed in to the function, and the memory to be
reserved for storing them. A function declared without any parameters (i.e., with empty parentheses)
TE
The compiler allocates memory differently depending upon the target part. For instance, the Byte
Craft compiler passes the first two (byte-sized) parameters through an accumulator and another
register in the processor. If local memory is specifically declared, the compiler will allocate
parameter passing locations out of that space.
6.3—
The Character Data Type
The C character data type, char , stores character values and is allocated one byte of memory space.
The most common use of alphabetic information is
Team-Fly®
Page 61
output to an LCD panel or input from a keyswitch device, where each letter used is indicated by a
character value.
6.4—
Integer Data Types
Integer values can be stored as int, short, or long data types. The size of int values is usually
16 bits on 8-bit architectures. The Byte Craft compiler's default int size is switchable between 8
and 16 bits.
The short data type helps compensate for varying sizes of int. On many traditional C platforms,
the size of an int is more than two bytes. On platforms in which an int is greater than two bytes,
a short should be two bytes in size. On platforms in which an int is one or two bytes in size —
most 8-bit microcontrollers — the short data type will typically occupy a single byte.
Should your program need to manipulate values larger than an int, you can use the long data
type. On most platforms the long data type reserves twice as much memory as the int data type.
On 8-bit microcontrollers, the long data type typically occupies 16 bits.
It is important to note that long integer values are almost always stored in a memory block larger
than the natural size for the computer. This means that the compiler must typically generate more
machine instructions when a program uses long values.
long and short are useful because they are less likely to change between a target with a natural
8-bit data type and one that delves into 16-bit values. In cases of a switchable int, you can
maintain code portability by using short for those values that require 8 bits, and long for values
which require 16 bits.
Like the int, the short and long data types uses a sign bit by default and can therefore contain
negative numbers.
6.4.1—
Byte Craft's Sized Integers
The Byte Craft compiler recognizes int8 , int16, int24, and int32 data types. They are
integers with the appropriate number of bits. These remove the ambiguity of varying or switchable
integer sizes.
6.5—
Bit Data Types
ISO/IEC 9899:1999 specifies the _Bool type. Variables of type _Bool can hold a 0 or 1. This is a
new addition to the C standard.
The Byte Craft compilers supply two types for bit-sized quantities: bit and bits. A bit value is
a single independent bit, which the compiler places and manages depending upon the capabilities of
the processor.
A bits variable is a structure of 8 bits, managed together and individually addressable using
structure member notation. You can assign a byte value directly to a bits variable, and then
address individual bits.
bits switch_fixup(void)
{
00EB 0000 bit heat_flag;
00EB 0001 bit cool_flag;
00EA bits switches;
6.6—
Real Numbers
While many desktop computer applications make extensive use of real or floating point numbers
(numbers with digits on both sides of the decimal place), 8-bit microcontroller applications do not.
The resources needed to store and manipulate floating point numbers can place overwhelming
demands on an 8-bit computer. Usually, the value gained is not worth the resources expended.
The fundamental data type for representing real numbers in C is the float type. The maximum
value for the target computer is defined in a C header file called values.h as a symbolic constant
called MAXFLOAT.
C compilers generally allocate four bytes for a float variable, which provides approximately six
digits of precision to the right of the decimal. You can have greater precision with the double and
long double data types. Compilers typically allocate eight bytes for a double variable and
more for a long double. There are approximately 15 digits of precision with double values
and perhaps more from long double values.
Another format, IEEE 754, specifies a 4- or 3-byte format for floating-point numbers.
You can assign an integer value to a floating point data type, but you must include a decimal and a 0
to the right of the decimal.
myFloatVariable = 2.0;
6.7—
Complex Data Types
Complex data types include pointers, arrays, enumerated types, unions, and structures. Even within
the restricted resources of an 8-bit microcontroller, complex data types are useful in organizing an
embedded program.
6.7.1—
Pointers
The implementation of pointer variables is heavily dependent upon the instruction set of the target
processor. The generated code will be simpler if the processor has an indirect or indexed addressing
mode.
It is important to remember that Harvard architectures have two different address spaces, and so the
interpretation of pointers can change. A dereference of a RAM location will use different
instructions than a dereference into ROM.
Page 64
It is also important to differentiate between near and far pointers. The differences in code
generation can be significant. For more information, see Section 6.9.4, Pointer Size Modifiers:
near and far.
6.7.2—
Arrays
When you declare an array, you must declare both an array type and the number of elements it
contains. For example, the following declares an array containing eight int elements.
int myIntArray[8];
When you declare an array, a single, contiguous block of memory is reserved to hold it. This is why
you must specify the array size or assign the contents in the declaration.
07FE 03 32
0332 AE C0 LDX #$C0
0334 7F CLR ,X
0335 5C INCX
0336 A3 EB CPX #$EB
0338 26 FA BNE $0334
Page 65
033A 5F CLRX
033B D6 03 48 LDA $0348,X
033E E7 C8 STA $C8,X
0340 5C INCX
0341 A3 08 CPX #$08
0343 26 F6 BNE $033B
0348 01 02 04 08 10 20 40 80
There are some restrictions on or disadvantages to using arrays in embedded C programming. They
arise because of the available methods of indexing into an array.
The Byte Craft compiler forbids arrays of struct and union. This restriction arises because of
the difficulty in addressing members of the data structures, which are themselves being addressed as
array members. To overcome this limitation, you can use several global arrays of basic data types,
and organize them together by context.
6.7.3—
Enumerated Types
For any list of enumerated elements, the compiler supplies a range of integer values beginning with
0 by default. While in many cases this is sufficient to identify elements in the set, in embedded C
you may wish to associate the enumerated set to a device-dependent progression. Enumerated
elements can be set to any integer values in two ways.
1. Specify values for each enumerated element. The following example is from the COP8SAA7
WATCHDOG service register WDSVR. Bits 6 and 7 of this register select an upper limit to the
service window that selects WATCHDOG service time.
Since character constants are stored as integer values, they can be specified as values in an
enumerated list.
will store the appropriate integer values of machine character set (usually ASCII) for each digit
specified in the element list.
2. Specify a starting value for one or more of the enumerated elements. By default, the compiler
assigns the value 0 to the first element in the list. You can set the list to begin with another value.
When the compiler encounters an element in an enumerated list without an assigned value, it counts
from the last value that was specified. For example, the following enumerated list specifies the
appropriate values for its elements.
6.7.4—
Structures
Structures support the meaningful grouping of program data. Building understandable data
structures is one key to the effectiveness of a new program.
The following declaration creates a structured type for an extended time counter and describes each
element within the structure. The display is defined as having the components hours, minutes,
seconds, and an AM/PM flag. Later, a variable timetext is declared to be of type struct
display.
struct display {
unsigned int hours;
unsigned int minutes;
unsigned int seconds;
Page 67
char AorP;
};
The Byte Craft compiler permits structures of bit fields, with individual fields taking less than 8 bits.
Using bit fields allows the declaration of a structure that takes up the minimum amount of space
needed: several fields could occupy one single byte.
The following example for the Motorola MC68HC705C8 defines the Timer Control Register (TCR)
bits as bit fields in the structure called TCR, and uses the structure to configure the timer output
compare.
struct reg_tag {
int ICIE : 1; /* field ICIE, 1 bit long */
int OCIE : 1; /* field OCIE, 1 bit long */
int notUsed : 3 = 0; /* notUsed is 3 bits and set to 0 */
int IEDG : 1; /* field IEDG 1 bit long */
int OLVL : 1; /* field OLVL 1 bit long */
} TCR;
The Byte Craft compiler can span a bit field across two bytes. Not all compilers support this
optimization, however. In the worst case, the following structure would place the second field
entirely in a separate word of memory from the first.
struct {
unsigned int shortElement : 1; /* 1 bit in size */
unsigned int longElement : 7; /* 7 bits in size */
} myBitField; /* could be 1 byte, worst case 2 */
Page 68
The order in which the compiler stores elements in a structure bit field also varies from compiler to
compiler.
Bit field elements behave exactly as an unsigned int of the same size. Thus, an element occupying
a single bit could have an integer value of either 0 or 1, while an element occupying two bits could
have any integer value ranging from 0–3. You can use each field in calculations and expressions
exactly as you would an int.
6.7.5—
Unions
C programmers developing for traditional platforms do not often use the union data type, but it is a
very useful resource for the embedded system developer. The union type interprets data stored in a
single block of memory based on one of several associated data types.
One common use of the union type in embedded systems is to create a scratch pad variable that
can hold different types of data. This saves memory by reusing one 16-bit block in every function
that requires a temporary variable. The following example shows a declaration to create such a
variable.
struct lohi_tag{
short lowByte;
short hiByte;
};
union tagName {
int asInt;
char asChar;
short asShort:
long asLong;
int near * asNPtr;
int far * asFPtr;
struct hilo_tag asWord;
} scratchPad;
Another common use for union is to facilitate access to data as different types. For example, the
Microchip PIC16C74 has a 16-bit timer/counter register called TMR1. TMR1 is made up of two 8-
bit registers called TMR1H (high byte) and TMR1L (low byte).
Page 69
It might be desirable to access either of the 8-bit halves, without resorting to pointer manipulation. A
union will facilitate this type of data access.
struct asByte {
int TMR1H; /* high byte */
int TMR1L; /* low byte */
}
union TIMER1_tag {
long TMR1_word; /* access as 16 bit register */
struct asByte halves;
} TMR1;
/* ... */
seed = TMR1.halves.TMR1L;
Since the compiler uses a single block of memory for the entire union, it allocates a block large
enough for the largest element in the union. The compiler will align the first bits of each element in
the lowest address in the memory block. If you assign a 16-bit value to scratchPad and then read
it as an 8-bit value, the compiler will return the first 8 bits of the data stored.
If you arbitrarily extract one byte of a 16-bit variable, the value returned will differ depending on the
endianness of the processor architecture. As mentioned in Section 5.2.3, Endianness, C does not
contemplate endianness.
6.8—
typedef
The typedef keyword defines a new variable type in terms of existing types. The compiler cares
most about the size of the new type, to determine the amount of RAM or ROM to reserve.
Page 70
typedef struct {
char * name;
int start;
int min_temp;
int max_temp;
} time_record;
time_record targets[] {
{ "Night", 0, 20, 25},
{ "Day", 5*3600, 20, 25},
{ "Evening", 18*3600, 20, 25},
}
6.9—
Data Type Modifiers
The C language allows you to modify the default characteristics of simple data types. Mainly, these
Y
data type modifiers alter the range of allowable values.
FL
Type modifiers apply to data only, not to functions. You can use them with variables, parameters,
AM
Some type modifiers can be used with any variable, while others are used with a set of specific
types.
TE
6.9.1—
Value Constancy Modifiers:
const and volatile
The compiler's ability to optimize a program relies on several factors. One of these is the relative
constancy of the data objects in your program. By default, variables used in a program change value
when the instruction to do so is given by the developer.
Team-Fly®
Page 71
Sometimes, you want to create variables with unchangeable values. For example, if your code
makes use of π, the constant PI, then you should place an approximation of the value in a constant
variable.
When your program is compiled, the compiler allocates ROM space for your PI variable and will
not allow the value to be changed in your code. For example, the following assignment would
produce an error at compile time (thank goodness).
PI = 3.0;
In embedded C, storage for constant data values is allocated from computer program memory space,
usually ROM or other nonvolatile storage.
declares a byte constant with an initial value of 30 decimal. The compiler will reserve far more than
just one or two bytes for a constant if any special technique is required to load the value into a
register. Due to architectural limitations, some platforms require constants to be the parameter of a
multi-byte load statement embedded in a ROM subroutine: to access the constant value, the
processor executes the dedicated load statement.
Volatile variables are variables whose values may change outside of the immediately executing
software. For example, a variable that is ''stored" at the location of a port data register will change as
the port value changes.
Using the volatile keyword informs the compiler that it can not depend upon the value of a
variable and should not perform any optimizations based on assigned values.
6.9.2—
Allowable Values Modifiers:
signed and unsigned
By default, integer data types can contain negative values. You can restrict integer data types to
positive values only. The sign value of an integer data type is assigned with the signed and
unsigned keywords.
The signed keyword forces the compiler to use the high bit of an integer variable as a sign bit. If
the sign bit is set with the value 1, then the rest of the variable is interpreted as a negative value. By
default, short, int, and long data types are signed. The char data type is unsigned by default.
To create a signed char variable, you must use a declaration such as
If you use the signed or unsigned keywords by themselves, the compiler assumes that you are
declaring an integer value. Since int values are signed by default, programmers rarely use the
syntax signed mySignedInt;.
6.9.3—
Size Modifiers:
short and long
The short and long modifiers instruct the compiler how much space to allocate for an int
variable.
The short keyword modifies an int to be of the same size as a char variable (usually 8 bits).
If you use the short keyword alone, the compiler assumes the variable is a short int type.
short myShortInt;
The long keyword modifies an int to be twice as long as a normal int variable.
6.9.4—
Pointer Size Modifiers:
near and far
The near and far keywords are influenced a great deal by the target computer
architecture.
The near keyword creates a pointer that points to objects in the bottom section of addressable
memory. These pointers occupy a single byte of memory, and the memory locations to which they
can point is limited to a bank of 256 locations, often from $0000–$00FF .
The far keyword creates a pointer that can point to any data in memory:
These pointers take two bytes of memory, which allows them to hold any legal address location
from $0000–$FFFF. far pointers usually point to objects in user ROM, such as user-defined
functions and constants.
Page 73
6.10—
Storage Class Modifiers
Storage class modifiers control memory allocation for declared identifiers. C supports four storage
class modifiers that can be used in variable declarations: extern, static, register, and
auto. Only extern is used in function declarations.
The ISO standard specifies typedef as a fifth modifier, though it explains that this is for
convenience only. typedef is described in Section 6.8, typedef.
When the compiler reads a program, it must decide how to allocate storage for each identifier. The
process used to accomplish this task is called linkage. C supports three classes of linkage: external,
internal, and none. C uses identifier linkage to sort out multiple references to the same identifier.
6.10.1—
External Linkage
References to an identifier with external linkage throughout a program all call the same object in
memory. There must be a single definition for an identifier with external linkage or the compiler
will give an error for duplicate symbol definition. By default, every function in a program has
external linkage. Also by default, any variable with global scope has external linkage.
6.10.2—
Internal Linkage
In each compilation unit, all references to an identifier with internal linkage refer to the same
object in memory. This means that you can only provide a single definition for each identifier with
internal linkage in each compilation unit of your program. A compilation unit can be more than one
file because of #include directives.
No objects in C have internal linkage by default. Any identifier with global scope (defined outside
any statement block) and with the static storage class modifier, has internal linkage. Also, any
variable identifier with local scope (defined within a statement block) and with the static storage
class modifier, has internal linkage.
Although you can create local variables with internal linkage, scoping rules restrict local variable
visibility to their enclosing statement block. This means that you can create local variables whose
values persist beyond the immediate life of the statement blocks in which they appear. Normally, the
computer shares local variable space between several different statement
Page 74
blocks. If a local variable is declared as static, space is allocated for the variable once only: the
first time the variable is encountered.
Note
Unlike other internal linkage objects, static local variables need not be unique within
the compilation unit. They must be unique within the statement block that contains
their scope.
Objects with internal linkage typically occur less frequently than objects with external or no linkage.
6.10.3—
No Linkage
References to an identifier with no linkage in a statement block refer to the same object in memory.
If you define a variable within a statement block, you must provide only one such definition.
Any variable declared within a statement block has no linkage by default, unless the static or
extern keywords are included in the declaration.
6.10.4—
The extern Modifier
int Calculate_Sum()
is declared in a library source file. An identifier with external linkage like this can be used at any
point within the same compilation unit, as long as it was previously declared.
If you want to use this function in any other compilation unit, you must tell the compiler that the
definition of the function is or will be available. The concept is identical to prototyping a function,
except that the actual definition will not appear in the same compilation unit. The function definition
is external to the compilation unit.
When the compiler encounters an external function declaration, it interprets it as a prototype for the
function name, type, and parameters. The
Page 75
extern keyword claims that the function definition is in another compilation unit. The compiler
defers resolving this reference to the linker.
If you build a library of functions to use in many programs, create a header file that includes
extern function declarations. Include this header in your compilation unit to make library
functions available to your code.
Like functions, global variables have external linkage. A global variable is a good way to present
general configuration settings for a library. This avoids an extra function call.
To create a global variable that can be read or set outside its compilation unit, you must declare it
normally within its source file and declare it as extern within a header file.
The compiler interprets an external declaration as a notice that the actual RAM or ROM allocation
happens in another compilation unit.
6.10.5—
The static Modifier
By default, all functions and variables declared in global space have external linkage and are visible
to the entire program. Sometimes you require global variables or functions that have internal
linkage: they should be visible within a single compilation unit, but not outside. Use the static
keyword to restrict the scope of variables.
Listing 6.13 Using the static data modifier to restrict the scope of variables
These declarations create global identifiers that are not accessible by any other compilation unit.
The static keyword works almost the opposite for local variables. It creates a permanent variable
local to the block in which it was declared. For example, consider the unusual task of tracking the
number of times a recursive function calls itself (the function's depth). You can accomplish this
using a static variable.
Page 76
void myRecurseFunc(void) {
static int depthCount=1;
depthCount += 1;
if ( (depthCount < 10) && (!DONE) ) {
myRecurseFunc();
}
}
myRecurseFunc contains an if statement that stops it from recursing too deeply. The static
variable depthCount is used to keep track of the current depth.
Normally, when a function is called, the computer reinitializes its automatic local variables (or at
least leaves them in a questionable state). Memory for static variables, however, is only
initialized once. The static variable depthCount retains its value between function calls.
Because depthCount is defined inside the myRecurseFunc() statement block, it is not visible
to any code outside the function.
6.10.6—
The register Modifier
When you declare a variable with the register modifier, you inform the compiler to optimize
access to the variable for speed. Traditionally, C programmers use this modifier when declaring loop
counter variables.
{
register int myCounter = 1;
while (myCounter<10) {
/* ... */
myCounter += 1;
} /* end while */
} /* enclosing block enforces reallocation of myCounter */
Unlike other storage class modifiers, register is simply a recommendation to the compiler. The
compiler may use normal memory for the variable if it is out of registers to allocate.
Page 77
Because of the scarcity of registers on 8-bit machines and the desire for size optimization rather than
speed, the register keyword is not very useful for embedded system programmers.
Notice that the technique used in the example does two things: it places the register declaration
and the while loop close together and inside a statement block. This minimizes the cost of
potentially dedicating a register to a specific variable. It also forces the compiler to reallocate
storage for myCounter as soon as the loop is finished: if the compiler uses a register to store
myCounter, it will not tie up the register longer than necessary.
6.10.7—
The auto Modifier
The auto keyword denotes a temporary variable (as opposed to static). You can only use auto
with local variables, because C does not support functions within a block scope. Since all variables
declared inside a statement block have no linkage by default, the only reason to use the auto
keyword is for clarity.
In this example, we declare tempNodePtr as an auto variable to make it clear that, unlike the
global TheStructRoot pointer, tempNodePtr is only a temporary variable.
Page 79
Chapter 7—
C Statements, Structures, and Operations
Part of the benefit of using C for programming is the availability of mathematical expression.
Beyond simple constant calculations, assembly forces you into a rigorous, procedural structure. C
provides assignment statements, logical and arithmetic expressions, and control structures that allow
you to express yourself using common math notation and helpful metaphors.
7.1—
Combining Statements in a Block
You create statement blocks for your functions, and at other times for the bodies of control
statements. For instance, the general format for the while statement looks like the following.
Since you can substitute a statement block anywhere a single statement can occur, the while
statement most commonly appears as follows.
while (condition){
statements
}
7.2—
Functions
When the compiler reaches the function definition, it generates machine instructions to implement
the functionality, and reserves enough program memory to hold the statements in the function. The
address of the function is available through the symbol table.
A function definition includes a statement block that contains all function statements. Even if a
function has only a single executable statement, it must be enclosed in a statement block.
Embedded C supports function prototypes. Function prototype declarations ensure that the
compiler knows about a function and its parameter types, even if its definition has yet to appear in
the compiler's input. Prototypes assist in checking forward calls. The function name is recorded as
an identifier, and is therefore known when invoked in code prior to its definition.
Header files of function prototypes provide the foundation for using libraries.
The syntax for a function call in C is the function name and a list of actual parameters surrounded
by parentheses.
Function calling is one area in which embedded C differs substantially from traditional C. The way
that parameters are passed differs significantly, as well as the permitted number of parameters.
Functions that produce extensive side effects are harder to maintain and debug, especially for
members of a development team. To safely use abstract functions, you need to know only the data
that goes in and comes out — the function interface. When a function produces side effects, you
need to know about the interface and behaviour to use it safely.
Some C programmers insist that functions that just produce side effects should return a value to
indicate success, failure, or error. Since ROM space is at a premium, the code needed to evaluate the
return status is a luxury.
Page 81
7.2.1—
Function Parameters
C for embedded processors places some unique restrictions on function calls. Some compilers
restrict the number of parameters that can be passed to a function. Two byte-sized parameters (or
one 16-bit parameter) can be passed within the common processor registers (accumulator and index
To pass by reference, pass a pointer as usual. See information on pointers in Section 6.7.1,
Pointers, for extra information about the relative cost of using pointers.
int myFunc()
However, it is good practice to specify that the function has no parameters with the void parameter
type.
int myFunc(void)
While the flow of some embedded C programs will appear strange at first (the prominence of
while(1), for instance), they are not fundamentally different than those in C for personal
computing.
TE
7.3.1—
The main() Function
It may seem incongruous that an embedded program, which has no operating system to invoke it,
has a traditional main() function and an explicit return value specification. What invokes main
()? Where will the function return?
Embedded C retains the main() function for compatibility with standard C. The return type of
main() should always explicitly be declared as void; omitting it, as mentioned in Section 6.2,
Function Data Types, causes it to be understood as an int return.
From there, the main() function can execute code from other functions and receive return values.
Remember to make your called functions available to main() by prototyping them, if necessary.
Team-Fly®
Page 82
7.3.2—
Initialization Functions
Embedded C also permits specialized initialization routines. __STARTUP() is one such function
understood by the Byte Craft compiler. If it is present, its statements are executed before control is
passed to main().
You can better organize initialization tasks with a separate initialization function. Device-dependent
hardware initialization, which must be rewritten for each target device, can live in the __STARTUP
routine or equivalent.
7.3.3—
Control Statements
Embedded developers often use program control statements that are avoided by other programmers.
For example, the goto statement is used in C in the same contexts as an explicit jump or
unconditional branch instruction would be used in assembly.
7.4—
Decision Structures
C provides three structures the programmer can use to support different types of decisions. Decision
structures test an expression to determine which statement or statement block to execute.
The switch..case structure chooses between several different possible paths of code to execute.
The switch..case structure is compiled to a structure resembling a string of if..elses.
switch(choice) {
case 1: return 5;
0304 A1 01 CMP #$01
0306 26 03 BNE $030B
0308 A6 05 LDA #$05
030A 81 RTS
Page 83
The Byte Craft compiler can extend the case label to deal with common programming problems.
These two examples would require a great deal more generated code if the compiler accepted only
single integer values for each case label.
The benefit of such structures is in avoiding recomparing the switch argument for each integer
value within a range of cases. The compiler can generate simple comparisons to deal with ranges or
lists of alternate values.
case '0'..'9':
{
0473 A1 30 CMP #$30
0475 25 24 BCS $049B /* branch if less */
0477 A1 3A CMP #$3A
0479 24 20 BCC $049B /* branch if greater */
047B AE DA LDX #$DA
047D CD 05 4B JSR $054B scanf(&temperature,ch);
Page 84
7.5—
Looping Structures
C control structures allow you to make a decision on the path of code execution. C also provides
looping structures for control over program flow. Loop control structures allow you to repeat a set of
statements.
while plays an interesting role in embedded C. You will often use while to intentionally create
infinite loops. An embedded controller typically executes a single program "infinitely", so this
structure is appropriate.
The alternative, using a goto , requires you to use a label; the compiler will implement the while
(1) decision with an unconditional jump or branch instruction anyway.
void main(void)
{
while(1)
{
0300 B6 01 LDA $01 PORTB = PORTB << 1;
0302 48 LSLA
0303 B7 01 STA $01
0305 20 F9 BRA $0300 }
}
7.5.4—
Control Expression
The key component of any loop structure is the control expression. At some point in each iteration,
the control expression is tested. If the control expression evaluates to 0, program execution passes to
the first statement following the loop structure. If the expression evaluates to 1, execution continues
within the loop structure statement block.
7.5.5—
break and continue
C provides two ways to escape a looping structure: the break and continue statements. When
either of these statements is encountered inside a loop, any remaining statements inside the loop are
ignored.
Page 85
Use a break statement to completely break out of a structure. When a break is encountered inside
a looping structure, the loop terminates immediately and execution passes to the statement following
the loop.
You may wish to jump to the next iteration of a loop without breaking out of the loop entirely. A
continue statement will allow you to do this. When a continue statement is encountered inside
a looping structure, execution passes immediately to the end of the loop statement block.
If continue is used with a while or for loop, execution jumps from the end of the statement
block to the control expression at the top of the loop. If used with a do loop, execution passes from
the end of the statement block to the control expression at the bottom of the loop. In all cases, the
effect is the same — a continue statement does not circumvent the loop control expression, but it
does skip any statements remaining in the loop iteration.
The most common place for a break statement is inside a switch..case structure. Since
switch..case is not a looping structure, a continue statement within it refers to the enclosing
loop structure (if any).
while(1)
{
030D AD F1 BSR $0300 ch = getch();
030F B7 EB STA $EB
switch(ch)
{
case '0'..'9':
{
0311 A1 30 CMP #$30 putch(ch);
0313 25 08 BCS $031D
0315 A1 3A CMP #$3A
0317 24 04 BCC $031D
0319 AD E8 BSR $0303
031B 20 10 BRA $032D break; /* after switch */
}
case 'A'.. C':
{
Page 86
7.6—
Operators and Expressions
Using C for embedded programming relieves the tedium of coding large arithmetic operations by
hand. Where a 32-bit integer divide operation may be encompassed by one instruction on a general-
purpose microprocessor, an 8-bit controller will need a series of loads and stores, in addition to the
simplified math operations, to perform the equivalent work.
With embedded systems, there is an increased emphasis on bitwise operations. Both for peripheral
operation and for memory efficiency, the compiler will try wherever possible to use bit-
manipulation instructions to implement bitwise operators.
7.6.1—
Standard Math Operators
?
Page 87
If no instruction is available, the compiler will provide multiply, as well as divide, and modulus as
functions. The Byte Craft compilers do this automatically if the operations are used.
7.6.2—
Bit Logical Operators
C supports one unary and three binary bitwise logical operators. Each of these operators act only
upon values stored in the char, short int , int, and long int data types.
Note
Binary logical operators perform data promotion on operands to ensure both are of
equivalent size. If you specify one short operand and one long operand, the
compiler will widen the short to occupy the long 16 bits. The expression will
return its value as a 16-bit integer.
The bitwise AND operator, &, produces a bit-level logical AND for each pair of bits in its operands.
For example, if both operands have bit 0 set, then the result of the bitwise AND expression has bit 0
set.
The AND operation is easier to imagine if your compiler has an extension that permits data values in
binary.
Listing 7.7 Using the AND bitwise operator with binary values
int x=0b00000101,
y=0b00000111,
z;
z = x & y;/* z gets the value 00000101, or 5 */
Page 88
The bitwise OR operator, |, performs a bit -level logical OR for each pair of bits in its operands. If
either operand has a bit in a specific position set, then the result of the bitwise OR expression has
that bit set.
int x=0b00000101,
y=0b00000111,
z;
z = x | y;/* z gets the value 00000111, or 7 */
The bitwise XOR operator, ^, produces a bit-level logical exclusive OR for each pair of bits in the
operand. XOR sets a bit when one of the operands has a bit set in that position, but not if both
operands have the bit set. This produces a result with bits set that the operands do not share.
int x=0b00000101,
y=0b00000111,
z;
z = x ^ y;/* z gets the value 00000010, or 2 */
The bitwise NOT operator, ~, produces the complement of a binary value. Each bit that was set in
the operand is cleared and each cleared bit is set.
int x=0b00000101,
z;
z = ~x;/* z gets the value 11111010, or 250 */
If you apply bitwise operators to individual bits, the compiler will use bit manipulation instructions,
if they are available. They avoid unintended side effects from reads or writes to other bits.
Page 89
7.6.3—
Bit Shift Operators
The right shift operator shifts the data right by the specified number of positions. Bits shifted out the
right side disappear. With unsigned integer values, 0s are shifted in at the high end, as necessary.
For signed types, the values shifted in is implementation-dependant. The binary number is shifted
right by number bits.
x >> number;
The left shift operator shifts the data right by the specified number of positions. Bits shifted out the
left side disappear and new bits coming in are 0s. The binary number is shifted left by number bits.
x << number;
porta = 0b10000000;
while (porta.7 != 1){
porta >> 1;
Page 90
}
while (porta.0 != 1){
porta << 1;
}
Shifting by a variable number of bits can create a substantial loop structure in code. This presents an
extra cost in ROM space that you must keep in mind.
Chapter 8—
Libraries
Libraries contain functions that serve a common purpose and a wide range of development projects.
Embedded and desktop systems share some library needs (e.g., enhanced mathematical functionality
or data type conversion). Libraries are the typical generic structure for cataloguing and transporting
this specialized knowledge.
Embedded systems can rely on libraries even more: a library can provide device drivers for a
common LCD controller or a timer peripheral. Programmers can be overwhelmed by taking
responsibility for everything within an embedded system. A programmer can relax and focus on the
core of the project if they have libraries to help them with direct manipulation of hardware
peripheral devices.
Since C is intended to be highly portable, libraries are a way to organize platform dependency. Main
line C code written for one specific 8-bit microcontroller can therefore be compiled for and run on a
different microcontroller with very minor changes to the code. Without the portability offered by
libraries, your investment in a particular architecture grows, and it becomes less attractive to seek
out a less-expensive processor option.
Y
FL
AM
TE
Team-Fly®
Page 92
The Byte Craft Code Development System products ship with a range of useful portable libraries
(and traditional API-style documentation). They provide routines for the most common features of
8-bit embedded systems.
•Standard I/O
With appropriate configuration, you can deal with a keypad and LCD display as standard input and
output.
•MICROWIRE bus
A UART is a prime candidate for replacement by ''bit banging" software, which could be
encapsulated within a library.
•I/O ports
While manipulating I/O ports is usually a matter of a few assignment statements, there is some
benefit in abstracting the port from the particular implementation.
•LCD displays
These routines can support the standard I/O model, and provide convenience routines for clearing
the display and moving the cursor.
•Timers
8.1—
Creating Libraries
For the thermostat, we need to display the current time and preset cycle start times, as a string. A
time string is seven bytes long.
In the thermostat, we are really tracking four times: the current time and three cycle start times.
There are several alternative ways to store these values, each with tradeoffs. Directly manipulating
the string representations is unworkable: it requires consuming a full quarter of working RAM, and
there would be lots of code to perform very odd carries and compares.
Page 93
Unsigned long variables as minute counters (0–1439) proved expensive in terms of ROM, but used
only 8 bytes of RAM (and scratchpad). Structures of time counter components (i.e., hours, minutes,
and am/pm) served better, but an array of them was not possible.
Two arrays of integers, one for hours and one for minutes, seemed best. Array element 0 is a good
choice for the current time, and 1–3 for the daily cycle start times.
For text representation of the time, we need to translate from a time counter value (two integers) into
a timestamp string. Different projects will use this type of functionality, so we will package it as a
library. We concluded that both 24-hour and 12-hour systems need to be supported, and the switch
between 12-hour and 24-hour should be a run-time configuration.
#ifndef __TIMESTMP_C
#define __TIMESTMP_C
#pragma library;
#include <timestmp.h>
/* Declared above:
bit use_metric = 0:
char buffer[7];
*/
Page 94
#pragma endlibrary;
#endif /* __TIMESTMP_C */
#ifndef __TIMESTMP_H
#define __TIMESTMP_H
bit use_metric;
char buffer[7];
#endif /* __TIMESTMP_H */
This is the skeleton of a library. When the library is completed, place the .lib file with the other
libraries, and the .h file with the other include files.
Page 95
8.2—
Writing the Library
The library software is much like other embedded programming. We have, in previous sections,
outlined what techniques are safe, what techniques are expensive, and what techniques are
impossible in the embedded environment.
MinutesToTime() accepts an hour integer and a minute integer. It inspects the use_metric
flag, and renders the time in buffer[].
/* Set up string */
buffer[5] = 'h'; buffer[6] = 0; buffer[2] = ':';
/* Fill in hours */
buffer[0] = '0';
for(i = '2'; hours >= 10; hours -= 10, i--);
buffer[0] = i;
buffer[1] = hours + '0';
Page 96
/* Fill in minutes */
buffer[3] = '0';
for(i = '5'; minutes >= 10; minutes -= 10, i--);
buffer[3] = i;
buffer[4] = minutes + '0';
}
Alternatively, you could unroll the bottom for loops to avoid the loop management code.
TimeToMinutes(), which isn't used in the thermostat project, is the reverse function. We include
it because it is simple and useful. In the thermostat project, time adjustments are made with hour and
minute increment buttons, much like an alarm clock. If ROM permitted, the configuration could be
rewritten to allow the user to enter the time using digits: the extra code for checking the digits
entered against valid times was substantial.
TimeToMinutes() accepts pointers to the hours and minutes integers that should receive the
translated values. Note they are near pointers, which should prove to be 8-bit values.
8.3—
Libraries and Linking
With the Byte Craft compilers, there are two scenarios for library use: traditional linking with
BClink and Absolute Code Mode.
As previously presented, the timestmp library source files are written for Absolute Code Mode.
To use them, write your main module as follows.
void main(void) {
/* ... */
}
#include <timestmp.c>
To make timestmp suitable for linking, you need to add some conditional defines to the library
header. Ideally, the header file should allow both Absolute Code Mode and traditional linking. Use
the MAKEOBJECT symbol to choose between the two as shown in Listing 8.6.
Listing 8.6 Header file for both linking and Absolute Code Mode
#ifndef __TIMESTMP_H
#define __TIMESTMP_H
ifdef MAKEOBJECT
#else /* MAKEOBJECT */
Page 98
bit use_metric;
char buffer[7];
#endif /* MAKEOBJECT */
#endif /* __TIMESTMP_H */
No changes are needed for timestmp.c if it includes the header file itself.
You can define MAKEOBJECT on the command line when you create the library object file. Invoke
where cds is your compiler executable name. Copy the .lib file to the libraries directory and
the .h file to the headers directory.
Defining the MAKEOBJECT symbol will cause the functions and variables to be extern, and will
include a definitions file. The definitions file is a device header file with definitions for all the
important device symbols (e.g., ports, timer registers, and so on). The most common values are
present in it, but these are not important: the compiler uses the definitions file to compile the library
to object without depending upon a particular device header file. During linking, the actual device
values will be matched with the references in the object file.
Some Byte Craft compilers define the symbol MAKEOBJECT automatically when compiling to an
object file (+o is present on the command line).
One other customization is helpful: buffer[] is a 7-byte string in RAM that you may wish to
declare in other ways (for instance, as SPECIAL memory). You can conditionalize its declaration
with an #ifndef if you are using Absolute Code Mode.
Page 99
Chapter 9—
Optimizing and Testing Embedded C Programs
As in any other programming endeavour, getting the code to compile ensures only linguistic
correctness. Without understanding the capabilities of the compiler, we have no real certainty about
how to read the generated code.
Without understanding the compiler's limitations, we have no way of adding in human intuition.
Compilers are best at relieving drudgery: they are no match for inspired programming.
Testing embedded software differs significantly from testing desktop software. One new central
concern arises: embedded software often plays a much more visceral role. Where a protection fault
on a desktop machine may cost the user hours of work, a software fault in an embedded system may
threaten:
•a lifeline of communication, or
The issue of life-supporting devices is outside the scope of this book. Devices meant for human
implant, or for monitoring or regulating health-related factors, are life-supporting devices. It is
debatable whether compiled code should be used in these devices. The motivation for compiled code
is relief from having to write assembly code from scratch. The risks of life-supporting activities
cannot permit such luxury.
Decisions about development testing software are first made when evaluating processor options. For
more information about tools, see Section 3.7, Development Tools for a Microcontroller.
9.1—
Optimization
Anyone interested in the art and science of compilers soon learns that optimization is the perpetual
goal of the compiler writer. Any interesting fact about the code that the compiler can recognize
becomes a candidate for optimization.
While some might feel that laborious hand-coding of assembly is the only way to really massage the
code, a compiler that is detached and objective can find otherwise hidden patterns suitable for
reduction.
The need for optimization is never greater than in embedded environments. For the 8-bit
microcontroller, successful optimization primarily reduces the amount of ROM and RAM used. This
is the acid test of code generation. Increasing execution speed comes a distant second.
There is a host of traditional strategies for optimizing generated code. You can trust that the
compiler watches for these factors.
Register Data Flow The compiler can recognize if a variable will be loaded into a register twice,
and remove the redundancy.
Code That Is Redundant or Dead Code governed by expressions that will never prove true can be
ignored at compile time. Code following a break or continue statement that will never be
executed, due to constants within the control structure, can be discarded.
Page 101
Adjacent Instruction Reductions A pattern of simple instructions can be reduced into a more
complex operation, such as an instruction with an auto-increment side-effect.
Constant Folding This evaluates constant values in the source and combines them if they are the
same.
Lofting Instructions within a loop that do not directly pertain to it can be lofted to an enclosing
syntax level.
Arithmetic Operations Involving Low Value Constants Operands of zero, one, and two can be
changed into instructions like increment or decrement to reduce code size and improve execution
time. No code is generated for adding 0, subtracting 0, or multiplying or dividing by 1.
Edge Effects Code that causes values to roll over within their variables can be a candidate for
special treatment.
Long Operations In controllers that have only 8-bit registers, long operations cost far more than
twice the instructions (some controllers can pair registers into a 16-bit variable and use it for longs).
Any knowledge about the range of possible values can determine whether to ignore either the top or
bottom bytes of a 16-bit variable.
Array Calculations Fixed references to an array element are dereferenced at compile time. This
avoids overwriting an index register.
Y
9.1.1—
FL
Instruction Set-Dependent Optimizations
AM
•++ increments a memory location, and -- decrements a memory location. If the variable is long,
the carry must be preserved with subsequent instructions.
•Bit operations can be conducted using bit set and bit clear instructions instead of using a multibyte
sequence that does a load, bitwise AND or OR, and store.
Team-Fly®
Page 102
9.2—
Hand Optimization
If a compiler is charged with taking a high-level program and generating optimized machine
language, why should hand optimization be a concern? For all its capability, a compiler cannot see
''the big picture". Sometimes it follows your high-level directions too well.
Examining Register Use In small routines, a register that starts out holding a function parameter
may be otherwise unused, especially if the routine manipulates memory directly (i.e., bit
manipulation with specialized instructions). Our normal reflex is to declare function parameters as
int, which will most likely cause local RAM to be reserved for the value. Declaring the function
parameter as a register type (registera or equivalent on Byte Craft compilers) saves the byte.
Rolling and Unrolling for Loops It may seem unintuitive to unroll an easily-understood short
loop, but the savings in ROM space may make it profitable. The opportunity to look for is expensive
code generated for the condition and action parts of the loop.
Using Ports as Variables Do not underestimate the desperation with which embedded
programmers pursue savings in RAM usage. If an output port can be read safely to determine the
current state of the output pins, and the port needs a looping operation, there is no reason not to use
the port itself as an index variable. Consider the following.
void walk_through_A(void)
{
for(PORTA = 0x01; PORTA != 0; ASL(PORTA))
delay_100us(10);
}
If, in this example, a separate char had been used to index the loop and assign to the port, there is
no reason to think that the compiler could omit the otherwise unused variable. The compiler
considers ports volatile, but we
Page 103
can determine from the design whether the port in this case will act in a volatile manner.
9.2.1—
Manual Variable Tweaking
In a traditional C environment, compilers can allocate variables without too much hand-wringing.
For instance, it is common to allocate a new location for each counter variable name within a scope.
void up_and_down(void)
{
int up, down; /* probably separate locations */
To minimize RAM usage, embedded systems developers will often create global loop counter
variables. Any function can then use this allocated block of data memory when a counter or
temporary variable is needed. The programmer oversees conflicts between enclosing loops.
An alternative solution leaves the variables as strictly local: some C compilers support an extension
which fixes the location of a symbol in memory. You can use this feature to manage how variables
are placed in data memory space. Here is suitable notation for the Byte Craft compiler.
void up_and_down(void)
{
int up;
int down @ up; /* overlay */
porta = up;
/*...*/
for(down = 127; down > 0; down--)
porta = down;
}
Because the declaration is so specific, the compiler will obey it as is. This is a useful technique for
reusing allocated variable space without resorting to macros or other techniques. If memory opens
up, only the unobtrusive @ location extension needs to be removed.
9.3—
Debugging Embedded C
After learning how to interpret the results of the compiler's code generation, you can begin
debugging.
9.3.1—
Register Type Modifier
Those compilers that implement the register keyword may not actually grant exclusive access to
a register. 8-bit MCUs do not have many registers to spare. Instead, the compiler may allocate from
the fastest available memory.
Other keywords, such as Byte Craft's registera and equivalents will associate an identifier with
the appropriate register, but the resulting variable should be considered volatile. You have
immediate access to all the assembly code used in your system; with it, you can determine by
inspection whether the compiled code is meddling with register contents.
9.3.2—
Local Memory
If your compiler supports variables with local scope, you should determine the manner in which the
compiler allocates memory for variables in function calls.
Within a Stack Frame This requires explicit stack-relative addressing, which is very much a
luxury. It isn't always a preferred code option, and the compiler may not use it even if available.
Page 105
From the Global Heap Variables are simply allocated from RAM as needed. Globals and locals
intermingle.
"Dedicated" Local Memory This is used and reused from within multiple function calls.
9.3.3—
Pointers
Because Harvard architecture MCUs have two address spaces that are chosen by context, pointers
must target either program (ROM) space or data (RAM) space. The resulting code sequences can be
confusing.
In some architectures, far pointer variables can only be accomplished by self-modifying code. For
more information, see Section 9.6, Debugging by Inspection.
9.4—
Mixed C and Assembly
Embedded systems code lives in a much more spartan environment than traditional application
software. Resorting directly to assembly code is undesirable, unless you have to observe fixed
timing, or you want to use pre-existing assembly code in your current project.
9.4.1—
Calling Conventions
•Does your compiler set up page bits, or perform bank switching, prior to calling a subroutine?
•Does the compiler or processor handle saving and restoring state during an interrupt?
•How are function arguments passed? How are results returned? It's almost guaranteed that an 8-bit
result will be left the accumulator.
9.4.2—
Access to C Variables from Assembly
Does your assembly code properly address C identifiers? While the compiler may allow you to use a
C identifier as an argument in an assembly mnemonic, it may not check the size of the value against
the prescribed size of
Page 106
the instruction. As a result, the program may load one byte of a multiple byte value, without regard
for its significance.
9.5—
Exercising Hardware
If you have access to a prototype of the target hardware, a small program to test the hardware will
confirm your beliefs about its configuration and performance.
If your main project does not behave as predicted in an emulator or development system, the same
technique will determine whether a problem lies in hardware or software.
9.6—
Debugging by Inspection
The compiler can help you inspect code by generating different reports. The Byte Craft compiler
assembles all reports in the listing file that centres around the generated code and the source code
from which it came. These reports can assist in the chores of hand optimization, as described in
Section 9.2, Hand Optimization.
The compiler should generate a map of all symbols that it recognizes. The symbol table generated
by the Byte Craft compiler follows the format shown in Listing 9.4.
SYMBOL TABLE
The symbols listed are declared variables and functions, and preprocessor symbols. Identifiers
declared by other means, such as #pragma statements, also appear. This is an inventory of all
identifiers understood by the compiler.
Page 107
Desktop programmers don't usually deal with a pointer's actual value. Typically, they assign the
address of an object to a pointer variable, and manipulate the pointer (increment or decrement). The
actual number is best left unknown, because it will change.
Since code and variables will not be relocated on an 8-bit embedded system, and since RAM is
precious, it is more useful to examine RAM allocation in the embedded environment.
This report presents all the symbols that have memory allocated for their values, and the location of
each. This is the location returned by the & (address-of) operator. Local variables are listed with the
program range where the variable is in scope.
The compiler should give you an overall ROM usage count. This is the acid test for programmers
and compilers: can a different code passage, a different theoretical approach, or a different method
of optimization save a few extra bytes of ROM?
The program listing itself can be customized. As a convenience, the compiler can list execution
times for each opcode. You can count them to gauge how long an interrupt service routine runs, for
example. This information can in turn help you calibrate timing-dependent functions.
In the Byte Craft compilers, one helpful listing file option outlines the nesting level of each block of
C statements, as the compiler understands
Page 108
them. A similar option reveals the hierarchy of function calls in a separate report.
The most useful aspect of CALLMAP is to determine how much of the stack is used. The compiler
takes a static setting for the depth of the stack. Using CALLMAP and your knowledge of the system,
you can tailor stack size to save unused space.
The compiler can also present the values that it knows are held in the processor registers. If you are
working without the benefit of an emulator, this provides some of the information an emulator
would track.
9.7—
Dummy Loads
One way to test the software of a microcontroller is to cause the controller to operate within a
dummy load environment. This is a hardware technique more than a software chore, but the gist of
it is to replicate with simple buttons, relays, and lights each external component of the target system.
Using your knowledge of how the target system should behave, you can recreate the signals
expected by the controller and watch for the controller to react.
9.8—
Working with Emulators and Simulators
9.8.1—
Simulators
A simulator is a host-based or desktop software application that evaluates a program designed for an
embedded target machine. The simulator recreates the running conditions of the target machine and
interprets the executable.
Using a simulator, you can step through your code while the program is running. The simulator will
report on register and status values, peripheral register contents, and RAM usage.
Since simulators are not hardware-based, they lack the particular character of a physical electrical
device. A simulator can be written according to the microprocessor documentation, and therefore
will omit any hardware quirks introduced in fabrication.
Page 109
9.8.2—
Emulators
An emulator is a hardware device that behaves electrically and logically like a target processor. It
may include a similar processor, but with extra programming to support development host control
and communication. The emulator has a link to the development system, to provide a window into
the device under test. Since microcontrollers usually contain the ROM and RAM the system needs,
this too is under external control.
Emulators work best when the program being inspected is unaltered from its intended production
version, though this is not always possible for reasons explained in the following text.
Good emulators set breakpoints based on an "external" table of addresses. When emulated execution
arrives at the location, the breakpoint stops execution and waits for user intervention.
The alternative is to rewrite the program: an emulator might save the value at the breakpoint
location and write in a software interrupt instruction. The software interrupt will in turn invoke
management code that returns control to the emulator host.
Once in a breakpoint, the emulator will report on the internal state of the target processor,
nondestructively.
While not directly software-related, an expensive emulator will give detailed information on the
electrical and timing signals presented to the target processor.
One particular challenge in debugging and testing via emulator is a frequently-invoked interrupt. An
interrupt that happens too often or is too short-lived will lap the emulator easily. Only high-end
emulators with extensive trace buffers can properly record the execution of these events.
Another challenge grows from the advances in semiconductor packaging. In-circuit emulators need
to attach to a target system in place of a microcontroller. MCU packaging has shrunk from DIP-
sized (often socketed) to tiny surface-mount parts. The required stable physical connection is
increasingly difficult to engineer.
The issue with external emulators is cost; the specialized hardware is low-volume, high-complexity,
and therefore expensive. Emulators deal with the external signals of the MCU: they may sacrifice
speed to adopt a simple
Page 110
manipulation technique, or may provide real-time signal emulation and monitoring at a tremendous
increase in complexity and cost.
1. Less complex than an emulator that replaces the microcontroller, a ROM emulator replaces an
external program memory device in your target system. It responds to instruction fetches by
returning the opcodes of your program, and can insert software interrupts at any point. Furthermore,
it can also provide the monitor code needed by the target microprocessor to service the breakpoints.
2. Many new MCU designs are incorporating on-chip emulation facilities into each production
device. The aim here is to build a complete prototype with a normal sample or production processor
permanently in place. Rather than use a specialized emulation device, developers can use built-in
emulation facilities to interrogate the processor.
The link to the controlling host is provided by a 2- to 4-pin serial interface. On the prototype, the
emulation signals are routed to a header strip, and a small cable and jack can provide the link to the
host, perhaps through a serial port. The final design will probably not feature the header, unless it is
needed to provide access to field engineers; the traces can be left in with little worry.
9.9—
The Packaging of Embedded Software
For testing and short runs, individual parts with programmable ROM may have the binary image
created by the compiler burnt into them.
For long runs, a fabrication facility can write the binary information into the masks used for silicon
production. Each part is created with ROM cells set according to the binary image.
Page 111
Chapter 10—
Sample Project
This chapter covers technical topics about the thermostat project not previously discussed.
Source code for the thermostat is available on the CD. If you wish to build the thermostat,
detailed information is available on the CD. This chapter comments on several technical topics in
detail, but the discussion will be helpful in other projects as well.
10.1—
Hardware Exercise Programs
These are the programs that were used to test the thermostat hardware. We wrote them to get to
know the challenges the board would impose. They are good examples to enter and modify, to
experiment with C and the JICS emulator.
Y
FL
AM
TE
Team-Fly®
Page 112
10.1.1—
''Hello World!"
Since we don't have any indicator LEDs on the thermostat board, we toggle one of the
heating/cooling unit relays. The LCD library was not yet configured.
#include <705j1a.h>
#include <port.h>
void pause(void)
{
for(counter = 0; counter < 255; counter++)
{
NOP();
}
}
void main(void)
{
PORTB.0 = 0;
DDR_MASKED(PORTB,_______C,00000000);
DDR_WAIT();
while(1)
{
pause();
PORTB.0 = 1;
Page 113
pause();
PORTB.0 = 0;
}
}
10.1.2—
Keypad Test
Next we configure the keypad. Depending upon your hardware setup, the keypad library may
require customization. In our example, it required some modification.
#include <705j1a.h>
#include <delay.h>
#include <port.h>
void main(void)
{
int8 store;
keypad_init();
while(1)
{
Page 114
switch(keypad_getch()) {
case '0' : PORTB.0 = 1; break;
case '6' : PORTB.0 = 0; break;
case '#' : PORTB.0 = ~PORTB.0;
}
}
}
#include <keypad.c>
#include <port.c>
#include <delay.c>
10.1.3—
LCD Test
Note the configuration needed by the LCD library. The symbols and possible values are documented
in the library reference materials and in the file lcd.h.
#include <705j1a.h>
#include <delay.h>
#include <port.h>
#define LCD_DL 0
#define LCD_UPPER4 1
#define LCD_DATA PORTA
#define LCD_RS PORTB.2
#define LCD_RW PORTB.3
#define LCD_E PORTB.4
#define LCD_CD DDRB
#define LCD_CDM ___CCC__
#include <lcd.h>
Page 115
void main(void)
{
lcd_init();
while(1)
{
puts("Hello World");
delay_100us(10);
lcd_send_control(LCDCLR);
delay_100us(10);
}
}
#include <lcd.c>
#include <delay.c>
10.2—
Talking to Ports
One of the most challenging aspects of working with libraries is ensuring that they work with each
other when sharing ports. Should a library not assume complete control of the ports it needs, and,
more importantly, leave them in a stable state, you run the risk of misdriving the external devices.
In the thermostat design, the data wires of the LCD display are multiplexed with four wires of the
keypad matrix.
These are the guidelines we devised for keeping accesses of both the keypad and LCD
organized.
•Ensure the LCD enable line is disabled after writing or reading data. This was accomplished by
quick code inspection.
•Determine the routines that require port direction setup. The lcd_read() and lcd_write()
functions required data direction setup, as they actually drive the LCD interface; other library
routines such as
Page 116
lcd_set_address() use these functions, and therefore don't need their own port direction
setup.
Even though keypad_getch() uses keypad_kbhit() , they both need data direction setup.
keypad_kbhit() is intended for the user's own polling loops; however, keypad_getch()
does not return until a key is pressed.
10.3—
A/D Converter Theory
This design features a simple A/D converter circuit, in place of a dedicated converter peripheral as
described in Chapter 3. Removing the requirement for an integrated A/D peripheral opens up the
number of part choices.
The main feature of this device is that it is inexpensive, an important consideration for a mass-
produced device. The tradeoff is that it is software-intensive.
Figure 10.1
A/D converter circuit
The A/D converter assumes that the input impedance of an embedded microprocessor port is
relatively high, and that the switch point remains constant with little hysteresis.
It also assumes that the junction between Ri and Rf is a current-summing junction,. Consider the microprocessor as a high gain op-
amp that attempts to keep voltage at the summing junction on the threshold of Pi low to high sense
voltage.
Page 117
Physically, Pf is PORTB bit 5 and Pi is the IRQ input, disabled as an interrupt source. Pi must be
reset when it latches, but is in other ways like an input bit. To get an idea of the A/D) converter
input range, run the following code on the thermostat.
#include <705j1a.h>
#pragma mor @0x7F1 = LEVEL;
#include <port.h>
#define Pf PORTB.5
#define Pi ISCR.IRQF
This mode is actually using the microcomputer as a high-gain operational amplifier. The scope will
show a pulse stream whose duty cycle will vary with input voltage from Ri. The ratio of zeros on the
scope trace to the total time is a direct function of input voltage. It is this ratio we ultimately want to
measure using software.
Page 118
equations determine the minimum and maximum input voltage that can be read by the A/D
converter.
The value of Vmin occurs when Pi is consistently just at the sense threshold, and the processor is
always feeding back a 1 to the Pf pin. At an input of Vmax, a 0 is always being fed back from Pf.
The A/D value is linear and scaled between Vmin and Vmax. It is determined from the ratio of 1s
read on Pi (N1) to the total tests in a sample. The accuracy of the system is a linear function of test
sample size (N). Vi can be calculated using the following relationship.
The value of C1 is not critical, it is used to control the slew rate and noise immunity of the system.
For a typical system measuring an input from 0–5 volts, start with 47K resistors and a .01–.1 micro-
farad capacitor.
Finally, ratiometric measuring systems like this one provide conversion accuracy that is a function
of conversion time, and results can be easily scaled to the application. This eliminates conversion
multiplies and divides created by changing the sample size.
Page 119
Appendix A —
Table of Contents
Introduction 123
DEF.H 127
STDIO 129
STDLIB 130
STDLIB 130
qsort 134
pow 135
STRING 136
size_t 136
strlen 138
CTYPE 139
CTYPE.H 139
DELAY 141
delay_ms 141
KEYPAD 142
LCD 143
I2C_EE 147
MWIRE_EE 149
mwire_bus_delay 150
Team-Fly®
Page 121
MATH 152
fabs 154
fmod 154
modf 155
FLOAT 156
FLOAT.H 156
UART 158
UART 158
PORT 160
Appendix A —
Embedded C Libraries
Introduction
Pressure to cut development costs leads naturally to the urge to standardize hardware and software
products. Standardized computers led to standardized development languages and (quasi-)
standardized operating systems. As well, developers created standard libraries of useful functions
with widespread appeal.
In contrast, the popular notion of 8-bit embedded systems is that each new design is a one-of-a-kind
programming task. The variety of applications doesn't lend itself to standard hardware. Only in latter
years have compilers equalled and surpassed hand-coded assembly efficiency. Finally, the intimate
level of programming forbids making any assumptions about third-party software.
Our experience is that programming 8-bit systems can take advantage of the development practices
that evolved for mainstream computer systems. Even though the architectures vary, embedded
hardware is standardized, functionally speaking. For instance: I/O facilities have port-pin features,
such as selectable tristate, but in a limited number of permutations. As well,
Page 124
controllers often use highly standardized buses like SPI or CAN: even though the interfaces differ,
the expected results remain similar.
This relative similarity in hardware leads to standardized development languages. We have found
that the vast majority of embedded applications can be implemented in C, and compiled for more
than one of the leading microcontroller architectures on the market. Just as in desktop computing
development, choosing a standard development language loosens your dependence on a specific
architecture and supplier. This in turn can provide downward pressure on costs.
What remains largely unexplored is the feasibility of standardized C libraries for the 8-bit
environment. Can they play the same role in embedded systems as they do in desktop computer
software development? The ideals they represent are attractive.
Reduced Time to Market This is a simple savings in keystrokes per product. Libraries represent
necessary steps already taken.
Reusable Code Libraries represent predigested knowledge, an investment in a well known, well
structured, and well documented body of code. The return arrives with the reduced time and effort
needed to customize or configure them. In C, configuration is a matter of answering a few questions
using #defines.
Product Reliability Each development project that reuses a library can reinspect it for quality
assurance. Since each user of the libraries should have access to the source code, local
customizations and fixes can be integrated into the libraries for posterity. Reinventing the wheel
each time disrupts a potentially valuable revision history or paper trail.
The downside, of course, is the challenge of reconciling a wide range of unforseen applications into
an authoritative standard.
Working with libraries themselves is not a problem. Software that performs multiplication, division,
or modulus is best supplied as an external set of library functions, which the compiler reads in as
necessary. However, there is little debate about the design of the intended functionality: being
operators, they have the most common calling interface of all.
The interface presents the largest stumbling block. Extended mathematics and peripheral
functionality are the targets that need a standard functional interface and library implementation.
Floating-point practices, 8-bit
Page 125
implementation tradeoffs, and logical division of functionality are all likely points of contention.
The challenge is to find a robust general interface that accomodates some embedded-specific needs.
Efficient Function Calls Eight-bit architectures with little stack space are not candidates for
frivolous function calling. The formal parameters of a library call will always include one too many
values for some users.
If you make the reasonable assumption that there will not be more than one compiler at work on a
project, the physical part of function invocation has no unknowns. The compiler can do anything to
overcome the limits on resources of the target device.
Physical Differences Underlying Logically Similar Functions Input and output bits are likely to
represent the actual voltage levels on I/O pins, but there is no consensus for data direction settings.
C can easily accommodate symbolic changes: see the port library for an excellent abstraction.
External Design Decisions This one is not so easily dismissed. If two peripherals are multiplexed
on one port, as is the case with the thermostat, they can cause mutual interactions that a standard
library might not contemplate. C can easily accommodate multiple levels of symbolic changes, but
the design challenge moves from tricky to inscrutable.
The latter point is one of the reasons why it's important to ship the library source code with the
compiler. Product reliability, discussed previously, is another. Fortunately, contemporary software
industry practice, from a business point of view, permits, and even encourages, the distribution of
source code. Byte Craft realized early on the importance of shipping library source with each
compiler.
The subsequent sections outline a robust standard library interface. At this point, the libraries are
useful and portable. We have obeyed the C (desktop) library interface as closely as possible, where
needed.
You can easily use the libraries in your programs with the following steps.
•Add the include subdirectory to your environment's INCLUDE environment variable (the full
path names will vary depending upon your instal-
Page 126
lation). Alternatively, specify the include subdirectory on the command line with the n=
command-line option.
•Add the lib subdirectory to your environment's LIBRARY environment variable (the full path
name will vary depending upon your installation). Alternatively, specify the lib subdirectory on
the command line with the t= command-line option.
•Use #include <> to add their header files at the top of your source code. For example:
#include <stdio.h>
/* your main function and other code */
This is referred to in the compiler manual as Absolute Code Mode. The compiler will search for a
matching library file for every header file included at the top of your source.
The Code Development System relies upon header files for definitions and constants. These often
vary between part numbers. They are usually named for the part to which they apply, with a .h
extension.
Math Library
The math library for the Code Development System is contained in a file whose name matches the
name of the product. It is usually supplied in source form, but with a .lib file extension. Thus, the
compiler can read it in and compile it when necessary.
The math library supplies functions to implement the *, /, and % operators on 8- and 16-bit values.
The relevant function names are as follows.
Operator Functions
* __MUL8x8(void)
__MUL16x16(void)
/ __DIV8BY8(void)
__LDIV(void)
% __RMOD(void)
Page 127
To adjust the math routines to your liking, back up the library file and make your changes to it
directly. For instance: for a Code Development System product named ABC, the math library file
itself would be ABC.LIB.
It is not necessary to #include this library, because the compiler will automatically include it if
necessary. It searches for the library
Accordingly, it is important to have the Byte Craft library subdirectory in your LIBRARY path.
Library Definitions
DEF.H
Note
The name of the definitions header will change between CDS products. Look for a file named
abc_def.h, where abc is the name of the CDS product.
Description
When writing libraries of common code, you may not know for which target part to compile.
Without including a device header file, you cannot write code using the standard identifiers that
make your routines easier to read and maintain.
The solution to this dilemma is to include the library definitions header in place of any specific
device header. The library definitions file defines all the standard identifiers present in each device
header.
When compiling your library to an object file, Byte Craft compilers will ignore the values defined in
the definitions file, preserving only the identifiers. During the linking process, the compiler will link
the identifiers to the actual values specified in the particular device header file.
Page 128
Example
This example assumes you will use Absolute Code Mode (i.e., not using BCLink). If you do link
libraries with BCLink, remember to properly declare library functions as extern. The presence of
the MAKEOBJECT definition can help you decide to do so conditionally.
When writing the library my_library. lib, include the def.h header file.
#pragma library
#pragma option +l /* keep library code in the listing */
#include <abc_def.h>
void my_func1(void)
{
PORTO.1 = 0; /* uses general definition in abc_def.h */
}
#pragma endlibrary
Compile the file to an object file, rename the object file with a . lib extension, and place it in a
directory in the LIBRARY path.
void my_func1(void);
Create your program source file and include both the device header and the library header file.
#include <specific_device.h>
#include <my_library.h>
void main(void)
{
/* . . . */
my_func1();
/* . . . */
}
STDIO
Name
Description
stdio is a good example of the way C can make embedded programming more palatable. Though
an operating system with streams is not generally possible on an 8-bit microprocessor, programmers
can call some of the familiar functions to perform input and output operations to the predictable
devices.
stdio can also provide embedded interpretations of more complex functionality. One possibility
that has been briefly investigated is a scanf() function that reads characters from the user-
supplied getch(), and evaluates keycodes against template characters in a buffer ('0' for digits, 'a'
for letters, and so on). A trial implementation consumed about 200 bytes of ROM.
Name
Synopsis
#define BACKSPACE . . .
#include <stdio.h>
void puts(char far * str);
void gets(char near * str, int8 size);
Description
gets() retrieves a line from a device understood to be the standard input, and places it in the
buffer str, which has size size . It retrieves characters up to a newline or carriage return, or to
size - 1. It zeros the last position of the buffer.
Defining the symbol BACKSPACE to a character allows gets() to backtrack when it receives
BACKSPACE from getch(). gets() actually uses BACKSPACE to perform the backtrack, so the
getch() device must provide BACKSPACE, and the putch() device must understand
BACKSPACE to be a character that moves the input point or cursor back one space.
These routines rely upon the library functions getch() and putch(), which must be declared
elsewhere. Possible definitions for getch() and putch() are
STDLIB
STDLIB
Name
Description
Name
Synopsis
#include <stdlib.h>
Description
The current random number is stored in a static-duration data object, and is updated on each call to
rand().
Requirements
Y
FL
Requires a part header file or definitions file and the string library.
Name
TE
Synopsis
#include <stdlib.h>
int8 abs(int8 i)
int16 labs(int16 l)
Description
abs() accepts a signed word value and returns the absolute value as a positive signed word value.
labs() accepts a signed int16 value and returns the absolute value as a positive signed int16
value.
Team-Fly®
Page 132
Name
Synopsis
#include <stdlib.h>
void ui16toa(unsigned int16 value,char near * str,
unsigned int8 radix);
void ui8toa(unsigned int8 value,char near * str,unsigned int8 radix);
void i16toa(int16 value,char near * str,unsigned int8 radix);
void i8toa(int8 value,char near * str,unsigned int8 radix);
Description
radix may be one of the following values. The string buffer must be long enough to contain all
characters created by the conversion. Therefore, the buffer must be sized accordingly.
ui8toa() is similar to the ui16toa(), except that it translates unsigned word values (8 bits).
Therefore, the space requirements for the output buffer are as follows.
i16toa() converts a signed int16 integer to a null-terminated ASCII string. It accepts a pointer
to a string buffer, a value to be converted to a string representation, and the radix in which to
represent the number.
radix may be one of the following values. The string buffer must be long enough to contain all
characters created by the conversion. Furthermore, a negative value has a minus sign (–) prepended
to it. Therefore, the buffer must be sized accordingly.
i8toa() is similar to the i16toa(), except that it translates signed word values (8 bits).
Therefore, the space requirements for the output buffer are as follows.
Name
ahtoi16(), ahtoi8(), atoi16(), and atoi8() convert an ASCII string value representing
a decimal or hexadecimal number into an integer.
Page 134
Synopsis
#include <stdlib.h>
unsigned int16 ahtoi16(char near * str);
unsigned int8 ahtoi8(char near * str);
int16 atoi16(char near *str);
int8 atoi8(char near * str);
Description
atoi16() converts a null-terminated ASCII string representing a signed number into a signed
int16 value.
-0b1000000000000000 to
0b1111111111111111 Binary
atoi8() converts a null-terminated ASCII string representing a signed number into a signed word
value.
Name
Synopsis
#include <stdlib.h>
void qsort(void near * base,size_t nelem, size_t size);
Description
qsort() sorts the elements of an array. The elements are left in place.
The function accepts a pointer to the array, a number of elements in the array (nelem) and a size of
each element (size ). nelem and size are of type size_t, which is defined in string.c.
qsort() compares the array elements using an external function that must have been defined as
pow
Name
Synopsis
#include <stdlib.h>
unsigned int16 pow(unsigned int8 base, unsigned int8 exponent);
Description
STRING
Name
Description
Routines in this library perform operations on both null-terminated and known-length string buffers.
size_t
Name
Synopsis
#include <string.h>
typedef unsigned int8 size_t;
Description
Byte Craft libraries accept ''size of" parameters as type size_t. A size_t parameter usually
represents the size of another parameter or object.
Name
Synopsis
#include <string.h>
void memcpy(char near * dest,const char far * src,size_t n);
void * memchr(const void * s,int8 c,size_t n);
int8 memcmp(unsigned char far * str1,unsigned char far * str2,
size_t n);
Description
memchr() searches an array for a character. It begins at address s, and searches for the first
element of the array of size n that equals (unsigned char)c. It returns the address of the
matching element, or a null pointer if no match was found.
memcmp() compares two arrays of unsigned char, str1 , and str2, to find differences
between them. If all elements are equal, memcmp() returns 0.
Where a difference occurs, if the element of str1 is greater than that of str2 , memcmp() returns
a positive value. If the element of str1 is less than that of str2, memcmp() returns a negative
value.
Name
strcat(), strchr(), and strcmp() copy, search, and compare null-terminated strings.
Synopsis
#include <string.h>
void strcat(char near * dest,char far * src);
void * strchr(const void * str,int8 c);
int8 strcmp(unsigned char far * str1,unsigned char far* str2);
void strcpy(char near * dest,char far * src);
Page 138
Description
strcat() copies elements of the null-terminated string src, including its null termination
character, to the array dest .
strchr() searches the null-terminated string str for the first occurrence of (char)c. strchr
() examines the terminating null of str as part of the string. strchr() returns a pointer to the
matching character of str, or a null pointer if no match was found.
strcmp() compares two null-terminated strings, str1 and str2, to find differences between
them. If all elements are equal, strcmp() returns 0.
Where a difference occurs, if the element of str1 is greater than that of str2, strcmp() returns
a positive value. If the element of str1 is less than that of str2, strcmp() returns a negative
value.
If one string is shorter than the other, strcmp() does not finish the longer string.
strcpy() copies the null-terminated string src, including terminating null, to the array of char
pointed to by dest .
strlen
Name
Synopsis
#include <string.h>
unsigned int8 strlen(char far * str);
Description
strlen() returns the number of characters in the null-terminated string str. The count does not
include the terminating null character.
Name
Synopsis
#include <string.h>
void strset(char near * str,char ch);
void strupr(char near * str);
void strlwr(char near * str);
Description
strset() stores (unsigned char)ch in each of the elements of the array pointed to by str.
strupr() converts all lowercase characters in the null-terminated string str to uppercase. It
converts the string in place.
strlwr() converts all uppercase characters in the null-terminated string str to lowercase. It
converts the string in place.
CTYPE
CTYPE.H
Name
Description
Name
Synopsis
#include <ctype.h>
int8 isalnum(int8 ch);
int8 isalpha(int8 ch);
int8 isascii(int8 ch);
int8 iscntrl(int8 ch);
int8 isdigit(int8 ch);
int8 islower(int8 ch);
int8 isupper(int8 ch);
int8 isxdigit(int8 ch);
#define toascii(CH) CH&0x7f
int8 tolower(int8 ch);
int8 toupper(int8 ch);
Description
isalnum() evaluates the character ch and returns a nonzero value if it is a lowercase character
(a–z), uppercase character (A–Z), or decimal digit (0–9). If not, it returns zero.
isalpha() evaluates the character ch and returns a nonzero value if it is a lowercase character
(a–z) or uppercase character (A –Z). If not, it returns zero.
Y
isascii() evaluates the character ch and returns a nonzero value if it is an ASCII character
(high bit is 0).
FL
iscntrl() evaluates the character ch and returns a nonzero value if it is an ASCII control
AM
character. (ASCII control characters include characters 0–31 and 127.) If not, it returns zero.
isdigit() evaluates the character ch and returns a nonzero value if it is a numeric digit (0–9). If
not, it returns a zero.
TE
islower() evaluates the character ch and returns a nonzero value if it is a lowercase character
(a–z). If not, it returns a zero.
isupper() evaluates the character ch and returns a nonzero value if it is an uppercase character
(A–Z). If not, it returns a zero.
isxdigit() evaluates the character ch and returns a nonzero value if it is a hexadecimal digit (0–
9, a–f, or A–F). If not, it returns a zero.
Team-Fly®
Page 141
DELAY
Name
Description
Requirements
delay_ms
Name
Synopsis
#include <delay.h>
void delay_ms(unsigned int8 ms);
Description
KEYPAD
Name
Description
The routines in this library operate a matrix keypad connected to a single, 8-bit I/O port.
Requirements
Name
keypad_getch() and keypad_kbhit() scan for and get a character from a matrix keypad.
Synopsis
#define KEYPAD_PORT
#define keypad_debounce_delay() delay_ms(0x20)
#include <keypad.h>
Description
The user must define KEYPAD_PORT to the register used to read from and write to the port.
A default definition may be available. Consult the source for the keypad
library.
Page 143
The user must define a function KEYPAD_READ to set up KEYPAD_PORT for reading. The
implementation will vary depending upon the circuitry of the keypad.
A default definition may be available, depending upon your Code Development System product.
Consult the source for the keypad library.
keypad_getch() waits for a keypad contact, and returns the appropriate character from the array
keypad_table[].
keypad_kbhit() looks for a keypad contact and returns 1 when a contact is made.
LCD
Name
Requirements
Description
The LCD library provides routines to drive a Hitachi HD44780 LCD controller.
Page 144
A typical LCD module configuration uses 3 wires for read/write, register select (command or data),
and enable, and either four or eight wires for data transmission.
The module needs to be initialized by a sequence of writes that sets parameters, including the width
of the data bus. This is accomplished by lcd_init(). After initialization, the LCD panel may
occasionally be busy. lcd_busy_check() determines whether the module can accept new data.
lcd_putch() and lcd_getch() are intended to be used as putch() and, less likely, getch
() for the stdio library.
Configuration
LCD_DATA
Name
Synopsis
Description
Name
Synopsis
#include <lcd.h>
void lcd_init(void);
void lcd_send_control (char control);
void lcd_busy_check(void);
Description
lcd_init() performs several LCD initialization tasks, including turning on the LCD display and
cursor, clearing the display, and setting the display to increment mode.
lcd_busy_check() waits until the busy bit of the LCD controller is clear. You can then safely
write to the controller.
Page 146
Name
lcd_init(), lcd_putch(), and lcd_getch() write to and read from the LCD module, and
move the cursor.
Synopsis
#include <lcd.h>
void lcd_putch(char ch);
char lcd_getch(void);
void lcd_gotoXY(int8 x, int8 y);
Description
Thus, to move the insert point to the final cell of the bottom row of a 2-line, 40-space panel, use
lcd_gotoXY(1,39);
Page 147
I2C_EE
Name
I2C_EE provides useful routines for the I2C 24LC01B/02B serial EEPROM.
Description
Ι2CTM is a standard of Phillips Electronics N.V. It is a serial peripheral interface that operates across
two wires. The two lines consist of the serial data line and the serial clock line, which are both
bidirectional. It is synchronous.
It is a multimaster, multislave network interface with collision detection. Up to 128 devices can exist
on the network. Each device has an address made up of several fixed bits (assigned by the I 2C
committee) and several programmable bits usually determined by pin connections. In this way,
several identical devices can coexist within one system. Either 7- or 10-bit addressing is available.
There are also several reserved addresses for broadcasting to all devices and other expansion
needs.
I2C has two speeds: In standard mode, 100 kbit/second, and in fast mode, 400 kbit/second. Effective
data rates are dependent upon configuration and addressing mode used.
The standard does not specify a programming interface for controllers that implement it. This
section deals exclusively with a serial EEPROM connected by I2C.
Requirements
Configuration
To configure the I 2C port, the following settings must be adjusted. If not changed, the I 2C control
(clock) line is bit 0 of port 1 and the data line is bit 5 of port 2.
Name
Synopsis
#include <i2c_ee.h>
void I2C_write(unsigned int8 address, unsigned int8 data);
unsigned int8 I2C_read(unsigned int8 address);
Description
I2C_write() writes the word data at the memory location address on the serial EEPROM.
MWIRE_EE
Name
Description
•A control register CNTRL that configures the interface (including the internally-generated shift
rate)
The MICROWIRE Shift Clock (SK) is a factor of internal clock speed, dividing the system clock by
2, 4, or 8. Each byte transmitted or received by MICROWIRE requires 8 SK cycles.
Software can cause a transmit by setting the BUSY flag of the PSW (processor status word). The
BUSY flag will clear when the transmit is complete. Some parts provide a vectored maskable
interrupt when BUSY is reset.
The following routines deal directly with an EEPROM connected via MICROWIRE.
Requirements
Requires a device header file or a definitions file. Requires an external function as shown in the
following text.
Page 150
Configuration
You must define the following symbols before using the mwire_ee library. If not defined, default
values are used.
mwire_bus_delay
TE
Name
Synopsis
#include <mwire_ee.h>
void mwire_bus_delay() {
/* Your preferred delay code */
}
Description
To properly time the MICROWIRE bus, you must write a delay function to wait between half clock
cycles. You can accomplish this by
Team-Fly®
Page 151
Name
Synopsis
Description
mwire_write() writes the value of data to the location address on the EEPROM.
mwire_read() reads and returns the value at location address from the serial EEPROM.
mwire_write_all() writes the same value to all locations of the serial EEPROM.
Page 152
MATH
Name
Description
Requirements
Requires float.h
Name
Synopsis
#include <math.h>
float acos(float x);
float asin(float x);
float atan(float x);
float atan2(float y, float x);
Description
asin() returns the angle in radians (from –pi/2 to pi/2) whose sine is x.
atan() returns the angle in radians (from –pi/2 to pi/2) whose tangent is x.
atan2() returns the angle in radians (from –pi to pi) whose tangent is y/x.
Page 153
Name
ceil() and floor() return the next higher or lower integer value.
Synopsis
#include <math.h>
float ceil(float x);
float floor(float x);
Description
Name
cos(), cosh(), sin(), sinh(), tan(), and tanh() are trigonometric functions.
Synopsis
#include <math.h>
float cos(float x);
float cosh(float x);
float sin(float x);
float sinh(float x);
float tan(float x);
float tanh(float x);
Description
fabs
Name
Synopsis
#include <math.h>
float fabs(float x);
Description
fmod
Name
Synopsis
#include <math.h>
float fmod(float x, float y);
float frexp(float x, int * pexp);
float ldexp(float x, int exp);
Description
frexp() calculates a mantissa and exponent for the float value x. frexp() returns the
mantissa and places the exponent in *pexp. The exponent is a power of 2.
Page 155
ldexp() calculates a floating point value for the mantissa x and the exponent (of base-2) exp.
Name
Synopsis
#include <math.h>
float exp(float x);
float log(float x);
float log10(float x);
Description
modf
Name
Synopsis
#include <math.h>
float modf(float x, float * pint);
Description
modf() calculates the integer and fraction portions of the value x, returns the fraction portion, and
stores the integer portion in *pint. Both the integer and fraction portions have the same sign as x.
Page 156
Name
Synopsis
#include <math.h>
float pow(float x, float y);
float sqrt(float x);
Description
FLOAT
FLOAT.H
Name
Synopsis
#include <float.h>
#define FLT_DIG
#define FLT_EPSILON
#define FLT_MANT_DIG
#define FLT_MAX
#define FLT_MAX_10_EXP
#define FLT_MAX_EXP
#define FLT_MIN
Page 157
#define FLT_MIN_10_EXP
#define FLT_MIN_EXP
#define FLT_RADIX
#define FLT_ROUNDS
Description
If you employ floating point variables or operations, the file float.h provides some required
definitions.
Definitions
FLT_EPSILON determines the smallest possible nonzero value for a float variable.
FLT_MANT_DIG is the number of mantissa digits for float variables. The value is of base
FLT_RADIX.
FLT_ROUNDS represents the rounding method used by floating point calculations. The following
value for FLT_ROUNDS sets the accompanying rounding method:
UART
UART
Name
Requirements
Requires a part header file or definitions file, and the port and delay libraries.
Definitions
UART_TD_PORT
Users must define this as the port intended for UART transmission. By default, this is defined as
PORT1.
UART_TD_PIN
Users must define this as the pin in UART_TD_PORT intended to drive the TD line. By default, this
is defined as 1.
UART_RD_PORT
Users must define this as the port intended for UART reception. By default, this is defined as
PORT2.
UART_RD_PIN
Users must define this as the pin in UART_RD_PORT intended to read the RD line. By default, this
is defined as 4.
Variables
uart_mode
Configures the uart library at run time as described in the following text.
Page 159
Configuration
Users must set the uart_mode variable with an ORed combination of constants.
Example:
Name
Synopsis
char uart_getch(void);
void uart_putch(char);
char uart_kbhit(void);
Description
PORT
Name
Requirements
Description
This header file includes some useful functions for manipulating ports. Many Byte Craft libraries
depend upon these definitions.
All single-chip MCUs have I/O ports of some nature. This library tries to smooth out the differences
between their peculiarities.
port.h causes portdefs.h to be read in. portdefs includes definitions for each possible
setting of a data direction register. In these definitions, 'I' stands for "input" and '0' stands for
"output." This is to resolve the question of which state (zero or one) stands for input or output. For
Y
example:
FL
portdefs also includes definitions for bit masks to be used in DDR_MASKED() . In these
definitions, '_' (underscore) means "no change", and 'C' means change.
Team-Fly®
Page 161
Name
Synopsis
#include <port.h>
DDR(port, direction)
DDR_MASKED(port, mask, direction)
DDR_WAIT()
Description
These functions manipulate a port's data direction. They use direction and mask definitions read in
from portdefs.h.
DDR() accepts a port and direction definition, and configures the port's data direction register to
operate accordingly.
DDR_MASKED() performs the same action, but only on the pins selected in the mask definition.
DDR_MASKED() helps solve the conflict between several library routines addressing different bits
on the same port. To change one or two bits, the compiler may use bit-change instructions if
available, leaving the rest untouched. Otherwise, the compiler will preserve the state of masked-out
DDR bits when it reads and modifies the DDR value.
DDR_WAIT() inserts a short delay to allow the data direction change to propagate.
Example
To set the low and high nibbles to output and input, respectively, use:
Appendix B—
ASCII Chart
It's always difficult to find an ASCII chart when you want one. Here is a chart of hex values and
their ASCII meanings.
1D GS 3D = 5D ] 7D }
1E RS 3E > 5E ^ 7E ~
1F US 3F ? 5F _ 7F DEL
Page 165
Appendix C —
Glossary
accumulator
Also "A", "AC", or other names. The register that holds the results of ALU operations.
A/D
Analog to digital.
addressing mode
The math used to determine a memory location in the CPU, and the notation used to express it.
ALU
Arithmetic Logic Unit. Performs basic mathematical manipulations, such as add, subtract,
complement, negate, AND, and OR.
AND
Logical operation in which the result is 1 if ANDed terms both have the value 1.
ANSI C
American National Standards Institute standards for C.
assembly language
A mnemonic form of a specific machine language.
Page 166
bank
A logical unit of memory as determined by addressing modes and their restrictions.
bit field
A group of bits considered as a unit. A bit field may cross byte boundaries if supported by the
compiler.
block
Any section of C code enclosed by braces, {}. A block is syntactically equivalent to a single
instruction, but adds in a new variable scope.
breakpoint
A set location to stop executing program code. Breakpoints are used in debugging programs.
CAN
Controller Area Network, developed by Bosch and Intel. It is an intermodule bus that links
controlled devices.
cast
Also coerce. Convert a variable from one type to another.
checksum
A value that is the result of adding specific binary values. A checksum is often used to verify the
integrity of a sequence of binary numbers.
cross assembler
An assembler that runs on one type of computer and assembles the source code for a different target
computer. For example, an assembler that runs on an Intel x86 and generates object code for
Motorola's 68HC05.
cross compiler
A compiler that runs on one type of computer and compiles source code for a different target
computer. For example, a compiler that runs on an Intel x86 and generates object code for
Motorola's 68HC05.
debugger
A program that helps with system debugging where program errors are found and repaired.
Debuggers support such features as breakpoints, dumping, and memory modify.
Page 167
declaration
A specification of the type, name, and possibly the value of a variable.
dereference
Also * or indirection. Access the value pointed to by a pointer.
EEPROM
Electrically erasable programmable read only memory.
embedded
Fixed within a surrounding system or unit. Also, engineered or intended to perform one specific
function in a specific environment.
endianness
The distinction of multibyte data storage convention. Little-endian stores the least-significant byte
first in memory. Big-endian stores the most-significant byte first in memory.
global variable
A variable that can be read or modified by any part of a program.
hysteresis
The delay between the switching action of a control and the effect. Can be enforced to prevent rapid
short-term reversals in the control's state.
index register
Also known as "X" or other names. The register used to hold a value that becomes a factor in an
indexed addressing mode. Frequently used for arithmetic operations, though without as many
capabilities as an accumulator.
interrupt
A signal sent to the CPU to request service. Essentially a subroutine outside the normal flow of
execution, but with many extra considerations.
J1850
An intermodule bus endorsed by the SAE (Society of Automotive Engineers).
local variable
A variable that can only be used by a specific module or modules in a program.
logical operator
Operators that perform logical operations on their operands. For example, !, &&, and ||.
Page 168
machine language
Binary code instructions that can be understood by a specific CPU.
mask
A group of bits designed to set or clear specific positions in another group of bits when used with a
logical operator.
maskable interrupt
Interrupts that software can activate and deactivate.
memory-mapped
A virtual address or device associated with an actual address in
memory.
NOP
No operation. An instruction used to create a delay.
NOT
Logical negation. A 0 becomes a 1, and a 1 becomes a 0.
object code
Machine language instructions represented by binary numbers not in executable form. Object files
are linked together to produce executable files.
operator
A symbol that represents an operation to be performed on operands. For example, +, *,
and /.
OR
A Boolean operation that yields 1 if any of its operands is a 1.
paging
A page is a logical block of memory. A paged memory system uses a page address and a
displacement address to refer to a specific memory location.
port
A physical I/O connection.
program counter
Also PC. A register that holds the address of the next instruction to be executed. The program
counter is incremented after each byte of each instruction is fetched.
programmer's model
The description of registers that make up the microprocessor's visible interface. Includes the
registers such as the accumulator and index register, program counter, and stack pointer.
PROM
Programmable read-only memory. ROM that can be programmed.
Y
FL
AM
TE
Team-Fly®
Page 169
real time
A system that reacts at a speed commensurate with the time an actual event occurs.
A byte or word of memory that exists within the microprocessor proper. Registers directly interface
to the ALU and other microprocessor functionality, as opposed to external RAM.
reset
To return the microcontroller to a known state. This operation may or may not alter processor
registers, and memory and peripheral states.
ROM
Read only memory.
ROMable
Code that will execute when placed in ROM.
RS-232
A standard serial communication port.
SCI
Also UART (Universal Asynchronous Receiver Transmitter). SCI is an asynchronous serial interface.
The timing of this signal is compatible with the RS -232 serial standard, but the electrical
specification is board-level only.
SPI
Serial Peripheral Interface bus. A board-level serial peripheral bus.
scope
A variable's scope is the areas of a program in which it can be
accessed.
shift
Also rotate, with subtle differences between them. Move the contents of a register bitwise to the left
or right.
side-effect
An unintentional change to a variable, or the work of instructions within a function not directly
related to the calculation of its return value.
simulator
A program that recreates the same input and output behaviour as a hardware device.
stack
A section of RAM used to store temporary data. A stack is a last-in-first-out (LIFO) structure.
stack pointer
A register that contains the address of the top of the stack.
Page 170
static
A variable that is stored in a reserved area of RAM instead of in the stack. The area reserved cannot
be used by other variables.
timer
A peripheral that counts independent of program execution.
UART
Universal asynchronous receiver transmitter. A serial-to-parallel and parallel-to-serial converter.
volatile
The quality of a value that changes unexpectedly. The compiler cannot trust that the value of a
volatile variable remains constant over time, and therefore cannot perform certain optimizations.
Declared explicitly by the programmer, or determined by the compiler.
watchdog (timer)
Another name for computer operating properly circuitry.
Page 171
Index
abs() 131
acknowledgement
asynchronous 26
synchronous 26
acos() 152
ahtoi16() 134
ahtoi8() 134
arbitration 27
architecture
Harvard 24
von Neumann 23
asin() 152
asynchronous acknowledgement 26
atan() 152
atan2() 152
atoi16() 134
atoi8() 134
block 79
bus 18
ceil() 153
cos() 153
cosh() 153
data type
character 60
double 63
float 63
Page 172
integer 61
long 61
long double 63
parameter 60
short 61
emulator 108
exp() 155
fabs() 154
floor() 153
flowchart 9
FLT_DIG 157
FLT_EPSILON 157
FLT_MANT_DIG 157
FLT_MAX 157
FLT_MAX_10_EXP 157
FLT_MAX_EXP 157
FLT_MIN 157
FLT_MIN_10_EXP 157
FLT_MIN_EXP 157
FLT_RADIX 157
fmod() 154
frexp() 154
Harvard architecture 24
header file 63
I
i16toa() 133
I2C 147
i8toa() 133
identifier
constant 71
assigning to a float 63
interrupts 18, 26
keypad_debounce_delay() 143
labs() 131
LCD_DATA 144
LCD_E 144
LCD_RS 144
LCD_RW 144
ldexp() 155
LED 54
log() 155
log10() 155
maskable interrupts 26
microcontroller 19
MICROWIRE 149
modf() 155
mwire_bus_delay() 150
mwire_disable() 151
mwire_enable() 151
mwire_erase() 151
mwire_read() 151
mwire_read_all() 151
mwire_write() 151
Page 173
nonmaskable interrupts 26
nonvectored arbitration 27
parameters 60
processor state 29
pseudocode 9
qsort() 135
QSORT_COMPARE 135
RAM 58
rand() 131
randmize() 131
real numbers 63
scopes 21
simulator 108
sin() 153
sinh() 154
size_t 136
sqrt() 156
srand() 131
stack 20
state diagram 9
strcat() 138
strchr() 138
symbol table 59
synchronous acknowledgement 26
tan() 154
tanh() 154
timer 24
typographical conventions 4
bold 4
ui16toa() 132
ui8toa() 132
variables 9
vectored arbitration 27
watchdog timer 25
while 79
Page 180
The CD-ROM the accompanies C Programming for Embedded Systems includes a working
C6805 Code Development System tailored for the Motorola MC68705J1A microcontroller. The CD
also includes:
•Supplementary documentation
System Rquirements
2. Enter D:\setup.exe, replacing "D:" for the drive letter of your CD-ROM drive.
AM
Team-Fly® | https://www.scribd.com/document/18088784/CMP-Books-C-Programming-for-Embedded-Systems-Fly | CC-MAIN-2019-30 | refinedweb | 30,296 | 54.83 |
To print Armstrong numbers between the given range in java, we first need to understand what is an Armstrong number. An Armstrong number is the number that is equal to the sum of the cubes of the single individual digits of the number. For example, we want to check if 153 is an Armstrong number or not. We will take the sum of cubes of 1, 5 and 3 which is 1+125+27. The sum is equal to 153. As a result, we conclude that 153 is an Armstrong number. The program in java to print an Armstrong number is below.
To check if a number is Armstrong or not, we follow the following algorithm:
- We take the integer value and assign them a value.
- Then we split the integer value.
- We find the cube value of each integer value and split them.
- We save the single outputs and add them together.
- The integer value is an Armstrong number if the sum is equal to the initial input value.
- The integer value is not an Armstrong number if the sum is not equal to the initial input value.
Armstrong number between the given ranges
import java.util.Scanner; public class DeveloperHelps { public static void main(String args[]) { int n, n1, n2, i, rem, temp, count=0; Scanner scan = new Scanner(System.in); System.out.print("Enter the starting number of the range : "); n1 = scan.nextInt(); System.out.print("Enter the ending number of the range : "); n2 = scan.nextInt(); for(i=n1+1; i<n2; i++) { temp = i; n = 0; while(temp != 0) { rem = temp%10; n = n + rem*rem*rem; temp = temp/10; } if(i == n) { if(count == 0) { System.out.print("Armstrong Numbers between the given range are: \n"); } System.out.print(i + " "); count++; } } if(count == 0){ } System.out.print("Armstrong Number is not Found between the given range"); } }
The output of the following program will be:
Enter the starting number of the range: 90 Enter the starting number of the range: 501 Armstrong Numbers between the given range are: 153 370 371 407
The user enters the range in which he wants to find the Armstrong numbers in the above program. As the user enters the starting and ending range, a ‘for’ loop is used which finds all the Armstrong numbers. We use our logic for checking the numbers. If we find a number that lies in the Armstrong number category, the value is printed in the output. Otherwise, a message is displayed that Armstrong Number is not found between the given range.
Thanks for the reading post. I hope you like and understand the post. If you have any doubts regarding this post please comment below. | https://www.developerhelps.com/java-program-to-print-armstrong-numbers-between-the-given-range/ | CC-MAIN-2021-31 | refinedweb | 450 | 65.52 |
Hunsberger, Peter wrote:
> Guido Casper <gcasper@s-und-n.de> writes:
>
>
>).
>
>
> I think there is something else going on here also: as technologies
> mature there is a push to make them more accessible. Making them more
> accessible means adding in capabilities that don't require formal CS
> training. JavaScript and scripting languages in general are a good
> example of this. They enable a whole new level of accessibility for a
> whole new audience that wants to "just do it" and have never heard of
> best practices.
>
> This is good, the demand for such a level of capability means a product
> has reached a level of appeal where even non CS users are wanting to use
> it. As such, we shouldn't be surprised if some of the uses for these
> capabilities don't employ what a more traditional Cocoon developer would
> consider best practices.
>
> So, my high level advice would be not to try and control such
> experimentation too much. Watch and see what comes of it and then start
> to develop a new level of best practices. Cforms is an example of this;
> the community in general is still working to figure out what is best
> practices for cforms: how to bind, how to add action handlers, etc.
> There's a general picture emerging, but it's not clear (as an outside
> observer) exactly what parts of cforms embody Cocoon flow best practices
> yet. I think this will become much clearer over time.
>
> So, I think, yes, you can have both strategy and best practices but it's
> just going to take time for the best practices to emerge and having a
> strategy on how to guide that will help (if we really understand what
> the strategy will do).
The pattern to apply might be to seperate the things changing from the
things staying the same. Recognizing what stays the same and what might
change requires exerience as well. But the Cocoon community should have
some experience in that space as what should stay the same IMO is the
desire to separate the concerns and to keep the pyramid of contracts.
>
>
>>----
>>
>>Welcome to my first RT :-)
>
>
> Gee, I have RT all the time, I just never write them down ;-)...
Well, OK ... I do have ... hmm ... point taken :-)
>
>
>> From the arrival of flow I liked it very much. But at the
>>same time I
>>felt it weakens the pyramid of contracts to a great extent
>>(as Gianugo
>>recently pointed out as well).
>>
>>The pyramid of contracts defined several roles, but what made it so
>>powerful (IMO) was the strong contract between a user and a
>>developer of
>>Cocoon. I feel like the distinction between these two not being that
>>clear anymore.
>>
>>It may be not immediately clear what this distinction is and
>>I thought a
>>lot about it (and my opinion on this may be debatable). So
>>here it goes:
>>
>>"A user is someone building applications without writing a
>>single line
>>of Java code."
>>
>>Some people might argue: Hm, if you try to build your application
>>without writing any Java code you end up in a mess. But the
>>point of the
>>above is, if that user needs a component written/extended in
>>Java he can
>>go to "his" developer and tell him: Go off and build this
>>component for
>>me and come back when you're done. When this developer comes
>>back with
>>the ready-built component the user goes on finishing his app.
>>This is a
>>strong contract. An important detail that easily slips through is the
>>fact that it is the user being responsible for the application's
>>architecture not the developer.
>>
>>So one might come up with the most simple definition of a
>>Cocoon user as
>>"someone building Cocoon apps without having eclipse installed" (Idea
>>and JBuilder counts as well - but Emacs doesn't :-).
>>
>>With flow this distinction is not that clear anymore.
>
>
> I think the line has always been blurred (does a user modify the
Well, yes. It's the _user_ building the application.
The line may not be always crystal clear. But the point is that it
allows you to separate concerns. And even if it's always myself wearing
a developer hat or wearing a user hat it surely makes complex
applications more manageable and gives me a development model quite
appealing to big project teams.
What I currently complain about is that the user role has been
degenerated to a stylesheet writer but it should be the one reponsible
for the application as a whole.
> it's just that flow makes it even more obvious that there is
> an overlap. The capabilities implemented for flow add capabilities for
> general scripting (in addition to flow control) that is going to be
> used; there's a pent up demand for easier development that Flowscript
> provides.
A nice scripting engine may provide a boost for developer productivity
(which is great). But general scripting is not and will never be what
makes Cocoon ubiquetous. What I am trying to find out is which concerns
are really affected by the way we use scripting currently and may use it
in the future.
>
>
>.
>>
>>Over time the intention of flow became "glueing your components
>>together". Developers tend to (ab)use flow for "its own benefits" and
>>use it the same way they use Java (JavaScript is not all that
>>different
>>from Java). I feel that the goal to build reusable (high level)
>>components went out of focus because of that (it may be
>>harder to build
>>reusable components for the flow layer then it was/is for the sitemap
>>and it may even be harder to hold on to the pyramid of
>>contracts while
>>moving from the publishing to the webapp space).
>>
>>----
>>
>>I'm not saying this necessarily is something bad. It just puts a
>>different perspective on the development process. Today with
>>advancement
>>of IDEs and automated build processes these roles and
>>processes may have
>>changed a bit and the user being "responsible" for all the flow layer
>>does not work anyway, does it? Your code repository is the collective
>>entry point into the system (being closely controlled via a set of
>>automated tests) and Cocoon users and developers are working more
>>closely "integrated" (if they are still to be distinguished
>>roles at all).
>>
>>Did the pyramid of contracts silently vanished? I don't think
>>so. Just
>>lift the user to an "educated user" (if he hasn't always
>>been). However
>>this doesn't mean to tell the user: go and figure how to use all the
>>public classes available from the flow layer. It rather means
>>use flow
>>like it's intended to be used and just use a well-defined
>>limited set of
>>available interfaces.
>
>
> Hmm, yes, maybe, I'm not sure... I think you're always going to have to
> expect a bit of a lag between new capabilities and best practices.
> Encoding a limited set of available interfaces means that we already
> know what the best practices are. For some areas that's probably true
> (parts of the guts of Cocoon), for other areas like DB access, I think
> we're still learning. Some areas are going to be very blurry for some
> time, flow control itself has a lot of different meanings to a lot of
> different people.
>
>
>>At first I thought, don't bother writing this email, everyone
>>thinks the
>>same. But I suspect there may be radically different opinions
>>about that.
>>
>>Yes, we habe FOM. The difference to the sitemap is that the sitemap
>>enforces the contract while flow doesn't.
>>
>>Why do "flow people" constantly fall back using Java classes? Do they
>>put to much into the flow layer? The expectations for the flow layer
>>seem to be so various. I fear that this fact does more harm
>>than good to
>>Cocoon. Hm, I don't even have a definition of "flow layer".
>
>
> Like I said, flow means a lot of things to a lot of people. Not sure
> you can have a single definition; I try to distinguish between
> application flow and screen flow.
Exactly, let's try to find out which concern are currently affected by
flow and if and how these concerns may be better separated. I'm not
saying we should immediately do that but start thinking about it.
> Limiting Cocoon flow to screen flow
> may bring some of the clarity you want, but telling people they can't do
> application flow would remove a lot of RAD capabilities from Cocoon that
> are also useful even for people who know how to do things the "right"
> way (eg; from what I understand Linotype was developed using flow as a
> RAD tool?)
>
>
>>Why is there
>>no library of flow components readily available? I don't know but I
>>suspect it's harder to build reusable flow components than it is to
>>build reusable sitemap components (the level of component
>>reusability of
>>the sitemap is unparalleled). At the same time it is too easy to just
>>get my stuff finished with flow. Which is exactly what makes flow
>>currently so powerful and what may count in many cases. However this
>>particular advantage may be just temporary.
>
>
> I think perhaps the main reason is that more time is needed for them to
> emerge?
Yes that might be one reason. Another one IMO is that it's much easier
to (conceptually) come up with a reusable sitemap component (being a
specialized thing) than it is to come up with a reusable flow component.
Guido
>
>
>>I guess I just want to hear what other people would think about that.
>>Even if this Email leads to nothing but people looking from another
>>perspective, I'm happy :-)
>>
> implicitly?
>>
>
>
>
--
Guido Casper
-------------------------------------------------
S&N AG, Competence Center Open Source
Tel.: +49-5251-1581-87
Klingenderstr. 5 mailto:gcasper@s-und-n.de
D-33100 Paderborn
------------------------------------------------- | http://mail-archives.apache.org/mod_mbox/cocoon-dev/200404.mbox/%3C40841BFF.6050707@s-und-n.de%3E | CC-MAIN-2015-40 | refinedweb | 1,640 | 69.41 |
On Dec 12, 2000, Robert Boehne <address@hidden> wrote: > Using the multi-language-branch as a starting point, I have a working > "libtool" script that incrementally links libraries to prevent running > into limits of the shell. Cool! > I have defined two new shell variables in libtool, > ${incr_archive_cmds} and ${old_incr_archive_cmds}, which are used > instead of ${archive_cmds}/${old_archive_cmds} when ${max_cmd_len} > is less than the length of the expanded > "${archive_cmds}/${old_archive_cmds}". I can see the point of old_incr_archive_cmds, given that old_archive_cmds can be pretty much anything, and you can't count on being able to incrementally add object files to it, but the good thing is that old_archive_cmds is only overridden on Cygwin and Mingw. However, incr_archive_cmds doesn't seem very useful to me. It would seem to me that it would be easier to arrange for libtool to know how to use reload_flag to link multiple object files into a single one, and iterate until the command line is short enough. > Since ${max_cmd_len} is not compiler-dependent, where should it be > defined? Good question. I wish I knew the answer :-) > The value can be determined with a short C program such as this: You can't depend on being able to run a C program. Think of cross-compilation. But I like the idea of using preprocessor symbols. How about preprocessing a program with the same #includes you use, but ending with: #if defined ARG_MAX LIBTOOL linelen ARG_MAX #else # if defined NCARGS LIBTOOL linelen NCARGS # endif #endif Then you grep the preprocessed file for '^LIBTOOL linelen *[0-9]* *' and extract the constant with sed. If there's no such constant, we might play with binary searching the length by running, say, `ls'. Or just go with a fixed, reasonable number, that can then be increased on a per-platform basis. > In my current implementation, the old method of linking is used unless > ${incr_archive_cmds} is defined AND the command is too long for the > shell. What if the command line is too long and incr_archive_cmds isn't defined? > I would like a bit of guidance since I seem to be hacking at the core > here. Indeed, you are. Sorry for not being more responsible, I've been far too busy for the past few weeks :-( > RMS suggested that it may be better to have libtool read commands from > a file, could one of the maintainers comment on that? This is definitely a good idea, but it can only work after what you're doing is implemented. One issue is that of preventing libtool from issuing command lines that are too long; the other is that of letting our users link as many object files as they want with libtool, despite command-line length limits that might arise in the invocation of libtool itself. You've been working on the former, but, in many cases, people with long lists of object files to link into a library will need the latter too. I suggest doing one thing at a time. Thank you *so* much for taking this over this task :-) -- Alexandre Oliva Enjoy Guarana', see Red Hat GCC Developer address@hidden, redhat.com} CS PhD student at IC-Unicamp address@hidden, gnu.org} Free Software Evangelist *Please* write to mailing lists, not to me | http://lists.gnu.org/archive/html/libtool/2000-12/msg00023.html | CC-MAIN-2016-44 | refinedweb | 540 | 66.57 |
Two Stack Model / Split Buffer for Text Editors
Get FREE domain for 1st year and build your brand new site
In my previous post, I wrote about data structures that could be used for text editors. And in this post, we will take a closer look at two of the data structures mentioned, in particular: two stack model and the split buffer.
To briefly reiterate the main points from the previous post, the core of a text editor relies on these essential functionalties: inserting, deleting, and viewing text. Based on the preferences you want your text editor to that will help you in which underlying data structures you would use. There is no best choice, but there are certainly better options depending on the text editor specifications.
Two Stack Model
In this data stucture, there are two stacks used hence the name two stack model. For the sake of portraying a difference, we will assume the stack will use a singly linked list as it's underlying data structure. The idea behind this data structure is to mimic editing lines rather than a huge document. The two stacks are used to represent the contents where the cursor is. One stack will represent all the contents left of the cursor while the other stack will represent all the contents right of the cursor.
The cursor is the black verticle line while the left stack is in reverse order while the right stack in the normal order. The two stack model will mimic a cursor movement by shifting the contents over their popping the stack and pushing it onto the other.
An important thing to take note is that we create our own stack using a linked list to allow more features without losing contents in the stacks such as viewing the entire input.
Interstingly enough, inserting, deleting, and viewing a character are all O(1) time complexity but inserting, deleting, and viewing a character at another location is O(N) where N is the amount of characters the cursor has to move through. Often times people will make lots of edits near one location which plays into the favor of the two stack model but the down side is that this approach does not perform well for large amounts of text where the cursor goes from one end to the other end of the large text over and over. There is also more memory required compared to perhaps a gap buffer but still less memory intensive as the tree approaches.
Moreover, I have not seen many real world text editors use this approach but it's certainly an interesting idea that is extremely easy to implement but more practical for an assignment.
Split Buffer
After reading the article where this idea came from, it is basically a variation of the two stack model. Everything else is pretty much the same idea as the two stack model except for the fact that you are using two array lists instead of two linked lists.
Although contents have to be shifted over, array lists have an amortised time complexity bringing all the fundamental operations to the same time complexity as the two stack model.
There is a bit more memory being unused in an the split buffer approach but accessing elements is a bit quicker than accessing links due to better cache performance but strictly speaking, they are both practically the same in performance but use a different underlying data structure.
Pros and Cons
Pros
- Extremely easy to implement
- Mimics a cursor and typing actions
- If the cursor is already at the edit location then inserting/deleting/viewing a character are all instant time complexity.
Cons
- Requires a bit more memory than other approaches.
- Does not handle large text documents but would handle lines and perhaps a paragraph just fine.
- Does not handle constant cursor jumping back and forth from the front and end of the text.
Code
I have decided to add code to show you how simple the implementation is.
I've implemented the three core fundamental functionalities for a text editor.
This section of code implements the underlying singly linked list.
public class Stack<T> { //generic stack protected static class Node<T> { Node<T> next; T data; public Node(T data, Node<T> next) { this.data = data; this.next = next; } } private Node<T> head; private int size; public void push(T item) { head = new Node<T>(item, head); size++; } public T pop() { T item = head.data; head = head.next; size--; return item; } public T peek() { return head.data; } public String getFrontToBack() { return getStackContent().toString(); } //The contents are in reverse order, so need to reverse the content to get back to front public String getBackToFront() { return getStackContent().reverse().toString(); } //Returning StringBuilder to make it easy to modify if we need to reverse the order of the contents //also a fast way of creating a string private StringBuilder getStackContent() { StringBuilder sb = new StringBuilder(size); //go through list and append the data for (Node<T> curr = head; curr != null; curr = curr.next) { sb.append(curr.data); } return sb; } public boolean isEmpty() { return head == null; } public int size() { return size; } }
These following sections shows the actual two stack model implemented.
public class TwoStackModel { public static final char EMPTY_CHAR = '\0'; private Stack<Character> left; private Stack<Character> right; public TwoStackModel() { left = new Stack<>(); right = new Stack<>(); } //Methods will be discussed public static void main(String[] args) { TwoStackModel buffer = new TwoStackModel(); buffer.insert("OpenGenus"); buffer.moveLeft(2); buffer.delete(); System.out.println(buffer.get() + "\t" + buffer.size()); buffer.delete(); buffer.moveLeft(3); System.out.println(buffer.get() + "\t" + buffer.size()); System.out.println(buffer.concatenate()); } }
Insert
Imagine the cursor is at the correct location. We are simply going to insert a character to the left of the cursor by adding it to the left stack.
The left stack is in reversed order as described on the left side of the two stack model picture. This will mimic the behavior of when you actually type a character.
public void insert(char ch) { left.push(ch); }
This is basically the insert method from above but we are going to insert a string as if we are pasting some text at the current cursor location.
public void insert(String input) { for (int i = 0; i < input.length(); i++) { left.push(input.charAt(i)); } }
Delete will simply delete whatever character is on the left side of the cursor. If there are no characters, we are going to return a default value null char which is nonprintable.
public char delete() { return left.isEmpty() ? EMPTY_CHAR : left.pop(); }
Moving cursor
This operation is where most of the time consuming work occurs where the cursor will pretend to move left simply by moving the contents on the left side onto the right side. There is also the case where the cursor can no longer go left, so we must ensure that left side still has contents to move otherwise stop.
//Moving the cursor position left, move left contents into the right stack public void moveLeft(int amount) { while (!left.isEmpty() && amount > 0) { right.push(left.pop()); amount--; } }
This is the ame operation as the one above, except will move contents right to left and the cursor will pretend to move right.
//Moving the cursor position right, move right contents into the left stack public void moveRight(int amount) { while (!right.isEmpty() && amount > 0) { left.push(right.pop()); amount--; } }
Viewing
Simply to how delete works, instead of modifying the underlying stack, we are only going to look at top of the stack. We also need to make sure to return an appropriate default value if the left side of the cursor is empty.
//Show content left of the cursor public char get() { return left.isEmpty() ? EMPTY_CHAR : left.peek(); }
This function will iterate throught the linked lists to concatenate both the left and right side of the buffer together in the proper order.
//Contents left and right of the cursor public String concatenate() { return left.getBackToFront() + right.getFrontToBack(); }
If we wanted to know how much content the cursor is dealing with, we simply add the contents on the left and right of the cursor.
//Size of contents left and right of the cursor public int size() { return left.size() + right.size(); }
Concatenating and moving the cursor takes O(N) time while all the operations are O(1) which is really nice in terms of such a simple implementation being able to perform quite well and mimicking a realistic text editor. | https://iq.opengenus.org/two-stack-model-split-buffer-for-text-editors/ | CC-MAIN-2021-43 | refinedweb | 1,413 | 59.84 |
PyX — Example: axis/grid.py
Drawing a graph with grid lines
from math import pi from pyx import * from pyx.graph import axis xgridpainter = axis.painter.regular(gridattrs=[]) ygridpainter = axis.painter.regular(gridattrs=[attr.changelist([style.linestyle.dashed, None])]) g = graph.graphxy(width=10, x=axis.lin(painter=xgridpainter, divisor=pi, texter=axis.texter.rational(suffix=r"\pi"), min=-4*pi, max=4*pi), y=axis.lin(painter=ygridpainter)) g.plot(graph.data.function("y(x)=sin(x)/x", points=200)) g.writeEPSfile() g.writePDFfile() g.writeSVGfile()
Description
The drawing of grid lines is performed by the axis painters of the graph. In order to turn on a grid, one has to specify in the argument
gridattrs a list of attributes defining the way the grid should look like. In order to enable a grid at the position of the axis ticks and subticks, it is enough to set
gridattrs to an empty list. In the example, this is done for the grid corresponding to the x-axis. If one wants to control the style of the grid lines or even turn them off selectively for the main or subticks, one can pass
attr.changelist instances in the list. The first item of the argument of this class is then used for the main ticks, the second for the first subticks, and so on. In the example, it is shown how to change the linestyle of the grid at the main tick positions and to turn off the grid for the subticks by setting the correpsonding value in the
attr.changelist instance to
None.
The example also shows a neat trick how to create an axis with axis labels at fractions of pi. This can be achieved by passing a
divisor argument to the axis itself, which means that for the axis handling, all values are divided by the corresponding value. Then, we automatically put ticks at the position of rational number by means of
axis.texter.rational and add the missing factor pi at the end of the TeX output. | http://pyx.sourceforge.net/examples/axis/grid.html | CC-MAIN-2016-26 | refinedweb | 341 | 57.57 |
Opened 3 years ago
Closed 3 years ago
#22427 closed Bug (needsinfo)
_session_cache of SessionBase affected by database session engine save
Description
I am running the exact same code on my local development machine and a production server.
Everything important I can think of is the same: both Ubuntu 13.10, both Python 2.7.5+, both Django 1.6.2, etc.
Yet the two machines are producing different behaviour!
I modified the file django/contrib/sessions/middleware.py, like so:
import sys sys.stderr.write('\nBefore!\n') for key, value in request.session.iteritems(): sys.stderr.write('%s=%s\n'%(key, value)) request.session.save() sys.stderr.write('\nAfter!\n') for key, value in request.session.iteritems(): sys.stderr.write('%s=%s\n'%(key, value))
So I am "printing" the session data before and after it is saved in the middleware.
On my machine, the data in question is present before and after (e.g. key = 'hello', value = '123'), but on the production server, the data in question is neither present before or after the save.
I have no idea how this is possible, but it's happening and driving me crazy.
Note: I am setting the session entry like so (in my view):
request.session['hello'] = '123'
So somewhere between that dict insertion and the middleware processing, the entry is completely disappearing, yet both machines are running identical code!
Change History (11)
comment:1 Changed 3 years ago by
comment:2 Changed 3 years ago by
Continuing on from the previous comment... or sometimes the "after" value just disappears for that 'hello' key!
comment:3 Changed 3 years ago by
This is certainly curious. What settings regarding sessions have you set, and are you using exactly the same database server? And are the settings between the two boxes the same? Calling it a "local development" machine makes me think DEBUG might already be set differently.
comment:4 Changed 3 years ago by
Using the default session engine, which I think is the database.
Yep, both running PostgreSQL 9.1.13
Settings are exactly the same (synchronisation managed by Git) and sorry should have been more clear, I get sane/desirable results on my local machine when DEBUG is True and False (i.e. when I'm in development and production mode).
comment:5 Changed 3 years ago by
Upgraded both machines to Ubuntu 14.04, which included an upgrade from PostgreSQL 9.1.13 to PostgreSQL 9.3
The problem still occurred.
I just tried switching from the default database session engine to a file system session engine and the problem seems to disappear.
Will try and do some investigation on that (not sure how helpful I will be), but it definitely looks like the database session engine is at fault here.
comment:6 Changed 3 years ago by
I'm pretty sure this is what's going on with the database session engine:
My manual call to save the session (request.session.save()) is working properly (have confirmed this), but then another copy of a request (and hence it's copy of a session) is overwriting my manual save.
I.e. I put debug prints in the Django database session engine code and noticed my manual save (looking as it should), but then there are two more saves after my manual one which sometimes (randomly) have the session data/values before my manual save and thus overwrite my desired data/values.
I'm guessing these overwriting saves are happening in the session middleware, but will confirm this.
So the problem seems to lie with the fact that copies of a request (and hence session) are being made, as opposed to creating references/pointers to the one canonical request (and session).
comment:7 Changed 3 years ago by
I have pinpointed the issue to as close as I can get without spending an enormous amount of time on it.
My latest find is that the "_session_cache" attribute of the SessionBase class (parent of the database SessionStore class) is changing when the database Session object/record gets saved.
I.e. I debug printed the value and id() of the _session_cache attribute before and after the transaction/atomic database save and sometimes (randomly) there are differences (which there shouldn't be).
Since session lookups are based off the _session_cache attribute, this is the most likely cause of the problem, but I have no idea why it is occurring on my production server machine and not my development machine.
Seems like some crazy Python bug to me, because I can't see why a database save would modify a different object, but who knows.
I'm just going to use the file system session engine for now (because I can't tolerate this absurd behaviour anymore), but I do hope someone is able to shed some light.
comment:8 Changed 3 years ago by
comment:9 Changed 3 years ago by
comment:10 Changed 3 years ago by
comment:11 Changed 3 years ago by
I am going to close this as needsinfo for now as I am not sure we'll be able to reproduce this given the details so far. If you can provide a minimal project that reproduces the issue that would be helpful.
Tried bringing the debug print statements forward, i.e. from the middleware to my view code (right after I insert the session entry):
The results on my local development machine are what a sane person would expect, but the results on the production server are what an insane person might expect.
I.e. On the production server, sometimes the results are OK, while other times the "before" and "after" values don't match up!!!
The "before" value might be right, but then the "after" value displays the previous value (from the last request).
I know it sounds like these two issues are not completely related, but the code on both machines is exactly the same! What the heck is going on??? | https://code.djangoproject.com/ticket/22427 | CC-MAIN-2017-39 | refinedweb | 997 | 61.67 |
This article describes how the code templates that are used when adding new project items in Visual Studio .NET work. There are several other articles on CodeProject that touches on this subject (a few are listed in the References section at the bottom) and the goal of this article is to describe in more detail how it works.
A component, called Krevera Template Manager, is also introduced that makes it (fairly) easy to create custom templates and its functionality is described. Included with the component are templates for strongly typed collections and strongly typed dictionaries for C#, VB and C++. If needed, this component can be extended to create even more powerful templates. All code examples are written in C#.
The component is available in two versions, one for Visual Studio .NET 2003 and one for Visual Studio .NET 2005. The latter has been tested on Beta 2 but will probably work with later versions as well.
There are several types of templates and wizards in Visual Studio, most notably project templates and project item templates. Project templates contain the basic files needed for the different types of projects, and project item templates are single file templates (or multiple if the item has code-behind files) that can be included in projects. To be completely accurate, there is actually no need of actual template files for all project items since they can also be created purely on-the-fly, but it's normally easiest to have a template file for each project item and then adjust it slightly when it's included in the project.
This article is about project item templates, for project templates the reader is advised to look elsewhere.
When adding a new project item to a project, the Add New Item dialog is displayed:
This dialog is where we will add our custom templates.
The items in the dialog above are generated by Visual Studio by reading configuration files from the current project type's project item directory. For example, if the current project is a Visual Basic project, then the items in this directory:
C:\Program Files\Microsoft Visual Studio .NET 2003\Vb7\VBProjectItems
are analyzed (that is on my system of course, the exact location depends on where the installation was made).
There are two important types of files in the project item directory:
These two types of files and a COM component that creates the instance are all that are needed to create project items. Here's an overall picture of how everything is connected:
The format of these files will now be more closely described before we introduce our solution to create flexible project item templates (as you might have guessed, it's an implementation of a COM component as described above).
Note that we can create categories of project items by storing our .vsdir and .vsz files in sub-directories. In the image above, we have sub-directories, for example, for "Local Project Items", "UI", "Code", etc.
Before we go into the details of file formats, it might be useful to know where to find the files. As usual, there are, of course, several ways. Easiest is probably to use the Explorer to navigate to the install directory of Visual Studio and look for sub-directories for the different .NET languages. For example, VB7 obviously contains stuff for Visual Basic. Within that directory, look for a directory name with "projectitem" in it. Soon enough, we find the VBProjectItems directory which contains the files. It's equally easy to find the project item directories for other project types.
However, if we want to do this programmatically, we use a more reliable way namely reading from the registry, under this key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\7.1\
Projects\{[PROJECT_TYPE_GUID]}
The value we're interested in, is called ItemTemplatesDir and it contains the absolute path to the correct directory. The only complication is that we have to know the GUID for the project type. For Visual Basic and C#, that GUID is available in the Visual Studio Automation interface in the form of these constants (requires a reference to VSLangProj.dll):
ItemTemplatesDir
VSLangProj.PrjKind.prjKindCSharpProject
VSLangProj.PrjKind.prjKindVBProject
Unfortunately, VSLangProj does not define constants for all project types, so for example, for C++, we have to hardcode it. Fortunately, it's fairly easy to find the correct GUID using regedit. Navigate to the key given above and look in each project sub-key for the DefaultProjectExtension value (for C++ that is vcproj). When that is found, we can be sure we're in the correct project type. Using that method, we find that the GUID for C++ projects is {8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}. The bad news is now of course that, we cannot be absolutely sure that Microsoft won't change this in the next Visual Studio version, but we'll worry about that when it happens...
VSLangProj
DefaultProjectExtension
Here's some code that retrieves the project item directory for C#:
const string sVisualStudioVersion = "7.1";
RegistryKey rk;
// C#
rk = Registry.LocalMachine.OpenSubKey("SOFTWARE")
.OpenSubKey("Microsoft")
.OpenSubKey("VisualStudio")
.OpenSubKey(sVisualStudioVersion)
.OpenSubKey("Projects")
.OpenSubKey(VSLangProj.PrjKind.prjKindCSharpProject);
_sCSProjItemPath = (string)rk.GetValue(@"ItemTemplatesDir");
Note: For Visual Studio .NET 2005 we set sVisualStudioVersion to "8.0".
sVisualStudioVersion
"8.0"
A .vsdir file lists a set of items and their properties. There can be several .vsdir files in the same directory.
The file format is described in MSDN (use the index search to find ".VSDir files") but here's a brief summary:
RelPathName
{clsidPackage}
LocalizedName
SortPriority
Description
DLLPath
IconResourceId
Flags
SuggestedBaseName
The fields that in my opinion are most interesting are marked with bold type in the list. I normally set all the others to 0 except SortPriority for which 1 is a suitable number. If an icon is desired it's easier to just copy an icon file (.ico extension) to the same directory as the .vsz file, and give it the same name as the .vsz file (except the extension of course) than to create resource components.
Here's an example of what a .vsdir file might look like (the lines are wrapped for readability):
Strongly Typed Collection.vsz|0|Typed Collection|1|
Sub-class of CollectionBase with elements of a given type|
0|0|0|TypedCollection.cs
Strongly Typed Dictionary.vsz|0|Typed Dictionary|1|
Sub-class of DictionaryBase with keys and values of the selected types|
0|0|0|TypedDictionary.cs
If we store that file in a sub-directory "Krevera Template Manager", the following items will be displayed in the Add New Item dialog (a few column numbers are given in the image to show how the column strings of the .vsdir file are used):
When the user selects an item and clicks the Open button, then Visual Studio opens the item's .vsz file, so it's time to describe its format now.
The sole purpose of .vsz files is to tell Visual Studio what component to call to create the project item and the parameters it needs. The file format is very simple and here's an example (namely the standard "Class" project item for C#):
VSWIZARD 7.0
Wizard=VsWizard.VsWizardEngine.7.1
Param="WIZARD_NAME = CSharpAddClassWiz"
Param="WIZARD_UI = FALSE"
Param="PROJECT_TYPE = CSPROJ"
Description:
WIZARD_NAME = CSharpAddClassWiz
There is not really a whole lot more to say about the .vsz file format, so we continue with describing the logic of actually creating project items.
As already mentioned, the actual project item is created by a component pointed out by a .vsz file. The component must fulfill a few requirements:
EnvDTE.IDTWizard
And that's it. When the project item is to be created, Visual Studio creates an instance of the class and calls its Execute method, in which the class creates the new project item and inserts it into the ProjectItems collection. Creating the project item normally involves copying an existing template file and modifying it according to the name given in the Add New Item dialog, the current project's default namespace, and other things.
Microsoft has created a fairly large number of project item templates that work in this way. The actual template files are not stored together with the .vsdir and .vsz files, but separately. It's entirely possible to adjust them, using the method described in the Code Project article "Customizing Visual Studio's Code Generation Templates" but the possible modifications are limited to layout changes, standard file headers etc. No dynamic content (current date, username, etc.) can be added, since the component that adjusts the template file for the project is limited to do what the Visual Studio developers deemed feasible. Also there is, as far as I know, no documentation of the variable replacements that are performed by the standard component. Another problem is that, we cannot build new logic, for example asking the user for information.
To allow creating more complex templates, we thus have to create a new COM IDTWizard component, and that's exactly what will be presented now.
IDTWizard
Krevera Template Manager is basically a COM component for handling requests for creating new project items. It's written in C# and the full source code is available for download at the top of this article. There's also a binary download that contains an installation program for the component and a few sample templates for creating strongly typed collections and dictionaries in C#, VB and C++.
Templates are normal text files that contain variables that Krevera Template Manager replaces when creating the project items. The variables are written in XML and include the following (the type attribute is here for clarity, it can be ignored in this case since its default value is "standard"):
<variable type="environment" name="TEMP"/>
Finally, we can also use custom variables whose values we retrieve by asking the user in a wizard-like interface. Here's an example:
<wizard>
<page>
<title>Select data type</title>
<description>Select data type for which to create
a strongly typed collection</description>
<variable name="datatype"/>
</page>
</wizard>
When creating the project item whose template contains the above wizard fragment, the following dialog is displayed:
When the user has typed the wanted value for the custom variable (named "datatype" in the example), we can use it later in the template by using variables with the type attribute set to "custom":
datatype
custom
<variable type="custom" name="datatype"/>
To make sure that the variable declaration for the template does not collide with the code syntax in the template text, all variables must be surrounded by [% and %].
[%
%]
To summarize, we now show the top part of a real template, namely the template for creating strongly typed collections that is distributed with the code:
[%
<wizard>
<page>
<title>Select data type</title>
<description>Select data type for which to create a
strongly typed collection</description>
<variable name="datatype"/>
</page>
</wizard>
%]using System;
using System.Collections;
namespace [%<variable name="namespace"/>%] {
public class [%<variable type="standard"
name="filenamebase"/>%] : CollectionBase
{
public [%<variable type="custom"
name="datatype"/>%] this[ int index ] {
get
{
return( ([%<variable type="custom"
name="datatype"/>%]) List[index] );
}
set
{
List[index] = value;
}
}
...
If we insert a project item of this type into a project with a default namespace of CS_Test, name the item FoobarCollection.cs, and answer the wizard question with Foobar, we will get a file containing the following:
CS_Test
Foobar
using System;
using System.Collections;
namespace CS_Test
{
public class FoobarCollection : CollectionBase
{
public Foobar this[ int index ]
{
get
{
return( (Foobar) List[index] );
}
set
{
List[index] = value;
}
}
...
Hopefully everyone agrees that, this is a very easy way of creating strongly typed collections, compared to doing it yourself.
Other frequent uses for templates are to enforce organization-wide rules about file headers. With this component, it's easy to include filename, creation date, username, etc. automatically in the header of the files. It's also easy to create new variables if needed, just modify the Wizard.EvaluateVariable function in the code to implement evaluation of the new variables.
Wizard.EvaluateVariable
The code will not be described in detail here; it's probably easier to read the code and its comments directly. It may however be useful to have an overview of how the code works, so here we go:
sn -k TemplateManager.snk
The key file must also be referenced from AssemblyInfo.cs (see that file for the details).
Update: This does not apply to the Visual Studio .NET 2005 version. We still have to set Register for COM Interop but we don't have to worry about strong names etc.
Krevera.TemplateManager.Wizard
Those steps should be enough to use the templates.
You're allowed to use this software in any way you want, except for making money. You're free to use it privately or in your organization (in original or modified state) but you're not allowed to include it in commercial products etc. At least not without explicit approval by the author (i.e. me!).
Book:
This is a book with a very good scope but unfortunately the contents don't look very organized and there are a number of errors. Still, it doesn't have very much of a competition, so it can still be recommended for readers interested in creating macros and add-ins for Visual Studio.
Other Code Project articles: 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/9856/Creating-project-item-code-templates-for-Visual-St?fid=162997&df=90&mpp=10&noise=1&prof=True&sort=Position&view=Expanded&spc=None | CC-MAIN-2014-52 | refinedweb | 2,230 | 52.8 |
Up to [DragonFly] / src / share / man / man9
Request diff between arbitrary revisions
Keyword substitution: kv
Default branch: MAIN
Sweep over our manual pages and remove .Pp before a .Bd or .Bl without -compact because it has no effect.
My round of spelling corrections in /share/man.
Don't use \*[Px] because it leads to an unwanted font size change. Found-in: FreeBSD
- Uniformly use .In for header file references. - Fix numerous wrong directory names.
Clarify what new code should not cast unused return values of functions to void.
Make an example follow the recommendation given in the immediately preceding paragraph, i.e. that function prototypes in userland code should not include parameter names.
Add omitted space after 'while'. Submitted by: Sascha Wildner Asked to commit by: joerg
Minor style cleanups. Start a list of obsolete functions that should no longer be used, and add a warning about the use of unbounded string functions. Submitted-by: "Douwe Kiela" <virtus@wanadoo.nl> Additional-work-by: Matt Dillon
Use stronger wording against using 'register' and '__P()'.
Correct spelling. Submitted-by: Tim Wickberg <me at k9mach3.org>
Remove unneeded empty line to silence mdoc(7) warnings.
Update to style(9) guidelines. - Explicitly state that the ``register'' keyword should be avoided. - Correct example and description of preferred indentation when wrapping function arguments over multiple lines. - Resolve contradictions in guidelines for ``return''. - Explicitly state whitespace rules for commas, semicolons, ``->'' and ``.'' operators. - General clarifications. Approved-by: dillon
main() more typically uses 'char **argv' instead of 'char *argv[]'. Remove the requirement that an empty line be inserted in function definitions without local variables (the requirement is actually that NO empty line be inserted). Revamp the documentation on when and when not to use braces around substatements. Submitted-by: Chris Pressey <cpressey@catseye.mine.nu> Additional-changes-by: dillon>
There are historically two families of fixed size integers, u_intX_t and uintX_t. Since the former is BSD specific, while the later is defined for POSIX anyway, prefer the second form.
Don't use parameter names for kernel prototyps
Update style(9) to reflect current code practise. Patch submitted by Chris Pressey <cpressey@catseye.mine.nu>
func() -> func(void) style.
Remove FBSDID, move $ rcs id back to a comment field.
Add the DragonFly cvs id and perform general cleanups on cvs/rcs/sccs ids. Most ids have been removed from !lint sections and moved into comment sections.
import from FreeBSD RELENG_4 1.32.2.19 | http://www.dragonflybsd.org/cvsweb/src/share/man/man9/style.9?f=h | CC-MAIN-2013-48 | refinedweb | 404 | 52.76 |
Juan Carlos Arevalo Baeza wrote: > Udo Stenzel wrote: > >Don't you think this will interfere somehow with type inference? > > With type inference? No, why? I mean... specifying the type of a > function [...] Okay, so want an implicit (return ()) only if the type of the do-block has been explicitly specified as (m ()) for a monad m. I've become used to type inference and assumed you wanted to tack on the (return ()) if the corresponding type was only inferred. The former is less destructive, of course. I still dislike it, being a special rule with very limited use. > >yourParser :: Parser String > >yourParser = liftM2 (++) (string "Hello") > > (option "" (string ", world!") > > Personally, that style is way too functional (and a bit lisp-ish) for > me. Uhm, well, of course you're entitled to an opinion, but I know where to find the children of Algol when I need them... > >ourParser :: Parser String > >ourParser = string "Hello" *> optional (string ", world!") > > So you do drop returned values now and then? But with that function > you lose out on the do-notation convenience. Why, yes, I do, but I like being explicit about it. (And I'm not sure that (*>) is explicit enough.) And I must confess, I don't find do-notation all that convenient. If it weren't for fail being called if a pattern match fails, I'd probably never use it at all. > >I'm more reminded of Perl... > > I don't know perl :) You're a very lucky man. (No, seriously, Perl is quite the opposite of Haskell in nearly every aspect.) : | http://www.haskell.org/pipermail/haskell-cafe/2006-February/014518.html | CC-MAIN-2014-41 | refinedweb | 260 | 75.91 |
When trying to run my code it gives me an error saying '.class' expected. When I put a class at the start of my code and try to run it, it tells me I don't need to add a class for this problem.
This is probably happening because the question is asking for "bare code" and thus does not require a class. Just the code that creates whatever output you are trying to create.
Could you give us the scope of this question? That would assist in providing an answer.
The error "'.class' expected" refers to an event where the compiler identifies a type name where it expects an expression and thinks you are trying to refer to that type's class object. For example, putting a main() method at the beginning of a PracticeIt question that asks for bare code returns this error, along with a slug of others:
"'.class' expected"
main()
Line 1, Column 34
'.class' expected
public static void main(String[] args) {
Line 1, Column 34
'.class' expected
public static void main(String[] args) {
This error can be the result of a misplaced class call, or by the fact that the problem asks for bare code-- where the `public class and main` methods aren't required. Check over the problem in question to make sure there aren't any silly mistakes.
`public class
and
main
Source: StackOverflow
Have you tried doing without creating a class? | http://lovelace.augustana.edu/q2a/index.php/613/what-does-class-expected-mean-in-practice-it | CC-MAIN-2019-09 | refinedweb | 239 | 70.23 |
We):
In this example we imported all members named
foo from the named object
mypackage.MyObject.
To import from companion objects of classes, we have to specify their full name:
Rich @Deprecated
We have been migrating a lot of code lately:
Multiple main() functions in the same package
We can now define a
main() function with standard signature in each file (with the exception of
@file:JvmMultileClass). This is very useful when experimenting with code:
Varargs and spread operator
To recap: when calling a
vararg function, we can use the spread operator that converts an array to a vararg::
@UnsafeVariance annotation
Sometimes we need to suppress declaration-site variance checks in our classes. For example, to make
Set.contains typesafe while keeping read-only sets co-variant, we had to do it::
Delegated properties. The conventions for delegated properties now use
KProperty<*> instead of
PropertyMetadata in
getValue and
setValue::
Nothing-returning functions. When a function is known to throw an exception or loop forever, it’s return type may be
Nothing, which means that it never returns normally. To make the tooling smarter, we require that such functions always have their return type specified explicitly:
It’s been stated before that futher work on JavaScript support will be after 1.0. So its a great question to ask after 1.0.
The plan for JavaScript is that it has to wait until we are done with 1.0 for JVM, and then we’ll get back to it.
Congratulations, guys ! Kotlin 1.0 is in sight, that’s tremendous news
All changes announced look good to me
I’m really excited about Kotlin finally reaching 1.0
Some libraries updated for this release of Kotlin:
Jackson-module-kotlin
2.6.3-1
Injekt
1.8.0
Klutter
0.8.0
Kovert
0.6.0
Kovenant
2.9.0
it’s nice to get more safety for maps and sets…
Got bitten by that a few times and it used to take time to find where the bugs came from
That’s really wonderful news
Love it! Love the better support for Android as well
Keep up the good work.?
Just checked on device with Android 4.1.2, same issue.
Can you please create a small project in which the bug can be reproduced? You can send it to yan.zhulanow[at]jetbrains.com.
I was able to reproduce the bug. We will investigate it.
I have the same issue, It’s fix now? I can’t install kotlin app on Meizu’s Phone. I’m using 1.0.0-beta-1038, I need help urgent.
We will publish a fix soon. Meanwhile you can roll back to the previous version of Kotlin.
I see, it is fixed in 1.0.0-beta-1103, thank you!
I’ve encountered this problem too…
And I also encountered with
INSTALL_FAILED_UID_CHANGED
INSTALL_FAILED_UID_CHANGED too!!!
Please fix it QAQ…
Must be fixed in 1.0.0-beta-1103, check it please
I’m trying to rollback to 0.14.451 but I can’t find the right plugins
There is a link
Show All Updatesat the bottom of the page:
What about better support for Annotation Processing?
What use cases do you have in mind?
Fully supporting Dagger 2 (as far as I know currently it’s not possible to use generated classes in Kotlin), supporting other libraries like Android’s DataBinding or ButterKnife.
Generated classes can be used with new
kapt:
That’s interesting, I couldn’t make it work. It would be great if you would update Dagger sample project on github
And what about ButterKnife and DataBinding? Should they work just fine?
I am confused why kotlin exists when scala has near identical syntax, has been around longer, can seem to do everything that kotlin can as well as a tremendous amount more. Can anyone clarify? This seems like a pretty fair answer to your question
Watch just about any of the videos they have out there. They have some beefs against Scala.
Kotlin has much better Android support than Scala. And for me that is a killer feature..
Pingback: Kotlin 1.0 Beta Candidate is Out! | JAVA
Great news!
Special thanks for relaxing “operator” restriction for java methods.!”
Pingback: Beta Candidate für Kotlin 1.0 erhältlich - JAXenter
}
Thanks for the use case. We’ll probably relax some limitations on data classes
Finally have you made a decision concerning marking result expressions ?
“^” or “<-” ?
Hi, I’m wondering as well if marking result expressions will make it into 1.0 or it was decided that it will be a future feature?
Thanks
Definitely not 1.0, most probably not a future feature either
Yes, we considered many points, and decided that it was impractical to require prefixes on result expressions…
Looks like either the standard library was not updated (e.g. you have different versions in the IDE plug-in and in Gradle), or IDE caches got stuck (in this case *File -> Invalidate Caches -> Invalidate and Restart)
Which one is new then in my case? Library or plugin? Invalidating cache didn’t help.
How is your project configured? Do you use Gradle? If yes, you can see the library version in your build file. And the version of the plug-in can be seen in Plugin Manager
Pingback: Links of the Week, W44 2015 | One More Game-Dev and Programming Blog
May I ask why
import object.*is not allowed?
Since Kotlin plugin can’t add import
object.Aautomatically, we still have to write import statements one by one for every imported object methods and variables.
import object.*leads to importing
hashCode,
equalset al. Mostly it would be very confusing.
And most likely special intention action will be implemented for auto imports from objects.
Objects may inherit things from supertypes, e.g.
equals()/hashCode()will be imported every time you ‘*’-import from an object, we decided that this would be too confusing. The IDE should be fixed soon
How about also add autoconversion between simple types? int -> float, float -> double
it’s a little anoing
fun foo(x:Float)
foo(1) //error
fii(1f) //no error
Unfortunately, this is incompatible with the fact that we do not distinguish between primitive types and classes
And I think it’s a bad idea, too. I just hate how many errors I get in Java because of automatic conversions. I’ve never grasped what is converted to what. Kotlin way seems much better,] –
Why we need the spread operator: because, for example, if a function takes vararg of Any, then any array may be either an element of a vararg or a container for all vararg elements:
I see. Thank you for your explanation and example. I am sorry for post the same question twice.
My previous comment got removed for some reasons so I ask again. Why do we need * prefix to pass arrays as varargs?
I would love to see the spread operator for maps for named arguments.
Can’t be done in a static language
That makes me sad. Still love kotlin so far. Looking forward to the finalized 1.0 release for my production android projects.
I think I’ve found an issue with 1.0 deleteAt(Int) vs delete(int) magic, filled it under KT-9824?
The reflection API is not complete at this point, more information, such as detailed type information, will be added later. As a workaround you could use Java reflection now (there’s an API to convert a Kotlin reflection object to a Java reflection object).
Can not install android apk file below Android 4.4
Failure [INSTALL_FAILED_UID_CHANGED]
Must be fixed in 1.0.0-beta-1103, check it please
I tried to install a simple android app on fresh emulator with android 4.1 with a new kotlin v.1.0.0-beta-1103, but had the same INSTALL_FAILED_UID_CHANGED problem.
From what I see here, it may not be connected to Kotlin.
Could you try one of these?
Looks like your AVD is not so “fresh”
Wipe out user data and the error will be gone.
Factory reset and removing /data/data/ folder work, but how about updating application?
Once app install failed with error INSTALL_FAILED_DEXOPT, you must reboot the device before install valid APK again, otherwise you will see INSTALL_FAILED_UID_CHANGED error.
Hi,
can you please check this issue?
Issue appeared in beta candidate and it appears in 1.0.0-beta-1103 as well.
I know that Javascript compilation is not your priority right now but hope it get resolved in 1.0
Thanks | https://blog.jetbrains.com/kotlin/2015/10/kotlin-1-0-beta-candidate-is-out/ | CC-MAIN-2019-43 | refinedweb | 1,429 | 67.35 |
See Also edit
- corp
- Can be used to "ship" a procedure to another interpreter.
- fmail, by AK
- Nicely employs slave interpreters.
- exit in slave interpreter
- Covers a specific trickiness in interp management.
- Managing Complexity in TeamRooms, a Tcl-Based Internet Groupware Application
, Mark Roseman, 1996
- An article about TeamWave that explains specific interp benefits of encapsulation and security. In a conversation in mid-2001, Mark summarized, "But if you have what might be considered very coarse-grained objects that really could be conceptualized as self-contained applications, multiple Tcl interpreters are definitely an option to consider."
- Safe Interps
- dgp: Nicely encapsulated the role of interp as to address "isolation and partition".
- tkcon
- An enhanced Tk console built in pure Tcl/Tk. It makes use of slave interpreters to isolate the user environment from the tkcon environment, except through certain special commands. It makes use of many tricks with interpreter slaves.
- Windows focus and multiple proc
, comp.lang.tcl, 2002-05-02
- DKF illustrates that interps can serve as an elegant "light-weight" way to implement related proc-s in a unified fashion.
Syntax edit
-
- interp option ?arg arg ...?
-
- interp alias srcPath srcToken
-
- interp alias srcPath srcToken {}
-
- interp alias srcPath srcToken targetPath targetCmd ?arg arg ...?
-
- interp aliases ?path?
-
- interp bgerror path ?cmdPrefix?
-
- interp cancel ?-unwind? ?- -? ?path? ?result?
-
- interp create ?-safe? ?- -? ?path?
-
- interp debug path ?-frame ?boolean??
-
- interp delete ?path ...?
-
- interp eval path arg ?arg ...?
-
- interp exists path
-
- interp expose path hiddenName ?exposedCmdName?
-
- interp hidden path
-
- interp hide path exposedCmdName ?hiddenCmdName?
-
- interp invokehidden path ?-option ...? hiddenCmdName ?arg ...?
-
- interp issafe ?path?
-
- interp limit path limittype ?-option? ?value ...?
-
- interp marktrusted path
-
- interp recursionlimit path ?newlimit?
-
- interp share srcPath channelId destPath
-
- interp slaves ?path?
-
- interp target path alias
-
- interp transfer srcPath channelId destPath
Documentation edit
Description editMany newcomers to interps seem to (mis?)understand them as a variant on object orientation, in that they provide a kind of encapsulation, inheritance, and ...The historical origin of interp was in "safe interpretation", that is, a mechanism for secure code evaluation. At a high level, this is what Java provides with its "sandbox", although far less flexibly and perhaps less securely.Another occasionally hazardous way to think about interps is as a programming model for handling a very weak form of concurrency. Interps originated as "safe interpreters" in the agent work of such people as Marshall T. Rose, ...[Explain insights from
Jeffrey Hobbs observes that, though several books mention interps, none really explains them adequately; they don't "go into enough detail for people to really understand what magic can be done. The power and flexibility of slave interpreters in Tcl is YA large advantage over other languages." (for more on Tcl's advantages, see "How Tcl is special")
Shared Resources editMGS 2006-09-11: I always thought that slave interps had their own working directory, but now I see that is not the case. Is there any way to prevent working directories in parent/child interps from being linked? Thanks.DGP: No. The Tcl filesystem is process-wide. All interps in all threads see the same filesystem, including the same value of the current working directory.Yes, this means that another thread can change the value of the current working directory right out from under you.Yes, this means any use of relative pathnames is inherently thread unsafe. Write your programs accordingly.
MHo: The env array (and other system information) seems to be global and shared between all interpreters, too. Also I noticed, that there is only one global event loop. If you do, e.g., a tk_messageBox from within a slave interpreter, after events originating from the master interpreter are processed. This is because tk_messageBox is waiting for user input via the global event loop. The conclusion is, not only to avoid the usage of vwait, tkwait and update to not produce unwanted side effects by accidentely re-entering the eventloop, but not to use any tk dialog from within slaves. Or am I wrong?
Examples edit[Gary Petersen] provides this on comp.lang.tcl as an example of using interp to create child interpreters and then using them.
# Create a new interpreter named "a": interp create a # Create a new interpreter named "b" within interpreter "a": interp create {a b} # Create a new interpreter named "c" within interpreter "b": interp create {a b c} # Make the "c" interpreter do something: interp eval {a b c} [list puts "Hello there."] # This is another way to create a new interpreter # within an interpreter (named dionysus): interp eval {a b c} [list interp create dionysus] # Let's get "dionysus" to do something by invoking it by name. interp eval {a b c} \ [list dionysus eval [list puts "Interpreter nesting works."]] set mycommand {puts "Interpreter paths have *nothing* to do\ with the filesystem."} interp eval {a b c dionysus} $mycommandNote that the creation of the deeply nested set of interps was not required by the above example - the example is for illustration purposes rather than for functionality.
DKF: You can do some cool things with interp (and other Tcl commands) to do things like dynamic downloading of code over the 'net...
package require Tk package require http pack [frame .f -container true] set i [interp create -safe] ::safe::loadTk $i -use [winfo id .f] proc http_source {interp base filename} { regsub {.*:/*} $filename {} trimmed set token [http::geturl $base$trimmed] set script [http::data $token] http::cleanup $token $interp eval $script } $i alias source http_source $i $YourBaseUrl $i expose exit; # WE DON'T MIND PEOPLE QUITTING THE APP! http_source $i $YourBaseUrl InitApp.tcl vwait forever
RS has been playing with interps too:
% interp create foo fooBy nature interps offer best encapsulation - their master can introspect them of course. On the other hand, they're probably more heavyweight than namespaces, and would have to repeat all package loading where required.The above code probably needs polishing up... :^)
Coupling variables between interpreters editMaybe this belongs on it's own page but...I've been playing around with sharing or linking variables between interpreters. I've got something that works in my very limited testing. I'll post it here because it may be useful to someone else and so I might get some feedback. -- CLN
# shareVar.tcl -- # # Allow sharing (or linking) of variables between interpreters. # # # Copyright 2002 Pinebush Technologies, Inc. # # Exported procs: # sharevar::sharevar - Sets up link between interpreters # # Private procs: # sharevar::TraceVariable - Updates other interpreter when # variable is written. # # Example: # # Create a slave interpreter # interp create a # # # Share a variable (common name) # sharevar::sharevar {} foo a foo # # # Create a namespace to play with. # namespace eval X { # variable X # } # # # Share a variable (different name and namespace). # sharevar::sharevar {} X::X a x # # # Create another slave # interp create b # # # Share a variable between them # sharevar::sharevar a a b b # # # Global data: # None. # #----------------------------------------------------------------------- package provide sharevar 0.1 namespace eval ::sharevar { namespace export \ sharevar } #======================================================================= # Public procs #======================================================================= # sharevar::sharevar -- # # Make varName a shared variable in sourcePath and targetPath. # # Arguments: # sourcePath - First interpreter to link # sourceVar - Variable in sourcePath to link to # targetPath - Second interpreter to link # targetVar - Variable in targetPath to link to # # Results: # Updates to sourceVar in sourcePath will change targetVar in targetPath # and vice versa. # # If sourceVar exists, targetVar is set to its value. If sourceVar # does not exist, and targetVar does, sourceVar is set to # targetVar's value. # proc sharevar::sharevar { sourcePath sourceVar targetPath targetVar} { foreach fromInterp [list $sourcePath $targetPath] \ fromVar [list $sourceVar $targetVar] \ toInterp [list $targetPath $sourcePath] \ toVar [list $targetVar $sourceVar] \ { # Give the interpreter the sharing proc interp alias $fromInterp shareTraceVariable \ {} [namespace code TraceVariable] # Use that command when the variable is written. set traceCmd [list shareTraceVariable \ $fromInterp $fromVar $toInterp $toVar] interp eval $fromInterp \ [list trace variable ::$fromVar w $traceCmd] # WUZ - need to clean up later, remove trace } # Initial synchronization if { [interp eval $sourcePath info exists $sourceVar]} { TraceVariable $sourcePath $sourceVar $targetPath $targetVar } elseif { [interp eval $targetPath info exists $targetVar] && ! [interp eval $sourcePath info exists $sourceVar]} { TraceVariable $targetPath $targetVar $sourcePath $sourceVar } else { # Neither exists, first write will sync. } } # sharevar::sharevar # #======================================================================= # Private procs only below this line #======================================================================= # sharevar::TraceVariable -- # # React to change in one interpreter by updating the other. # # Arguments: # fromInterp - Interpreter where value changed # fromVar - Variable in fromInterp which changed # toInterp - Interpreter to update # toVar - Variable in toInterp to update # args - (IGNORED) Added by the variable trace # # Results: # toVar is updated # proc sharevar::TraceVariable { fromInterp fromVar toInterp toVar args } { puts stderr [info level 0] set value [interp eval $fromInterp set ::$fromVar] interp eval $toInterp [list set ::$toVar $value] } # sharevar::TraceVariable
Discussion edit
suchenwi: Another OT: Why do windows have children, but interps have slaves? stever: because slaves do work? children just play?
ken: Just want to enquire whether is it possible to use interp to create a slave interp which can execute on its own but suspend and awaiting for command for the main interp to input a variable to it before it continues. I trying to emulate a discrete event simulator model of sensor nodes which my event queue is running continuously to activate the node that should be awake at a single time then update a variable so thtat the slave interp emulating that node can run and then suspend and pass control back to the main interp to continue? Is it possible? Thanks in advanceLars H: Not with interp-created interpreters, for the same C call stack reasons as prevented your tkwait attempts at this earlier. It might be possible using threads though.PYK 2015-04-15: And in modern versions of Tcl, there's coroutine.
Perhaps someone here can shed light on an issue. When I enter the code as listed above
package require Tk package require http pack [frame .f -container true] set i [interp create -safe] ::safe::loadTk $i -use [winfo id .f] ...and the remainder of the script...and execute it I get the following error condition:
can't read "Sinterp0(access_path,n)": no such element in array while executingwith the remainder of the stack trace down to the call to safe::loadTk. I was able to load Tk into the slave using the mechanism elsewhere where you need to provide the argv list to make it work, but the safe:: package always errors. This is consistent on the Cygwin WISH and tclkit interpreters.Any ideas?
TR It seems the correct way to get Tk in an interpreter is to do (taken from the Using Tk as a loadable package page, down at the bottom there):
interp create slave load {} Tk slaveAt least, using package require inside the slave interpreter, was not really working for me.RFox 2012-10-01 12:18:22:On Tcl 8.5.8/Tk 8.5.8
interp eval slave package require Tkworks just fine for me.TR: Maybe this has to do with using an embedded build of Tcl (Tcl8.6b3 here from fossil trunk) on Mac. I call the embedded Wish from the Finder and just type the two lines of code and Wish will then crash with something like
Thread 0 Crashed:: Dispatch queue: com.apple.main-thread 0 libsystem_kernel.dylib 0x93f9b9c6 __pthread_kill + 10 1 libsystem_c.dylib 0x93781f78 pthread_kill + 106 2 libsystem_c.dylib 0x93772bdd abort + 167 3 Tcl 0x001d8e77 Tcl_PanicVA + 227 4 Tcl 0x001d8e92 Tcl_Panic + 27 5 Tcl 0x001bf518 Tcl_RegisterChannel + 108 6 Tk 0x0e66fed8 TkpInit + 1207 ...Actually, I can also do what you describe with Tk 8.5.12 (also embedded build) just fine. So, it could be an issue with Tk-Cocoa on Tk 8.6, but this is not for sure. So how is [interp eval slave package require Tk] different from load {} Tk slave? The first is executed inside the slave, the second is executed in the master interp? | http://wiki.tcl.tk/1477 | CC-MAIN-2015-35 | refinedweb | 1,934 | 54.63 |
Chapter 1In this chapter:
Windows NT/2000 Security
Internet Threats
Building a Secure Site on the Internet
The Windows NT/2000 Architectures
Windows NT/2000 in the Perimeter Network
Cryptography Basics
The use of Windows systems as Internet servers presents security challenges. In contrast to most internal systems, systems connected to the Internet are directly exposed to security attacks from both unsophisticated and highly skilled attackers. The typical Windows NT 4.0 (and, more recently, Windows 2000) installation makes a Windows server an easy target for such attacks. Securing the Windows NT or the Windows 2000 operating system for Internet use is a complex task. The purpose of this book is to offer a strategy for making your Windows-based server configuration as secure as possible. This strategy has two basic parts:
- Secure or "harden" any Windows server that will be exposed to potential attacks from the Internet so it is as secure as it possibly can be. An exposed system of this kind is typically known as a bastion host.
- Provide extra security protection for such exposed systems by installing an additional network -- typically known as a perimeter network -- that separates the outside network (usually the Internet) from your organization's internal networks.
Later chapters of this book describe specifically how to harden your Windows NT or Windows 2000 system so it can function on your perimeter network as a secure bastion host. Before I present the step-by-step security details, this chapter sets the scene by describing briefly the security threats your system will face, the architecture of the Windows NT and Windows 2000 operating systems, and the recommended placement of Windows servers on your perimeter network.
Internet Threats
An Internet server faces many different kinds of threats. The most common include:
- Intrusion
- An intrusion occurs when an unauthorized person gains access to your system. These days, intrusions most often result in web page defacement: an attacker alters the contents of your web site. Such attacks are growing in popularity. Attrition () maintains a daily updated list of defaced web sites. The current record is 56 reported defacements in one day (November 21, 1999). About 60% of the defacements recorded at Attrition between October 1999 and April 2000 have occurred on Windows NT systems.
- Denial of service
- The goal of a denial of service (DOS) attack is to sabotage operation by consuming all of your computing resources (CPU time, network bandwidth, etc.). This effectively stops authorized users from using the system.
- Information theft
- This type of attack occurs when an unauthorized person obtains private information. The most popular targets are login/password information, credit card information, and software source code.
Many intrusions are made possible by improperly configured software. Looking at a concrete example may help underscore this point. Recently, the Apache web server site () was hacked.[1] In this particular case, the attackers uploaded a PHP[2] script to a world-writeable FTP directory. The web server root directory was the same as the FTP server root directory. This allowed the attackers to launch Unix commands using the uploaded script. They uploaded and executed a shell binary that bound to a high port and enabled them to initiate a connection to that port. The attackers now had interactive shell access on the system. The next step was to gain root access. This was accomplished by using a database process that was running as root to indirectly create a setuid root shell.
Fortunately, these attackers (so-called "gray-hats"[3]) were not out to thrash the site; they only replaced the "powered by Apache" logo with a Microsoft Back Office logo and alerted the site administrators.
The following configuration errors made the Apache break-in possible:
- The web server and the FTP server had the same root directory. This allowed the attackers to upload the software that was used to launch the attack. The uploaded software could be executed because the web server software used the same filesystem hierarchy.
- There was no (or an improperly configured) firewall system protecting the web server. It was possible for the attackers to connect to any port on the system. This made the attack much easier.
- The database software was running as root. This is the reason why the attackers were eventually able to gain root access.
Windows NT systems present many vulnerabilities, which attackers are only too happy to take advantage of. For example, there are cases where an attacker has been able to connect directly to a system using Windows file sharing. Those systems are an even easier target than the Apache site was. Just start guessing passwords and try to connect as Administrator!
The number of security incidents reported to the Computer Emergency Response Team Coordination Center (CERT-CC)[4] has grown at an alarming rate in recent years. Figure 1-1 illustrates this development; note how steeply incidents have increased since 1997. (Incidents include, but are not limited to, attempts to gain unauthorized access to a system or its data, and disruption or denial of service.) The real security picture is far worse than these statistics show; it's safe to assume that only a small number of all incidents are reported to CERT-CC.
If you already have a presence on the Internet, you probably know that attempts are made to compromise your site's security mechanisms every day. And the stakes are high. Imagine how you'd feel if an online store that you use was hacked and the attacker managed to steal your credit card information. Would you feel comfortable shopping there again? Would you use an Internet bank that was successfully attacked last year? I wouldn't.
As a result, it's of great importance to have and maintain a high level of security for your site. This is a complex task, but after reading this book I hope you will find it somewhat less troublesome.
Keep in mind that even if you're not running a large online bank or shopping site, you still need to take steps to protect your servers. The attackers are out there; they may be after your intellectual property; they may want to use your computing resources; or they may just want to have some fun defacing your web site.
Building a Secure Site on the Internet
Building and maintaining a secure site on the Internet includes many more tasks than simply installing your operating system, however securely you may do so. Overall security is a combination of secure software and careful human planning and administration. You will need to be concerned with all of the following tasks:
- Planning
- Securing an Internet site must be a carefully planned and coordinated process. It's not just a matter of clicking on screens and working it out as you go. Figure out the goals and tactics ahead of time, and then implement security, step-by-step. It's also important to understand that you need one encompassing plan that includes all aspects of the process, rather than several small and uncoordinated planning efforts.
- Policies
- In order to achieve a high level of security, you need policies that define the main aspects of running an Internet site. This is not a book on policies, but keep in mind that before you start building a secure system, you need to have the appropriate policies in place. Start by reading the Site Security Handbook (RFC 2196); it's an excellent introduction to this topic.
- Access control
- Access control protects systems from unauthorized use; there are several different types:
- Physical access control
- Physical access control[5] is often overlooked, but it's an extremely important outer level of protection. Large organizations often have big computer rooms that are both bomb-proof and earthquake-proof, which is good. In many cases, however, pretty much everyone in the organization has access to these rooms, which makes it possible for anyone in the building to sabotage operations.
- System access control
- Only the people involved in the daily operation of your systems should have access to these systems. Those who are granted access should have only the amount of privilege required to do their jobs. For example, not everyone needs to be a member of the Administrator group.
- Network access control
- Network access to your systems needs to be restricted by a firewall system. A firewall system consists of a number of components that act in concert to enforce your network access policy; it's typically not just one single gateway with firewall software installed. The perimeter network (discussed later in this chapter) is a type of firewall system.
- Operation
- Once your system is up and running, you need to manage its operation in a careful and secure manner. System management includes:
- Auditing
- Watch your systems carefully. Set up an audit policy that keeps you informed of any access policy violations. Chapter 6, Auditing and Monitoring Your Perimeter Network, deals with the different aspects of setting up auditing on a Windows NT/2000 bastion host.
- Backups
- Make frequent backups. Always back up before and after changing the configuration of your systems. The flip side of backup is restore; you must attempt to restore your system from backups at regular intervals to make sure you'll be able to do so if there is a disaster. Chapter 5, Backing Up and Restoring Your Bastion Host, serves as an introduction to backing up and restoring bastion hosts.
- Log management
- Collect logs in real time on a separate secured logging host and carefully review this information. Chapter 6 suggests a strategy using syslog as a transport mechanism for log collection.
- Peer reviews
- Ask your colleagues or a third party to review your work periodically. See Chapter 7, Maintaining Your Perimeter Network, for details.
- Encryption
- Use encryption to secure communication and sensitive data stored on disk. You will find references to various types of encryption methods and algorithms throughout this book. The "Cryptography Basics" section later in this chapter provides a brief introduction.
It's important to understand that site security is a very big and complex subject and that this book's focus on the practical aspects of building and managing secure bastion hosts based on Windows NT/2000 is a very narrow aspect of site security.
Hardening the Bastion:
- A projecting part of a rampart or other fortification.
- A well-fortified position or area.
- Something regarded as a defensive stronghold.:
- How does the bastion host protect itself from attack?
- How does the bastion host protect the network behind it from attack?.
Configuring the Perimeter Network.
The perimeter network architecture
A perimeter network is an untrusted part of an enterprise network that resides on the outskirts of the private network. The perimeter network is often also referred to as the demilitarized zone, or DMZ, named after the region separating North Korea and South Korea. An example of a perimeter network is where the Internet connection and the web servers are located. A company might have several perimeter networks, as illustrated in Figure 1-2.
All external communication from the internal network has to pass the perimeter before it can reach an external host, and no communication is allowed directly from an external network to the internal network.
A good approach to building the perimeter network is to build it in compartments, so that the perimeter is able to protect itself and the internal network even if one compartment is compromised. This compartmentalization is illustrated in Figure 1-3.
Because each compartment has access control mechanisms, the farther in from the external network a host is placed, the better it is protected. It's good security practice to block as much traffic as possible in each compartment layer--I recommend that you take a default-deny stance regarding network traffic. With a default-deny stance, everything that isn't explicitly allowed is denied, in contrast to a default-allow stance, where everything that isn't explicitly denied is allowed. Consider the example in Figure 1-4.
In this example, if the web server is compromised, it's easy for an intruder to attack any service provided by the database server. This is because there is no network access control between these two servers.
On the other hand, in the topology shown in Figure 1-5, if the web server is compromised, the access control layer between the compartments will block unneeded traffic to the database system. As a result, the intruder may be able to attack the database process on the server, but not be able to attack anything else.
Components in the Perimeter
It takes a number of different components to build a perimeter network, and some architectures are quite complex. This section does not attempt to describe all of the issues or possible combinations. It simply introduces the components and explains how they interact so you will have enough background to be able to understand subsequent chapters.
- Routers
- Routers are the traffic police of the network. They decide what route a datagram should take at each router or "network intersection." Like the police, routers can also choose to stop certain types of traffic. Traffic is controlled by rules called router Access Control Lists (ACLs). Example 1-1 shows a router ACL for a Cisco router.
Example 1-1: Cisco IOS Router ACL Example
ip access-list extended example_access_list
permit tcp any 192.168.1.0 0.0.0.255 eq http
permit icmp any any
deny ip any any log
- A Cisco IOS ACL is applied from top to bottom. An incoming datagram is tested against each line in the ACL. This example allows HTTP from anywhere to the 192.168.1/24 network. It also allows any type of ICMP anywhere. All other datagrams[7] are blocked and logged.
- Using router ACLs in this manner provides us with a useful network access control mechanism in the perimeter. A router that implements access control in this manner is generally referred to as a screening router.
- Firewall gateways
- Certain components in the perimeter typically have firewall software installed, and these machines are referred to as firewall gateways.
- There are two common techniques that a firewall gateway can use. One method, shown in Figure 1-6, is to act as an application-level gateway; the gateway serves as a middleman that intercepts traffic at the application level, and it initiates a new connection to the target system on behalf of the client. Examples of application-level protocols are File Transfer Protocol (FTP), HyperText Transfer Protocol (HTTP), Simple Mail Transfer Protocol (SMTP), and Post Office Protocol (POP).
- The other technique, illustrated in Figure 1-7, is to inspect the traffic on the Internet Protocol (IP) level. This is called packet filtering. A more sophisticated form of packet filtering, called stateful inspection, is used by products such as Checkpoint's Firewall-1. A state-aware firewall gateway keeps track of the state of the connections that are going through it. If an outgoing HTTP request from a client is allowed through the gateway, the response to that request also has to be allowed through. The firewall software adds a temporary rule in its rulebase to allow the response from the destination web server to the client. The firewall gateway also understands some types of application data (HTTP, SMTP, FTP, etc.) in the IP datagrams, and for this reason, it may be able to make better security decisions than a screening router can.
- In theory, an application-level proxy can make more sophisticated decisions, but it's usually slower than inspecting the IP datagrams. As "inspection" technology gets more sophisticated (it's now becoming possible to keep track of the state of many application-level protocols), the gap between the two approaches lessens. Many firewall products provide both application-level proxies and IP-level inspection or filtering. These products are referred to as hybrids.
- Bastion hosts
- The bastion hosts are the application servers in the perimeter. A bastion host usually runs one specific piece of software, such as a mail gateway or some web server software. A bastion host has no unnecessary services running, and it is installed and configured in a highly secured manner, as described in Chapters and .
- Switches and hubs
- As with any other network, you need switches or hubs to build the network infrastructure in the perimeter. A network segment that uses a hub is a shared media, where all traffic is visible from all network stations (hosts). On the other hand, a switch connects the sender directly to the receiver for every Ethernet packet. This provides improved performance for unicast (one-to-one) traffic, but also some additional security. If one of the hosts on a network segment is compromised, an intruder may be able to install a network sniffer to spy on traffic on that segment to get information. However, if a switch is used, the intruder may not be able to see the traffic between other hosts.
- I recommend that you use "dumb" switches and hubs without management software if possible. If the switch or hub device has its own IP stack, it may be vulnerable to attacks, and for this reason, it will have to be secured in the same manner as your bastion hosts.
A perimeter network example
The best way to describe how all the components fit together is to present an example perimeter network design. The example network I describe in this section is very general and simplified; don't use it as a ready-to-run implementation blueprint.
What are the objectives of this design?
A design always has to meet some core objectives. These are usually determined by specific business requirements. Let's assume that our example company has the following needs:
- It must allow access to the web servers from the Internet.
- It must accept incoming mail.
- It must allow outbound web and FTP from the internal network.
- It must allow outgoing mail.
The example company must solve these business objectives with regard to two key network security needs:
- No direct traffic can be allowed between the Internet and the internal network.
- If one component in the perimeter is compromised, it should not result in a compromise of the entire perimeter or the internal network.
What's a possible solution to these problems and objectives?
The solution shown in Figure 1-8 meets all the objectives of this example and protects the perimeter both from external and internal threats. The solution implements a perimeter network with the web servers, a firewall gateway, a mail gateway, and an HTTP proxy server.
In this example, the following services are allowed:
- Only inbound HTTP to the web servers and inbound SMTP to the mail gateway are allowed from the Internet.
- The proxy server and mail gateway are allowed to do DNS queries (udp/53).
- The proxy is allowed outbound HTTP, HTTPS, and FTP.
- The mail gateway is allowed to send mail (SMTP) to the Internet and to relay incoming mail to the internal mail server.
- The internal mail server is allowed to relay outgoing mail to the mail gateway.
- The internal network is allowed to use the proxy server in the perimeter.
The screening routers protect the perimeter from the Internet and the internal network from the perimeter in case there is a problem with the firewall gateway. You'll notice that no direct traffic is allowed between the internal network and the Internet and vice versa.
The proxy and mail servers are placed on a different network from the web servers; doing so separates outgoing web surfing from published web services. In the future, the company might consider a separate Internet connection for outgoing web traffic to guarantee bandwidth to its public web servers.
This design has four separate security zones:
- Two zones between the firewall and the screening routers
- One zone for the web servers
- One zone for the mail gateway and proxy server
As a result, the perimeter is well compartmentalized; if one security zone is compromised, the others remain intact. Note that if the firewall gateway is compromised, multiple security zones are also compromised. However, the interior screening router still protects the internal network.
All the components in the perimeter must be hardened to a very high level. This implies removing all unneeded or unsecure services that are provided by default. An easy thing to do is to list the active network services with a command (
netstat
-anon most operating systems), and to scan and probe the host for available services to identify which services you need and which ones you can turn off or remove.
The Windows NT/2000 Architectures
This section provides a very basic summary of the architecture of Windows NT and Windows 2000 systems. You'll need at least this background information for understanding the instructions in subsequent chapters. For more detailed information, see a good Windows operating system book. I particularly recommend Inside Windows NT, Third Edition by James D. Murray (O'Reilly & Associates, 1999).
TIP:
In the discussion that follows, most of the details are the same for Windows NT and Windows 2000. If there is an architectural difference, I will note it.
Windows NT is a multithreaded, micro-kernel-based[8] operating system. The term micro-kernel implies that the kernel component is very small, and provides only basic functions such as thread dispatching and hardware exception handling. Hardware-specific code is kept in a separate layer called the Hardware Abstraction Layer (HAL). The HAL simplifies porting of the operating system to new processor architectures like the IA-64.
The core operating system code runs in privileged processor mode. This mode is also known as protected mode (when referring to the CPU), or kernel mode (when referring to a process or thread). Protected mode provides direct access to system memory and other hardware. Applications run in a nonprivileged processor mode known as user mode and have no direct hardware access. Applications have to use the system calls -- the API (Application Programming Interface) -- in the underlying operating system to perform tasks such as reading or writing to memory or to the screen.
The basic Windows NT architecture is shown in Figure 1-9.
Windows NT/2000 Subsystems and Services
Operating system services are kept in discrete subsystems, some running in user mode and others in kernel mode. There are several kernel mode subsystems in Windows NT. They provide NT's native functionality for user mode subsystems through ntdll.dll (running in user mode). The kernel mode subsystems make up the Windows NT Executive, and consist of the following:
- Object Manager
- The Windows NT architecture is not strictly object-oriented, but internal structures such as shared memory segments, processes, and threads are represented as objects to provide a uniform method for handling things like access control. The Object Manager creates, manages, and deletes Windows NT Executive objects. Objects are represented in a hierarchical namespace much like a filesystem.
- Process Manager
- Responsible for creating and terminating processes and threads using underlying kernel functions.
- Virtual Memory Manager
- Implements the virtual memory used to allocate a private address space to each process.
- I/O Manager
- Provides a device-independent I/O system to processes. It dispatches I/O requests to the appropriate device driver.
- Local Procedure Call (LPC) Facility
- Implements a fast, lightweight version of Remote Procedure Call (RPC) for communication between components within a computer.
- Security Reference Monitor (SRM)
- Enforces the access and audit policies in the system. The Security Reference Monitor provides access validation, privilege checking, and audit message generation at runtime for both user and kernel mode processes.[9]
- Window Manager and Graphical Device Interface (GDI)
- These components make up the kernel mode part of the Win32 subsystem. They handle user input and screen output. All of the Win32 subsystem originally ran in user mode; however, for performance reasons, a part of it was moved to kernel mode as of NT 4.0.
The subsystems running in user mode are called the environment subsystems. There are three environment subsystems:
- Win32 subsystem
- The part of the Win32 subsystem running in user mode. The Win32 subsystem is a required part of the operating system and is loaded as a part of the boot sequence. The subsystem consists of the Win32 API DLLs (kernel32.dll, user32.dll, gdi32.dll ) and the Win32 subsystem process (csrss.exe ).
- POSIX subsystem
- Provides support for POSIX.1 applications. It's an optional component that is loaded on demand.
- OS/2 1.x subsystem
- Provides support for OS/2 1.x console applications. It's an optional component that is loaded on demand.
TIP:
Windows NT also provides support for MS-DOS and 16-bit Windows 3.x applications through its Virtual DOS Machine. This is not a native NT subsystem. It's a Win32 application that emulates a DOS environment.
Windows NT Networking
The first version of Windows NT (Windows NT 3.1[10]) was released in 1993. It was positioned as a successor to the LAN Manager products from Microsoft and IBM. To interoperate and provide backward compatibility with these products, it had to support some established networking standards, such as NetBIOS and SMB. It's important you understand what these protocols are and how they are used in Windows NT. They still provide the foundation for most Windows NT network communication in both Windows NT 4.0 and Windows 2000.
NetBIOS
NetBIOS (Network Basic Input/Output System) is a standard for transmitting data between computers over the network. The NetBIOS specification was developed for IBM back in 1983 to allow network communication between applications. NetBIOS provides three key services:
- Name service
- Locates NetBIOS names on the network.
- Session service
- Provides a connection between two computers.
- Datagram service
- Provides a connectionless communication channel between computers.
The first implementations of NetBIOS didn't separate the software interface from the network protocol. Later on, the network-level part of the standard was named NetBEUI (NetBIOS Extended User Interface). The Windows NT version of NetBEUI is also referred to as NBF (NetBIOS Frame). Nowadays, NetBIOS can use transports other than the nonroutable[11] NetBEUI protocol, such as TCP/IP (NetBIOS over TCP/IP--NetBT) or IPX/SPX.
Server Message Block (SMB)
Remember that NetBIOS is merely a standard for finding resources and transmitting bits. A higher-level protocol is required on top of NetBIOS for it to be of any real use. Here's where SMB comes in. Server Message Block (SMB)[12] is a standard for sending commands and data. SMB is mostly used for file and print sharing, but it can also be used for Inter-Process Communication (IPC) to communicate with processes on other systems.
SMB over NetBIOS uses ports udp/137 (NetBIOS name service) and udp/138 (NetBIOS datagram service) or tcp/139 (NetBIOS session service). Windows 2000 includes support for running SMB without NetBIOS over tcp/445. This support is referred to as Direct Host.
NT networking architecture
The I/O Manager in the NT Executive is responsible for most I/O processing, including disk and network I/O. Figure 1-10 illustrates some of the networking components in the I/O Manager and shows how user mode services interact with these components.
Like all subsystems in the Executive, the I/O Manager exposes a number of APIs to user mode processes. These APIs include the following:
- Windows Sockets (Winsock)
- The Windows NT implementation of the widely used Sockets API. Applications that use Winsock include Internet Explorer, IIS, Telnet, and FTP.
- SMB Named Pipes
- One-way or duplex communications channels between the pipe server and one or more pipe clients.
- SMB Mailslots
- A simple IPC mechanism that can be used to send or receive small (less than 425 bytes) datagram broadcast messages.
- Remote Procedure Call (RPC)
- Microsoft's Remote Procedure Call (MS-RPC) provides a mechanism for using ordinary function calls to communicate with processes on another computer. Distributed Components Object Model (DCOM) components use MS-RPC.
- There are two ways of performing RPC communication between two hosts:
- MS-RPC over SMB
- Uses SMB-named pipes as transport for the RPC calls. Administrative tools such as Server Manager, User Manager, Performance Monitor, and Event Viewer all use MS-RPC over SMB to connect to remote hosts. Windows NT domains also rely on MS-RPC over SMB.
- MS-RPC using Windows Sockets
- Communication is established by using dynamically assigned high ports (>1023) and the RPC portmapper services tcp/135 and udp/135. This RPC method is often used by DCOM applications.[13]
- SMB filesystem drivers
- There are two components that enable SMB file sharing:
- SMB Redirector
- The redirector is a filesystem driver that communicates with the SMB server driver component on a remote system. The Workstation service uses the SMB redirector.
- SMB Server
- The Server filesystem driver and the Server service work for the connections requested by client-side redirectors, forwarding them to the appropriate local filesystem driver, such as NTFS.
- NetBIOS Interface API
- The NetBIOS interface API is provided primarily for existing applications that use IBM NetBIOS 3.0 and need to be ported to the Win32 API.
There are two boundary layers in the network architecture:
- Transport Driver Interface (TDI)
- The TDI provides developers with a protocol-independent network API for network services. Developers need only to program against the TDI to support all available network protocols.
- Network Driver Interface Specification (NDIS)
- The NDIS wrapper driver communicates with the network protocols. The wrapper driver provides a uniform interface between protocol drivers and NDIS device drivers.
Bindings enable communication between two components on adjacent layers in the protocol stack. For example, bindings can be configured to limit a service to one network protocol or to allow only a network protocol on one of the network adapters in the system.
In the example shown in Figure 1-11, the binding between the Server service and the NetBEUI protocol has been removed. This means the Server is not able to service requests from NetBEUI clients. TCP/IP is bound only to the NIC1 network interface card. IPX/SPX and NetBEUI are bound only to NIC2. As a result, the system will only use TCP/IP on NIC1, and both IPX/SPX and NetBEUI on NIC2.
Windows NT/2000 in the Perimeter Network
Features like discretionary access control, security auditing, and memory protection place the Windows NT core operating system on par (or better) with many Unix systems in terms of local host security. So why do many people claim that Windows is less secure than Unix?
The problem is not really Windows itself; rather it's the services and applications built on top of the operating system that are the weakest links.
The following sections describe some fundamental principles of secure system design, as well as examine how some of Windows NT/2000's services and applications stack up to these principles.
Least Privilege
A very important principle is that of least privilege. The least privilege philosophy dictates that an application should be designed to run only with the privilege level it needs to execute properly--and no more.
Consider the following question: what privilege level do you need to grant to a web server application? The simplified answer is that the application needs the right to read the data files it serves. Now, take a look at the Internet Information Server's (IIS) WWW service. By design, it has to run as Local System, the highest privilege level in Windows. IIS does run the actual worker threads with lower rights, but if an attacker manages to break IIS before the security context switch is made, he'll be able to do anything, including deleting filesystems, starting up a back door,[14] and so on--you get the idea!
Microsoft designed IIS in this way to be able to integrate the web server with the NT security architecture. There's not much specific security code in IIS; instead, it uses the same access control mechanisms as any other NT process would. The IIS authentication mechanisms use the NT account database. Access to individual files and directories is controlled by NTFS DACLs, just like on a file server. To achieve this level of functionality, IIS needs to be able to start a process or a thread in the security context of the connecting user,[15] and to call the required Win32 APIs it needs to run at very high privilege level.
It's unfortunate[16] there's no option to install IIS without this functionality, since most Internet web servers don't need user authentication, and because of this, could run IIS at a much lower privilege level.
Unfortunately, many Windows applications and services run as Local System. Some of them may not need that privilege level, but it's the default. Most Windows software vendors don't seem to be aware of the least privilege approach, or at least they don't reflect such awareness in their code. As a result, a bug or back door in these programs can compromise the security of your entire machine. If an application is exposed in the same way it is in a perimeter network, it needs to be designed with security in mind. In fact, the top priority in the perimeter is often not functionality or speed--it's security.
Any application that must run as Local System is potentially a major security hazard. It's a sitting duck waiting for a new buffer overflow attack (described in the sidebar later in this section) to happen. If you're running web servers like IIS, one possible solution is to place an application-level proxy in front of those servers. The proxy should be able to verify that any requests to the IIS WWW service conform to the HTTP standards. Any malformed HTTP requests will be blocked in the proxy. As a result, the web server is protected from many forms of attack. The disadvantage of having a reverse proxy as an additional layer of security is that it will impact performance to some extent. You also need to make sure that the proxy solution isn't a single point of failure if you want to build a highly available site.
The choice of proxy server product depends on your security needs. It may be sufficient to use an intelligent and configurable application-level (or hybrid) firewall. A better solution may be a combination of one or several dedicated firewalls and a reverse proxy server, as shown in Figure 1-12; such a configuration provides additional layers of security.
Separate Ports
Another important principle of secure design is to use one (or a few) fixed TCP/IP port (TCP or UDP) per application. It's good practice to use different ports for logging, viewing performance data, network logon, and so on. This separation makes it possible to implement granular network access control in the perimeter. It's often a good idea to design an application using this method.
So how does Windows behave on the network? Windows NT is terrible -- just about every service uses SMB over the NetBIOS session port (tcp/139). Windows 2000 is somewhat better. Logon authentication is Kerberos (tcp/88 and udp/88). There's also LDAP (tcp/389) to the Active Directory database. Everything else uses SMB just as in Windows NT 4.0 -- either over NetBIOS or over the new Direct Host protocol port (tcp/445).
Microsoft could have done a better job here. It's virtually impossible to have Windows servers that need to communicate using NetBIOS or Direct Host in different compartments in the perimeter.
If you plan to support a large number of Windows NT 4.0 or Windows 2000 servers, you may find that it's difficult to manage them as separate hosts. It is tricky to have both security and a management platform that scales up to hundreds of servers. It is tempting to use a centralized accounts database (using NT domains) and other NetBIOS-based tools like Event Viewer and Server Manager.
At very large sites (those with 50 or more NT servers in the perimeter), a common setup is to have dual-homed NT/2000 systems with NetBIOS/SMB unbound (deactivated) from the external network interface. The internal network interface is connected to a kind of management network so that the servers can be managed using the standard RPC-based tools in a domain environment. A remote console solution such as Terminal Server is often used to gain remote access to the management network. Figure 1-13 shows such a solution.
If you must run NetBIOS in this manner, you should be aware that it will be extremely difficult to build a well-compartmentalized perimeter. You can't set up network access control to allow only a certain type of NetBIOS traffic. As a result, you have to consider all hosts within an NT domain as one security zone. In such a configuration, if one server is broken into, there are no security mechanisms that can protect your domain controllers and other servers in the same administrative domain.
NetBIOS was not designed with security in mind and I recommend against using it in a perimeter. However, if you choose to implement NetBIOS anyway, I urge you to implement an extremely secure perimeter using multiple firewalls and a reverse proxy solution. Do not allow any direct connections from the Internet to your exposed services.
Cryptography Basics
You will find references to various types of encryption methods and algorithms throughout this book. This section is a very brief summary of some of the terms and algorithms relevant to discussions in later chapters. For more detailed information on this complex topic, consult a good cryptography reference.[17]
Public Key Cryptography
With public key cryptography, each party has a key-pair consisting of a private key and a public key. The public key is published while the private key is kept secret. Data encrypted with the public keys can only be decrypted using the private key and vice versa. Public key cryptography can also be used for authentication (through the use of digital signatures).
An important advantage of public key cryptography is that there are less complicated key distribution problems. All parties that want to be able to communicate using public key cryptography need to publish their public key in some kind of directory. When Alice wants to send an encrypted message to Bob, she uses Bob's public key to encrypt the data. Alice can also digitally sign a message by encrypting it with her private key. Bob can then decrypt the message using his private key and verify Alice's signature by decrypting using her public key.
The main disadvantage is that public key cryptography is slow compared to symmetric key cryptography.
Two common public key systems are:
- Rivest-Shamir-Adleman (RSA)
- The RSA cryptosystem is the most widely used public key cryptosystem. It's designed for doing both digital signatures and data encryption. RSA is used in Internet standards and drafts like IPSec, S/MIME, and TLS (the successor to SSL). RSA was patented in the U.S. until September 20, 2000.
- Digital Signature Algorithm (DSA)
- The Digital Signature Algorithm is an unpatented alternative to RSA. DSA was intended for performing digital signatures only, but it can be adapted for encryption as well. DSA is described in the Digital Signature Standard (DSS).[18] DSA was designed by the National Security Agency (NSA) based on the ElGamal algorithm, which is unpatented.
Symmetric Key Cryptography
With symmetric key cryptography, a single key is used for both encryption and decryption. Symmetric key cryptography is also known as secret key cryptography. The two most common methods that use symmetric key cryptography are stream ciphers and block ciphers, described in the following sections.
An important advantage of symmetric cryptography is that it's generally faster than public key cryptography. The main disadvantage is that it's hard to manage and distribute the keys to all parties in a secure manner.
Stream ciphers
Stream ciphers use a key stream that is the same length as the cleartext (unencrypted) data to produce the ciphertext (encrypted) data. The key stream can be independent of the data, or it can be generated based on it. Stream ciphers can be designed to be extremely fast. The most commonly used stream cipher is probably RC4 (Rivest Cipher 4), which is used in SSL-enabled browsers, for example.
Block ciphers
Block ciphers use a fixed-size encryption key to encrypt fixed blocks (generally 64 bits) of data. The following are some commonly used block ciphers:
- Data Encryption Standard (DES)
- The U.S. Government's Data Encryption Standard is a block cipher, originally created by IBM, that operates on 64-bit blocks using a 56-bit key. This version is known as Single DES. The latest revision of DES now incorporates the Triple DES (3-DES) algorithm. This is also referred to as the TDEA (Triple Data Encryption Algorithm). 3-DES is simply Single DES performed three times (encrypt, decrypt, encrypt) with three different keys (3 × 56-bit keys) on the same 64-bit block -- hence the name 3-DES. DES is described in FIPS 46-3, available from.
- Advanced Encryption Standard (AES)
- The Advanced Encryption Standard, currently under development, will eventually replace DES as the U.S. government encryption standard. The AES development effort is led by the U.S. National Institute for Standards and Technology (NIST). NIST initiated the AES effort in 1997 as a "call for algorithms" in which the cryptographic community was invited to submit AES candidates. On October 2, 2000, the Rijndael (pronounced Rhine-doll) algorithm was declared the winner. It will eventually become the official AES in 2001. Follow the progress at.
- Blowfish
- Bruce Schneier's Blowfish algorithm is another block cipher that operates on 64-bit blocks. Blowfish uses variable-length keys (32 to 448 bits) and offers very good performance. Blowfish is unpatented and free. You can get it from.
- International Data Encryption Algorithm (IDEA)
- The International Data Encryption Algorithm is yet another block cipher that operates on 64-bit blocks. Many consider IDEA the best block cipher algorithm to date. It is used in several products and protocols such as PGP and some SSH implementations. Ascom Systec Ltd. () holds the rights to the IDEA algorithm. The licensing cost is about $10 per end user.
Hash Algorithms
Hash algorithms provide a method for reducing variable-length data to a small fixed-length hash. Hashes are also called message digests or fingerprints. Hash algorithms are often used to produce message integrity checksums or to store passwords in a secure manner. A hash algorithm has the following requirements:
- It should not be possible to deduce the data from the hash.
- No sets of data should produce the same hash.
- It should not be possible to generate a given hash.
Two of the more common hash algorithms are:
- Message Digest (MD5)
- MD5 is available from RSA Data Security. Ronald Rivest (the "R" in RSA) published the MD5 hash algorithm in 1992 as RFC 1321. MD5 was an improvement over the previously published MD4 algorithm, which has some design weaknesses. MD5 produces a 128-bit hash from an input of any length.
- Secure Hash Algorithm (SHA-1)
- Available from the U.S. National Institute of Standards and Technology, SHA-1 is the NIST Secure Hash Standard.[19] It's considered to be the most secure hash algorithm today. It produces a 160-bit hash from a variable-length input.
1. This attack was described in detail on the BugTraq mailing list on May 4, 2000, in a message entitled "How we defaced."
2. PHP is a free server-side scripting language () similar to Microsoft's Active Server Pages (ASP).
3. Tom O'Donnell of the IEEE Ethics Committee describes gray-hats as "self-styled Robin Hoods who make it their business to expose security flaws in software in a very public way" ().
4. CERT-CC originally was established in response to the first major Internet security incident: the release of the Internet worm back in 1988.
5. Practical Unix and Internet Security, Second Edition, by Simson Garfinkel and Gene Spafford (O'Reilly, 1996) has an excellent chapter on physical security. You might consider checking it out even if you don't need the Unix details.
6. Available at.
7. Non-first TCP fragments are permitted. See RFC 1858, "Security Considerations for IP Fragment Filtering," for details.
8. The NT architecture is not a true micro-kernel architecture. Most true micro-kernel implementations have exhibited poor performance. Many compromises in the micro-kernel design have been made in the NT architecture to achieve better performance.
9. SRM doesn't check for object permissions if the calling thread or process is running in kernel mode. For performance reasons, SRM assumes that the caller has permission on all objects, since it is running in kernel mode and is therefore a part of the Trusted Computing Base (TCB).
10. It was dubbed Version 3.1 mainly because it reported version number 3.1 for backward compatibility with Windows 3.1 applications.
11. All hosts have to be on the same network segment to be able to communicate using NetBEUI.
12. Microsoft has renamed its SMB protocol implementation "CIFS" (Common Internet File System) in a marketing effort to make it an "open" protocol.
13. You can configure DCOM to use a specific port range on a per-application basis using the DCOM Configuration Properties application (dcomcnfg.exe).
14. An example of a back door is a shell process (like cmd.exe) that runs with Local System privilege and that can be accessed over the network.
15. Unauthenticated "anonymous" connection threads run as the IUSR_MACHINENAME account.
16. If you consider the security implications, you'll realize that an experienced Unix system administrator would never run a web server as root. It's just not a very bright thing to do!
17. I particularly recommend Bruce Schneier's Applied Cryptography, Second Edition ( John Wiley & Sons, 1996). You can also find a very readable summary of fundamental cryptography terms and algorithms in Appendix C of Building Internet Firewalls, Second Edition, referenced earlier in this book. There's a good online FAQ at RSA Labs as well ().
18. Digital Signature Standard, Federal Information Processing Standard (FIPS) 186-2 ().
19. The Secure Hash Standard, FIPS 180-1 ().
Back to: Securing Windows NT/2000 Servers for the Internet
© 2001, O'Reilly & Associates, Inc.
webmaster@oreilly.com | http://oreilly.com/catalog/securwinserv/chapter/ch01.html | crawl-002 | refinedweb | 7,734 | 54.73 |
Note to self: reader monad transformer
Note to self on constructing a monad transformer. In a way this follows on from the earlier post Applicatives compose, monads do not. Literate Haskell source for this post is available here:.
{-# LANGUAGE ScopedTypeVariables, InstanceSigs, MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-} module MyOwnReaderT where import Control.Monad hole = undefined data Hole = Hole
The Reader Monad
A
Reader is a data type that encapsulates an environment. The
runReader function takes an environment (a
Reader) and runs it, producing the result of type
a.
newtype Reader r a = Reader { runReader :: r -> a }
Note that with record syntax, the type of
runReader is actually
runReader :: Reader r a -> (r -> a)
Reader that increments its environment value, returning the same type:
reader1 :: Num r => Reader r r reader1 = Reader $ \r -> r + 1
Reader that converts its environment value into a string:
reader2 :: Show r => Reader r String reader2 = Reader $ \r -> "reader2: " ++ (show r)
“Run” the reader using
runReader:
ghci> runReader reader1 100 101 ghci> runReader reader2 100 "reader2: 100"
There’s nothing magic about
runReader; it is just taking the function out
of the data type. We can do it manually ourselves:
runReader' :: Reader r a -> (r -> a) runReader' (Reader f) = f
ghci> runReader' reader1 100 101
Next, make
Reader an instance of
Monad:
instance Monad (Reader r) where return :: a -> Reader r a return a = Reader $ \_ -> a (>>=) :: forall a b. Reader r a -> (a -> Reader r b) -> Reader r b m >>= k = Reader $ \r -> runReader (k (runReader m r :: a) :: Reader r b) r
The definition of
>>= is relatively easy to work out using hole driven development.
Example usage:
eg1 :: Reader Int String eg1 = Reader id >>= \e -> return $ "hey, " ++ show e
Or in the more readable
do notation:
eg1' :: Reader Int String eg1' = do e <- Reader id return $ "hey, " ++ show e
ghci> runReader eg1' 100 "hey, 100"
Note that we use
id to produce a
Reader that just passes its environment argument along as the output. See
readerAsk later for the equivalent situation which uses
return for
MonadReader.
Since
[] is an instance of
Monad we can also do things like this:
eg1'' :: Reader Int String eg1'' = do e <- Reader (return :: Int -> [] Int) return $ "hey, " ++ show e
ghci> runReader eg1'' 100 "hey, [100]"
Reader Transformer
We’d like to use the
Reader in conjunction with other monads, for example running
IO actions but
having access to the reader’s environment. To do this we create a transformer, which we’ll call
ReaderT:
newtype ReaderT r m a = ReaderT { runReaderT :: r -> m a }
The
r parameter is the reader environment as before,
m is the monad (for example
IO), and
a is the result type, as before. Again, note the actual type of
runReaderT:
runReaderT :: ReaderT r m a -> (r -> m a)
It takes a
ReaderT and provides us with a function that takes a reader environment of type
r and produces a monadic value. Following from the
Monad instance declaration for
Reader it is straightforward to write the definition for
ReaderT.
instance Monad m => Monad (ReaderT r m) where return a = ReaderT $ \r -> return a (>>=) :: forall a b. ReaderT r m a -> (a -> ReaderT r m b) -> ReaderT r m b m >>= k = ReaderT $ \r -> do let a' = runReaderT m r :: m a a'' <- a' runReaderT (k a'') r :: m b
With a
ReaderT as the outer monad, we would like to “lift” a monadic computation into the reader. A monadic action doesn’t know anything about the reader environment, so to lift the monadic value we just create a
ReaderT with a function that ignores the environment:
liftReaderT :: m a -> ReaderT r m a liftReaderT m = ReaderT (\_ -> m)
Example usage:
egLift :: ReaderT Int IO () egLift = do e <- ReaderT (return :: Int -> IO Int) -- This is similar to "Reader id" earlier. liftReaderT $ print "boo" liftReaderT $ print $ "value of e: " ++ show e
Note the type of
return on the first line of
egLift. In this context,
return :: a -> m a is the equivalent of
id :: a -> a from the earlier
Reader example.
ghci> runReaderT egLift 100 "boo" "value of e: 100"
More generally, let’s name the
ask function:
readerAsk :: (Monad m) => ReaderT r m r readerAsk = ReaderT return
If we want to modify the environment, we use
withReaderT which takes as its first parameter a function to modify the environment. Note that the result is of type
ReaderT r' m a so the function is of type
r' -> r which modifies the supplied reader of type
ReaderT r m a.
withReaderT :: (r' -> r) -> ReaderT r m a -> ReaderT r' m a withReaderT f rt = ReaderT $ (runReaderT rt) . f
Lastly, it is convenient to apply a function to the current environment.
readerReader :: Monad m => (r -> a) -> ReaderT r m a readerReader f = ReaderT $ \r -> return (f r)
This is almost the same as
readerAsk except that we create a reader that returns
f r instead of
f. In other words:
readerAsk' :: (Monad m) => ReaderT r m r readerAsk' = readerReader id
Finally, we collect the functions
readerAsk,
withReader, and
readerReader in a type class
MonadReader and give them more general names:
class (Monad m) => MonadReader r m | m -> r where -- Retrieve the monad environment. ask :: m r -- Execute the computation in the modified environment. local :: (r -> r) -> m a -> m a -- Retrieves a function of the current environment. reader :: (r -> a) -> m a
An instance declaration for our
ReaderT type:
instance Monad m => MonadReader r (ReaderT r m) where ask = readerAsk :: ReaderT r m r local = withReaderT :: (r -> r) -> ReaderT r m a -> ReaderT r m a reader = readerReader :: (r -> a) -> ReaderT r m a
Now we can write fairly succinct code as follows. Use the
IO monad as the inner monad in a
ReaderT, with an
Int environment and
String result type.
eg2 :: ReaderT Int IO String eg2 = do -- Get the reader environment. e <- ask :: ReaderT Int IO Int -- Run an IO action; we have to use liftReaderT since we are currently -- in the ReaderT monad, not the IO monad. liftReaderT $ print $ "I'm in the eg2 function and the environment is: " ++ (show e) -- Final return value, a string. return $ "returned value: " ++ show e
ghci> result <- runReaderT eg2 100 "I'm in the eg2 function and the environment is: 100" ghci> result "returned value: 100"
All of the above is available from Control.Monad.Reader and Control.Monad.Trans.
StateT, ReaderT, and ask
The State monad encapsulates a modifiable state. It has a transformer
StateT as one would expect. Yet we are able to call
ask inside a
StateT monad. Here is an example (the raw code is here):
import Control.Monad.Reader import Control.Monad.State inside0 :: ReaderT String IO Float inside0 = do e <- ask :: ReaderT String IO String liftIO $ putStrLn $ "inside0, e: " ++ show e return 1.23 inside1 :: StateT [Int] (ReaderT String IO) Float inside1 = do e <- ask :: StateT [Int] (ReaderT String IO) String s <- get :: StateT [Int] (ReaderT String IO) [Int] liftIO $ putStrLn $ "inside1, e: " ++ show e liftIO $ putStrLn $ "inside1, s: " ++ show s put [1, 1, 1] return 1.23 run0 :: IO () run0 = do let layer1 = runReaderT inside0 "reader environment, hi" result <- layer1 print $ "result: " ++ show result run1 :: IO () run1 = do let layer1 = runStateT inside1 [0] layer2 = runReaderT layer1 "reader environment, hi" (result, finalState) <- layer2 print $ "final state: " ++ show finalState print $ "result: " ++ show result
The function
inside0 has the
IO monad nested inside a
Reader, while
inside1 has a
StateT with the
ReaderT inside. Yet in both we can write
e <- ask.
Inspecting the types using ghcmod-vim we find that
-- in inside0 e <- ask :: ReaderT String IO String -- in inside1 e <- ask :: StateT [Int] (ReaderT String IO) String
so there must be a type class that provides the
ask function for
StateT.
First, inspect the type of
ask using ghci (here we are using the definitions from
Control.Monad.Reader and
Control.Monad.State, not the implementation in this file).
ghci> :t ask ask :: MonadReader r m => m r
So
StateT must have a
MonadReader instance. Confirm this with
:i:
ghci> :i StateT (lots of stuff) instance MonadReader r m => MonadReader r (StateT s m) -- Defined in `Control.Monad.Reader.Class' (lots of stuff)
Looking in Control.Monad.Reader.Class we find:
instance MonadReader r m => MonadReader r (Lazy.StateT s m) where ask = lift ask local = Lazy.mapStateT . local reader = lift . reader
The
lift function comes from Monad.Trans.Class,
and looking there we see:
class MonadTrans t where -- | Lift a computation from the argument monad to the constructed monad. lift :: Monad m => m a -> t m a
So actually we are after the
MonaTrans type class. Again looking at
:i on
StateT we see:
ghci> :i StateT instance MonadTrans (StateT s) (lots of stuff) -- Defined in `Control.Monad.Trans.State.Lazy' (lots of stuff)
So off we go to Control.Monad.Trans.State.Lazy where we finally get the answer:
instance MonadTrans (StateT s) where lift m = StateT $ \s -> do a <- m return (a, s)
This shows that for
StateT, the
lift function takes a monadic action and produces a state transformer that takes the current state, runs the action, and returns the result of the action along with the unmodified state. This makes sense in that the underlying action should not modify the state. (There are some laws that monad transformers must satisfy.)
If we did not have the
MonadTrans type class then we would have to embed the
ask call manually:
inside1' :: StateT [Int] (ReaderT String IO) Float inside1' = do e <- StateT $ \s -> do a <- ask return (a, s) s <- get :: StateT [Int] (ReaderT String IO) [Int] liftIO $ putStrLn $ "inside1, e: " ++ show e liftIO $ putStrLn $ "inside1, s: " ++ show s put [1, 1, 1] return 1.23
Obviously this is laborious and error-prone. In this case, Haskell’s type class system lets us implement a few classes so that
ask,
get,
put, etc, can be used seamlessly no matter which monad transformer we are in.
The downside is that reading Haskell code can be nontrivial. In our case we had to follow a trail through a few files to see where
ask was actually implemented, and finding the right definition relied on us being able to infer the correct types of certain sub-expressions.
Personally I am finding more and more that plain vim and ghci does not cut it for Haskell development, and something richer like ghcmod-vim is a real necessity. Shameless self plug: ghc-imported-from is also very useful :-) | https://carlo-hamalainen.net/2014/03/05/note-to-self-reader-monad-transformer/ | CC-MAIN-2020-40 | refinedweb | 1,740 | 55.07 |
J2ME Random Number
J2ME Random Number
In this application we are going to generate the random number using Random...;"+(f*100.0f)%100);
}
In the above source code
random number
random number Please
How do I generate a program that gives me random integer from 115 to 250? Using java.util.random.
Thank you very much!
Hi Friend,
Try the following code:
import java.util.*;
public final
random number
random number Sir could u please send me the code registration form of roseindia.net with image varification generate random number in java
How to generate random number in java
In this section you will learn how to generate random number in java. Java
API provide a random class in java.util.Random package
which generate random number within a range. The random
Download and Build from Source
Download and Build from Source
Shopping cart application developed using Struts 2.2.1 and MySQL can be
downloaded from... Of An Application
Download Source Code
Get Random Number
to describe you a code that helps you in
understanding to Get Random Number....
On Execution the code show you a set of Random number in the command prompt...
Get Random Number
J2ME
J2ME Hi,
what is the source code for Mortgage Calculator in J2ME for Developing Symbian
Random Number Generation - Java Beginners
Random Number Generation Can any one tell me about to generate integers that should be a 10 numbered integer. Should be between 100000000 to 9999999999. Core Application Hi friend,
Code to solve the problem sir, i need a source code for simple calculator along with buttons in mobile application
j2me
j2me hey i m doing a project
can i create message reader using j2me in nokia phone??
pls give me source code or hint
Generating Random Number
to the random number generator.
Here is the code of the program... Generating Random Number
... for
your application. Random Number is the frequently used to generate numbers
I'm getting an illgal start of expression error in my code for the public static boolean portion at the bottom... any ideas?
I'm getting an illgal start of expression error in my code for the public... = (int)(100 * Math.random()) + 1; //Generates random number
int userInt...;
}}}}}}
Here is a code of number game. We have modified
J2ME Books
and trends of the J2ME platform, the book uses the source code of several award... directives to allow you to write code such that J2ME Polish's build script can...;
Pro J2ME Polish: Open Source Wireless Java Tools Suite
How do I generate random number?
How do I generate random number? In my Java program there is a requirement of generating random numbers between two given numbers. How do I write code for generating the random number?
Thanks
Hi
J2ME
J2ME What is the source code for Mortgage Calculator. using text fields are home price,loan amount,down payments,down payment percent, Annual tax... in J2ME language for Symbian developing.
so please help me
random numbers
random numbers Hi I need some help with the code for the this program.
This program should randomly choose a number between 1 and 1000... the computer has randomly chosen the number 759.]
Guess my number! It's between 1 and 1000
J2ME
J2ME i wann source code to find out the difference between two dates... (ParseException e) {
e.printStackTrace();
}
}
}
i wann j2me code not java code my dear sirs/friends
Javascript random number - Design concepts & design patterns
Javascript random number Dear Sir,
I have a table with many... are retreived from database.I have to generate random numbers corresponding to every row.But problem is one constraint is there while generating random numbers.If digit number and display the length of longest incresing swries
using random number
using random number generate 10 number and display the length of longest incresing series
J2ME code - MobileApplications
J2ME code hi...
i'm facing problem while connecting J2ME code... ...
user enter name and pwd to J2ME code...j2me cl the servlet..and servlet... servlet???
tutorial given on site is not enough for me..i'm not getting
Generate random numbers in Java
= randomGenerator.nextInt(1000);
Following is the code to generate 10 random number between 0... to
generate desired random number in Java program?
In this tutorial I will teach you... class for generating the random number.
We are using - Java Beginners
random numbers Hello i need this code to be modified for me to display the random numbers, but not twice or more. I mean i need a number to be display once. This code allows some numbers to be displayed more than once.
Hi
J2ME Tutorial
.
J2ME Random Number
In this application we....
Source code of
'jad' and 'properties' file
Java... be fill with some colors and text. The following source code shows
how to create
PHP Random Number
PHP Generate Random Numbers:
A random number is becoming more useful.... To generate random number, PHP
provides rand() function. ...
rand() function could generate another random number as
follows:</b>
j2me
j2me hi, i'm working emulator in j2me language, for Symbian OS (Nokia) development.
then, what are the click events in this for developing the application.?
Thank you
understanding buttons :JSP random no program
"no is greater"
please help me to understand buttons .thank you
java code for random...; //The random number will be between 100 and 200
for(int i=0;i<10;){ //suppose...understanding buttons :JSP random no program I hav java random
random numbers
random numbers hi.. i am creating a website and on feedback form to authenticate user i want to generate a random number on label.if user types that number correctly in textbox then he is allowed to submit feedback otherwise
J2ME
J2ME Hi friends,
i have display the bar code image from Mysql database to web page i need to display that image in my J2ME application i want code in which when we input same data in midlet page ... than on ok button it will show in servlet page.. code that pass information to mobile application page to servlet page
PHP SQL Random
the records of table
'users'.
Table: users
Source Code... on the browser.
Output:
Download Source Code...
PHP SQL Random
Random Number |
J2ME Label |
J2ME KeyEvent |
J2ME Key Codes...
Map | Business Software
Services India
J2ME Tutorial Section
Java
Platform Micro Edition |
MIDlet Lifecycle J2ME
|
jad and properties file
MySQL random number
MySQL random number
You may fall in the condition when you want to create random number for your...
create a random number by the use of RAND() function of MySQL. There are two
Build and test application
Build and test application
Building and application using ant
At first...;!-- Normal build of application -->
<target name="compile".../classes"/>
</target>
<!-- Remove classes directory for clean build
How to build calander - Date Calendar
How to build calander My requirement is
When user is registering... {
}
/* a table cell that holds a date number (either blank or 1-31) */
.dpTD... #AAAAAA;
}
/* the date number table cell that the mouse pointer
Php Sql Random
from
table.
Table: users
Source Code of sql_random.php... Source Code
Output:
...Php Sql Random
This example illustrates how to fetch random data from database
Javascript random number - Design concepts & design patterns
Javascript random number Dear Sir,
I have a table with many... are retreived from database.I have to generate random numbers corresponding to every row.But problem is one constraint is there while generating random numbers.If
Eclipse Plunging-Build and Deploy
further build automation Best Practices like test automation, code coverage...
Eclipse Plunging-Build and Deploy
Mojo - Free Build to Release
OpenMake
java source code - Java Beginners
java source code write a program to read the value of n as total number of friend relatives to whom the person wants to call
Open Source e-commerce
with the source code freely available for alteration and customization. Using... code and J2EE best practices.
Open Source E... source PHP code allows modifying every aspect of the system to meet business
navigation system in j2me
navigation system in j2me how to load map image for offline navigation system?plz send the source code in j2me
open source help desk
modify their source code. For those reasons, they've gained popularity...Open Source Help Desk
Open Source Help Desk Software
As my help desk... of the major open source help desk software offerings. I?m not doing
Source code
Source code source code of html to create a user login page
java source code - Java Beginners
java source code hello Sir,
Im a beginner in java.im greatly confused, so plz send me the source code for the following concept:
Telephone... and phone number for N subscribers and perform the following operations :
1. Search
Java GUI to build a Student Registration Program
Java GUI to build a Student Registration Program Write a program... a course number, credit hours and a minimum and maximum enrollment. The
system... undergrad courses). I also made a list of 10 students.
I'm a little hesitant
Open Source DRM
and source code for DReaM, an open-source, "royalty-free digital rights management...Open Source DRM
SideSpace releases open source DRM solution
SideSpace Solutions released Media-S, an open-source DRM solution. Media-S is format
Open Source Directory
architecture includes source code for both directory client access and directory servers... unveiled the Red Hat Directory Server and simultaneous release of the source code... includes source code for both directory client access and directory servers. Open
source code
source code hellow!i am developing a web portal in which i need to set dialy,weekly,monthly reminers so please give me source code in jsp
source code
source code how to get the fields from one page to another page in struts by using JSTL
J2me notes - MobileApplications
will help you. The following link provide you whole running example with source code...J2me notes hi to all,
i am a final year m.c.a student.i want to learn j2me.please inform to me.
where i can have a j2me guide?
thank u
JavaScript array get elements at random
. Here is the full example code for printing the array
elements by the random... Sample Source Code...
JavaScript array get elements at random
source code
source code how to use nested for to print char in java language?
Hello Friend,
Try the following code:
class UseNestedLoops{
public static void main(String[] args){
char[][] letters = { {'A', 'B'}, {'C','D
problem with executing JSF file(Build failed)
problem with executing JSF file(Build failed) *while executing below code i am getting problem as
**init:
deps-module-jar:
deps-ear-jar:
deps...
Compiling 1 source file to /root/NetBeansProjects/JSFProject3/build/generated/classes
random numbers - Java Beginners
random numbers write a program to accept 50 numbers and display 5 numbers randomly Hi Friend,
Try the following code:
import java.util.*;
class RandomNumberExample {
static Random generator = new Random
Chapter 2. Design, build and test web components
Chapter 2. Design, build and test web...
any application code or JSP pages.
Dynamic: At runtime... application code. Finally, filters are independent of any platform or Servlet
Random numbers - Development process
Random numbers hi,
How to generate unique random numbers between range like(10 to 50) Hi friend,
class RandomNumber
{
public... to this number
int aNumber = (int) (Math.random() * 40 + 10);
//print
j2me code - Date Calendar
j2me code how to write a calendar program using alert
List in J2ME
as follow..
Source Code of CanvasListExample.java... List in J2ME
J2ME Canvas List Example will explain you, how to create list of items
Open Source Identity
a small project to build open source identity selectors for Microsoft?s... and code to "Project Higgins," an open-source on-line identity manager.
Higgins... currently used by companies. Novell hopes that the availability of source code
random color fill
random color fill Hi I am trying to create a randomly color filled oval but the outcome is a black filled oval this is the code: package...;
Random rcolor = new Random();
int r = rcolor.nextInt(255);
int g1
Open Source Build system written in Java
Open Source Code
number of items in those categories.
Java 2 source code...
Open Source Code
What is SOAP
SOAP is a protocol for exchanging... that the actual program code that the developer created, known as the source code
RANDOM ACCESS FILE CONCEPT
RANDOM ACCESS FILE CONCEPT Write a program to write the details of an employee to a file. Details such as year of
joining, department code, employee name and salary should be included. You must use
RandomAccessFile
Open Source Browser
, the name of the public release, only exists as C++ source code. You have... contains a subset of the early source code from Communicator 5.0. Therefore, it has... to standardize on a single Web browser, Nokia on Wednesday released the source code
PHP Random image, PHP Randomizing image
);
This line generates a random value not greater than number of files...PHP Random image
PHP Random image Tutorial
Ever wanted to know how to create the random gallery?
Well, here is the way you can do it:
<?php application
j2me application code for mobile tracking system using j2me
Generate array of random numbers
Generate array of random numbers
You can generate a random number either by using the Random class or by using the static method Math.random... then there is no need to create a new Random object for each new random number
Generating Random Numbers to Fill array. Java Beginner needing help!
Generating Random Numbers to Fill array. Java Beginner needing help! ... a program that produces random permutations of the numbers 1 to 10. eg... displayPermutedArray(){} // Repeat the selection of a number 10 times to populate
GUESS NUMBER - Java Beginners
GUESS NUMBER Create a guessing game that picks a random number...() {
super("Guess Number");
randomNumber = new Random().nextInt(100) + 1..., "CONGRATULATIONS! You got it!!",
"Random Number: " + randomNumber
Chapter 2. Design, build and test web components
for the build path on the Source page...
Chapter 2. Design, build and test web...;
Chapter 2. Design,
build and test web components
generate random numbers and display the largest
generate random numbers and display the largest Hi, I am using... creates an array and fills it with random ints, prints the contents... ArrayRandom{
public static void main(String args[]){
Random r = new Random
source code for the following question
source code for the following question source code for the fuzzy c-means
I got build failed when deploying enterprise application - EJB
I got build failed when deploying enterprise application I created...:\My Documents\NetBeansProjects\ProjectIT407-1\z1EnterpriseApplication3\build...\ProjectIT407-1\z1EnterpriseApplication3\build
post-compile:
compile:
pre-dist | http://www.roseindia.net/tutorialhelp/comment/89597 | CC-MAIN-2014-49 | refinedweb | 2,447 | 56.86 |
I post this on C too... Well, my program read all lines from (plain.txt) and save temporary every read strings line by line into another text called(all.txt), i made the md5sum hash on each line separately of (all.txt) and saving this hashes on calculating.txt... then delete the all.txt and calculating.txt, creating a new copy of calculating (hashes.txt)
I want to do this process one-way only with the command
with array or something without using files.
echo -n (read string line) | openssl md5
plain.txt a b c d e f g
#include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #define Plain "plain.txt" int main(){ FILE *fp; FILE *read_fp; FILE *read_tmp; int chars_read; char hash[1024] = "openssl dgst -md5 all.txt >> calculating.txt"; char buffer[1024]; char line[128]; if ((fp = fopen(Plain, "r")) == NULL){ perror (Plain); return (EXIT_FAILURE); } printf("\tCreating Hash Table. Please wait....\n" ); while(!feof(fp)) { fscanf(fp,"%s", &line); read_tmp = fopen("all.txt","w+"); fprintf(read_tmp,"%s", &line); fclose(read_tmp); read_fp = popen(hash,"r"); if (read_fp != NULL) { while ((chars_read = fread(buffer, sizeof(char), 1024 , read_fp)) > 0 ){ } pclose(read_fp); } } fclose(fp); system("sed '$d' calculating.txt > hashes.txt"); system("rm all.txt"); system("rm calculating.txt"); printf("Hashes Calculated Successfully... [OK!]\n"); return 0; } | https://www.daniweb.com/programming/software-development/threads/411878/openssl-command-with-c-help | CC-MAIN-2017-09 | refinedweb | 220 | 72.63 |
Member Since 5 Years Ago
2,575immck left a reply on Mailable: Non Numeric Value Encountered
Yeah no need for routes. URL cannot pass class instances! Controllers cannot receive class instances directly from a URL. Use Middleware to inspect a URL from a ROUTE and maybe construct a class instance and PASS it to the controller. Hence the word Middleware. Or if you are more adventurous your code Infer the Class and constructor data in the URL but really why?
Emails have separate URL links than webpages. Different mediums. Emails contains contain more static and/or time dependent data.
jimmck left a reply on Mailable: Non Numeric Value Encountered
jimmck left a reply on Mailable: Non Numeric Value Encountered
jimmck left a reply on How Can I Listen To The Db In Real Time?
Database triggers
jimmck left a reply on How Can I Convert Many Statement Mysql To Laravel Eloquent?
You could have done all of this in 1 SQL statement. Are you under the impression that Eloquent will do some magical transformation? It will not. Learn Eloquent and convert it. No one here knows or understands your data or your database structure. What was the purpose of this original SQL? You need to answer to that to convert into Eloquent or any other ORM.
jimmck left a reply on Need Help Understanding Public Functions
Well your not using $this if the function is part of the controller class. Jeff has great intro videos to basic concepts. Thats what this site EXCELS at.
jimmck left a reply on How To Handle Event Listeners In Single Page Application?
Use Vue. It makes managing events easy.
jimmck left a reply on Problem With Vhosts
@Viernes Hi Hmm... looked at Acrylic it forwards packets to a proxy server and routes back to local? No we don't what that. I assume you have local hub/router or wifi provider LOCAL to your PC? All of my machines are connected of DHCP LOCALLY and dnsmasq runs locally. I used to do this as you want on a Windows setup. Your running XAmpp which was my original Apache server. So each virtual host needed a hosts entry.
Can you please give me brief overview of your LOCAL Xamp setup: router setup... Or are you stricly one machine localhosting???
Searching for dnsmasq Windows equivalents and so far nothing. Are you running in a VM?
Update Just saw this. I loved Windows 7!
Unsure of if it works, but sound if there is hidden dnsmasq like services inside Windows networking code.
Laragon looks interesting per other post. I personally opt for more direct control of things, but if its local to your network in may solve your immediate issues.
jimmck left a reply on Problem With Vhosts
jimmck left a reply on Private Method Injection In A Trait
There is nothing to inject. Traits do not exist on their own. All of the enclosing objects is available to the trait.
jimmck left a reply on Private Method Injection In A Trait
Traits are shared methods/data added to a class. The class using a Trait still needs to be instantiated.
jimmck left a reply on Laravel - Large Database
@matteoEB S3 is a service provided for Amazon EC3 cloud infrastructure. The PHP League has a great library for managing the code.
$s3 = Aws\Laravel\AwsFacade::get('s3'); $result = $s3->putObject(array ('Bucket' => 'bucket-name', 'Key' => 'xxxxxx', 'Body' => 'Hi!!!!!',)); print $result['Expiration'] . "\n"; print $result['ServerSideEncryption'] . "\n"; print $result['ETag'] . "\n"; print $result['VersionId'] . "\n"; print $result['RequestId'] . "\n"; // Get the URL the object can be downloaded from print $result['ObjectURL'] . "\n";
jimmck left a reply on Getting Data Into Vue Component
You need to show your Blade file.
jimmck left a reply on VUE Js Sending Data As A Props
@amjadkhan896 HiWhen you mean hide? Do you mean the JavaScript source? In that case on non secure sites no. The browser view source shows all the code delivered to the browser. Specific kinds of data has to come from the server over HTTP. Then you can dynamically change your page, message components etc. Vue is Great for that! And then if you don't have anything monitoring HTPP traffic only the browser app knows. https connections are much more secure you can't see a lot of stuff in the browser anymore. There are plenty of examples of locking down apps. You need to be more specific in what your design is.
jimmck left a reply on VUE Js Sending Data As A Props
In older versions of Vue props were 2 way. So you send/get data with components. Since then props are strictly one (read only). I have always treated props as custom HTML attributes used to configure the Vue component. I use component methods to get/set data with a component. Of course you have to give unique Id to each component instance so can message it.
jimmck left a reply on Any “famous” Sites Built With Laravel?
Fully stocked with popcorn!
jimmck left a reply on Mixing Vue SPA With Laravel Routes
Yes. I only write SPA Vue apps. Post messages to specific Laravel routes. I use JSON for the message protocol.
jimmck left a reply on LARAVEL OR PHP VERSION ISSUE !!
MySQL is not installed for one.
jimmck left a reply on Union/Join/Merge Table To Get The Result
@ravipw1801 Hi again. Do you know how to join tables in a database? There is no magic Eloquent solution. If you don't understand SQL you will not be able to solve the problem. You have NOT listed your Table schema's. There is no way to answer your question, only you understand the actual structure of the data.
jimmck left a reply on Union/Join/Merge Table To Get The Result
If a user_id can post either a business or social type you can join on that. You may need a mapping table to help match different business/social relationships (Metadata).
jimmck left a reply on Can't Connect To Mysql
Make sure access to MySQL is allowed for localhost.
Latest MongoDB releases as well.
jimmck left a reply on Putting Model Data Into More Than One Tables
jimmck left a reply on Putting Model Data Into More Than One Tables
jimmck left a reply on Can't Turn An Object Into An Array.
This object has private, protected or public data members only a constructor which takes an array and a method to iterate the array.
jimmck left a reply on Slow MySQL Query With Laravel Eloquent
@rafito Your query is doing a count and checking if 2 other selects have any rows? Since I don't know your data sets why are you doing the exists at all? Either the count result will be zero or > 0. The 2 exist selects seem to filter a result set? What is the main driving table in relation to these 2 exist sub-queries? Just creating indexes to speed up a query can hurt the overall performance of your database. Proper indexes will help the optimizer limit the table scan, too many indexes can force a full table scan. Do SQL Explain plan on this query to see what the optimizer will do.
jimmck left a reply on Laravel 5.2 -> Laravel 5.6 Framework Upgrade
@joshuabedford I use many libraries from the collective and they run fine in 7.1. Main issues I have is PHP code written for 4.x or early 5. Code written in a less (OOP) style in older PHP naming conventions will generate many warnings and will fail silently in certain situations (like pass by ref vs. pass by value) and packages not using Use causing namespace collisions.
jimmck left a reply on MCrypt Deprecation Warning Breaks File Upload - PHP7.1 MCrypt Laravel 5.2
@joshuabedford Glad you got it going. The "Composer Fire Dance" is very important to understand. When I first started using this it was frustrating and seemed stupid. Learning the tool saved time, help find problems and fix them. You should do the upgrade to 5.6 yourself to learn the Laravel environment. What are your deprecated features you depend on (Laravel deprecated they die hard and FAST)? If you are using 7.13 already good. Otherwise you have PHP remediation to do in order to move PHP 7.13.
jimmck left a reply on MCrypt Deprecation Warning Breaks File Upload - PHP7.1 MCrypt Laravel 5.2
@joshuabedford You cannot use mcrypt. A link in the article I posted when to another report. Did you read that? What is the OpenSSL version in your installation. I had many such incidents when moving to 7.x You have look at the code and the 7.x release notes and mitigate it.
There are no magic solutions.
Dont publish the whole stack trace, the first 25 lines will work. What versioin of phpspec are you using same with OpenSSL.
jimmck left a reply on Extending A Vendor Package
Well you can fork it. Put it into your own repository and reference that instance in your composer.json. Remove the original package.
"repositories": [ { "type": "vcs", "url": "" }
jimmck left a reply on Setting Up The Command Line In PHPStorm / Windows / Homestead
If things don't seem synced, remember to 'Synchronize your project after updates.
Right click on the top of the project tree in the project pane on the left side to get menu and select Synchronize name.
jimmck left a reply on Phpstorm Command Line Tools And Vagrant / Homestead(SSH)
If things don't seem synced, remember to 'Synchronize your project after updates.
Right click on the top of the project tree in the project pane on the left side to get menu and select Synchronize name.
jimmck left a reply on Adding 0.000005 To 0.000005?
@13en Are you trying to update all of the rows in your DB where the cost is > .0000005 + .000005 ? Using a formula as a part of a where clause? My initial thought was/is can't work. But apparently in MySQL there is way. Which looking at the solution with an alias and HAVING seems interesting. Note I have not tried this yet, going to to so as its interesting. Remember Eloquent is an ORM not an extension to SQL. All Eloquent code turns into SQL and may further process the returned result sets. Of course any searches apply to result sets. But interesting question! I will be check this further. Good Luck.
Here is search URL
jimmck left a reply on Will Laravel Have A Official Implementation Of Websockets (real-time)?
Not sure what you mean by official Laravel. You can many things.
jimmck left a reply on How To Render A Component When You Ajax The Html?
@check202 Also check out Sue Drasner's excellent series on Vue.
jimmck left a reply on How To Render A Component When You Ajax The Html?
jimmck left a reply on How To Mix Multiple Js In One?
Jeff has a great Free video series on Webpack and laravel mix.
jimmck left a reply on Composer Help
jimmck left a reply on Composer Help
Lookup the package on packagist.org and follow the install instructions. If there is no install for it don't put in the vendor directory.
jimmck left a reply on Adding A Space....
In sql
select first_name || ' ' || last_name as name ...
Double Pipe
||
Is the ANSI standard for concatenation in SQL.
jimmck left a reply on Laravel Frequently Showing 'Undefined Variable: _SERVER'
Are you all working in the same shared laravel directory? I assume you are running one actual server instance not 4 off the shared directory?
jimmck left a reply on How Can I CONCATENATE.
In SQL || "Pipe Pipe" concats separate DB columns.
select first_name || last_name as Name, age, city ...
jimmck left a reply on Pi (π) Button
Prime number sieve function?
jimmck left a reply on Check For Duplicate Entry And Skip During Import?
As @Snapey is asking, How many records to import? The database will be do this check for you with the constraint violation on import as shown (When fail next record from input is read). But as the master table table grows the time to insert will increase as each insert will take time to scan THE constraints. You can of course maintain an array of inserted records from the source and have the loader check this array before insert. Shorter list to check and in memory.
jimmck left a reply on Change Imported File Encoding In Laravel
You cannot just change the encoding of a whole file. You have to parse the content. And Excel files are a Binary format you cannot try to convert a binary file like this. There is no "magic" way to do this.
jimmck left a reply on Combine Two Tables Into One Result Set. Merge/append/join
@patrykszady Can you list the 2 table columns? If you want one result set you will need to join the 2 tables. Eloquent ORM will not solve this problem efficiently you will end up passing in a raw query. A SQL query will do the merge/append/join that you require that is what SQL is for. Are you using MySQL? This is probably a great use off a Group By with Rollup. You will get a result set with expected results. The ORM will be break this up into many queries and then attempt to merge data or worse leave you with a bunch on collections to manually combine. I know of only one reader of this forum who may be able to show an Eloquent way, but I have not seen him in a long time.
jimmck left a reply on Combine Two Tables Into One Result Set. Merge/append/join
Hi, What are the columns for each table ? Is expense_splits.expense_id related to expenses.id meaning the splits table has many instances? What is the purpose for each table?
jimmck started a new conversation Fractional Units CSS GRIDS Video Is Not Free?
In the CSS Grids series Fractional Units is not free? The others can be viewed?
jimmck left a reply on Vue Refs
$refs point to Vue components. clockpicker is dependent on JQuery. If you want to port it you have to make it an actual Vue component. Or just use JQuery in your Vue app, its easily done. But JQuery components will not show up in your $refs array unless it is wrapped into Vue component. | https://laracasts.com/@jimmck | CC-MAIN-2019-39 | refinedweb | 2,425 | 76.52 |
On Thu, 7 Oct 2010, Anthony Liguori wrote: > On 10/07/2010 04:49 PM, Yehuda Sadeh Weinraub wrote: > > On Thu, Oct 7, 2010 at 2:04 PM, Anthony Liguori<address@hidden> > > wrote: > > > > > On 10/07/2010 03:47 PM, Yehuda Sadeh Weinraub wrote: > > > > > > > > How is that possible? Are the callbacks delivered in the context of a > > > > > different thread? If so, don't you need locking? > > > > > > > > > > > > > > Not sure I'm completely following you. The callbacks are delivered in > > > > the context of a different thread, but won't run concurrently. > > > > > > > Concurrently to what? How do you prevent them from running concurrently > > > with qemu? > > > > > There are two types of callbacks. The first is for rados aio > > completions, and the second one is the one added later for the fd glue > > layer. > > > > This is a bad architecture for something like qemu. You could create a > pipe and use the pipe to signal to qemu. Same principle as eventfd. > Ideally, you would do this in the library itself. I'm sorry, I'm having a hard time understanding what it is you're objecting to, or what you would prefer, as there are two different things we're talking about here (callbacks and fd glue/pipes). (Please bear with me as I am not a qemu expert!) The first is the aio completion. You said a few messages back: > It looks like you just use the eventfd to signal aio completion > callbacks. A better way to do this would be to schedule a bottom half. This is what we're doing. The librados makes a callback to rbd.c's rbd_finish_aiocb(), which updates some internal rbd accounting and then calls qemu_bh_schedule(). Is that part right? The second part is an fd (currently created via eventfd(), but I don't think it matters where it comes from) that was later added because qemu_aio_flush() wouldn't trigger when our aio's completed (and scheduled the bottom halves). This was proposed by Simone Gotti, who had problems with live migration: Apparently calling the bottom half isn't sufficient to wake up a blocked qemu_aio_flush()? His solution was to create an eventfd() fd, write a word to it in the aio completion callback (before we schedule the bh), and add the necessary callbacks to make qemu_aio_flush() behave. Is the problem simply that we should be using pipe(2) instead of eventfd(2)? So far I've heard that we should be scheduling the bottom halves (we are), and we should be using a pipe to signal qemu (we're using an fd created by eventfd(2)). Thanks, sage > > Regards, > > Anthony Liguori > > > The first callback, called by librados whenever aio completes, runs in > > the context of a single librados thread: > > > > +static void rbd_finish_aiocb(rados_completion_t c, RADOSCB *rcb) > > +{ > > + RBDAIOCB *acb = rcb->acb; > > rcb is per a single aio. Was created before and will be destroyed > > here, whereas acb is shared between a few aios, however, it was > > generated before the first aio was created. > > > > + int64_t r; > > + uint64_t buf = 1; > > + int i; > > + > > + acb->aiocnt--; > > > > acb->aiocnt has been set before initiating all the aios, so it's ok to > > touch it now. Same goes to all acb fields. > > > > + r = rados_aio_get_return_value(c); > > + rados_aio_release(c); > > + if (acb->write) { > > + if (r< 0) { > > + acb->ret = r; > > + acb->error = 1; > > + } else if (!acb->error) { > > + acb->ret += rcb->segsize; > > + } > > + } else { > > + if (r == -ENOENT) { > > + memset(rcb->buf, 0, rcb->segsize); > > + if (!acb->error) { > > + acb->ret += rcb->segsize; > > + } > > + } else if (r< 0) { > > + acb->ret = r; > > + acb->error = 1; > > + } else if (r< rcb->segsize) { > > + memset(rcb->buf + r, 0, rcb->segsize - r); > > + if (!acb->error) { > > + acb->ret += rcb->segsize; > > + } > > + } else if (!acb->error) { > > + acb->ret += r; > > + } > > + } > > + if (write(acb->s->efd,&buf, sizeof(buf))< 0) > > This will wake up the io_read() > > > > + error_report("failed writing to acb->s->efd\n"); > > + qemu_free(rcb); > > + i = 0; > > + if (!acb->aiocnt&& acb->bh) { > > + qemu_bh_schedule(acb->bh); > > This is the only qemu related call in here, seems safe to call it. > > > > + } > > +} > > > > The scheduled bh function will be called only after all aios that > > relate to this specific aio set are done, so the following seems ok, > > as there's no more acb references. > > +static void rbd_aio_bh_cb(void *opaque) > > +{ > > + RBDAIOCB *acb = opaque; > > + uint64_t buf = 1; > > + > > + if (!acb->write) { > > + qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size); > > + } > > + qemu_vfree(acb->bounce); > > + acb->common.cb(acb->common.opaque, (acb->ret> 0 ? 0 : acb->ret)); > > + qemu_bh_delete(acb->bh); > > + acb->bh = NULL; > > + > > + if (write(acb->s->efd,&buf, sizeof(buf))< 0) > > + error_report("failed writing to acb->s->efd\n"); > > + qemu_aio_release(acb); > > +} > > > > Now, the second ones are the io_read(), in which we have our glue fd. > > We send uint64 per each completed io > > > > +static void rbd_aio_completion_cb(void *opaque) > > +{ > > + BDRVRBDState *s = opaque; > > + > > + uint64_t val; > > + ssize_t ret; > > + > > + do { > > + if ((ret = read(s->efd,&val, sizeof(val)))> 0) { > > + s->qemu_aio_count -= val; > > There is an issue here with s->qemu_aio_count which needs to be > > protected by a mutex. Other than that, it just reads from s->efd. > > > > + } > > + } while (ret< 0&& errno == EINTR); > > + > > + return; > > +} > > + > > +static int rbd_aio_flush_cb(void *opaque) > > +{ > > + BDRVRBDState *s = opaque; > > + > > + return (s->qemu_aio_count> 0); > > Same here as with the previous one, needs a mutex around s->qemu_aio_count. > > > > +} > > > > > > > If you saw lock ups, I bet that's what it was from. > > > > > > > > As I explained before, before introducing the fd glue layer, the lack > > of fd associated with our block device caused that there was no way > > for qemu to check whether all aios were flushed or not, which didn't > > work well when doing migration/savevm. > > > > Thanks, > > Yehuda > > > > -- > To unsubscribe from this list: send the line "unsubscribe ceph-devel" in > the body of a message to address@hidden > More majordomo info at > > | http://lists.gnu.org/archive/html/qemu-devel/2010-10/msg00386.html | CC-MAIN-2016-50 | refinedweb | 935 | 62.68 |
Pascal’s triangle is a nice shape formed by the arrangement of numbers. Each number is generated by taking the sum of the two numbers above it. The outside edges of this triangle are always 1. The triangle is as shown below.
Briefly explaining the triangle, the first line is 1. The line following has 2 ones. This is the second line.
The third line is
1 2 1 which is formed by taking sum of the ones in the previous line. Similarly, the forth line is formed by sum of 1 and 2 in an alternate pattern and so on.
Coding Pascal’s Triangle in Python
Let’s begin by creating the
PascalTriangle Function.
In this function, we will initialize the top row first, using the
trow variable. We also initialize variable y=0. Now we will use a for loop to run the code for
n iterations.
Inside the for loop we will print the list initialized by
trow variable. Now we will add the left and right elements of the trow. Along with that, we’ve used the zip function here. The function is shown below.
def PascalTriangle(n): trow = [1] y = [0] for x in range(n): print(trow) trow=[left+right for left,right in zip(trow+y, y+trow)] return n>=1
Now just give a function call with parameter stating number of rows needed. It is as shown below.
PascalTriangle(6)
Output of the code is as shown below:
[1] [1, 1] [1, 2, 1] [1, 3, 3, 1] [1, 4, 6, 4, 1] [1, 5, 10, 10, 5, 1]
Conclusion
This comes to the end of our tutorial on the creation of a Pascal’s triangle using Python. Try out this code and let us know your feedback in the comment section below. | https://www.askpython.com/python/examples/pascals-triangle-using-python | CC-MAIN-2021-10 | refinedweb | 301 | 74.69 |
IN ADDITION TO THE major overhaul in the structure and architecture of the language, ActionScript 3 introduced some exciting new features that make ActionScript development much more powerful. This chapter covers completely new features that are built into the language, including event bubbling, label statements, namespaces, and animating with external XML.
If there were not already enough reasons in this book to make the switch, this chapter should be pretty convincing.
As covered earlier, the event-handling architecture in AS3 is a far cry from AS2’s. But there’s more: event bubbling is built into the event architecture, making it easier than ever to dispatch an event from a DisplayObject ...
No credit card required | https://www.safaribooksonline.com/library/view/the-actionscripttm-30/9780321591111/ch14.html | CC-MAIN-2018-26 | refinedweb | 115 | 52.49 |
We are pleased to announce GNU Guile release 2.0.9, the next maintenance release for the 2.0.x stable series. This release contains 347 commits by 15 people over 4 months.: (7.1MB) (4.4MB) Here are the GPG detached signatures[*]: Use a mirror for higher download bandwidth: Here are the MD5 and SHA1 checksums: 531839c3fe887382ca9d4774db544d34 guile-2.0.9.tar.gz a69b575d4a633bdd9118f3a4a1e97766 guile-2.0.9.tar.xz fc5d770e8b1d364b2f222a8f8c96ccf740b2956f guile-2.0.9.tar.gz a2275c23c4a03e8dbd5e500c47af694e14d2365b guile-2.0.9.tar.xz [*] Use a .sig file to verify that the corresponding file (without the .sig suffix) is intact. First, be sure to download both the .sig file and the corresponding tarball. Then, run a command like this: gpg --verify guile-2.0.13.1 Libtool 2.4.2 Gnulib v0.0-7865-ga828bb2 Makeinfo 5.1 This release provides new features, many bug fixes, and performance improvements. Here are the highlights, taken from the `NEWS' file: Changes in 2.0.9 (since 2.0.7): Note: 2.0.8 was a brown paper bag release that was never announced, but some mirrors may have picked it up. Please do not use it. * Notable changes ** New keyword arguments for procedures that open files The following procedures that open files now support keyword arguments to request binary I/O or to specify the character encoding for text files: `open-file', `open-input-file', `open-output-file', `call-with-input-file', `call-with-output-file', `with-input-from-file', `with-output-to-file', and `with-error-to-file'. It is also now possible to specify whether Guile should scan files for Emacs-style coding declarations. This scan was done by default in versions 2.0.0 through 2.0.7, but now must be explicitly requested. See "File Ports" in the manual for details. ** Rewritten guile.m4 The `guile.m4' autoconf macros have been rewritten to use `guild' and `pkg-config' instead of the deprecated `guile-config' (which itself calls pkg-config). There is also a new macro, `GUILE_PKG', which allows packages to select the version of Guile that they want to compile against. See "Autoconf Macros" in the manual, for more information. ** Better Windows support Guile now correctly identifies absolute paths on Windows (MinGW), and creates files on that platform according to its path conventions. See "File System" in the manual, for all details. In addition, the new Gnulib imports provide `select' and `poll' on Windows builds. As an incompatible change, systems that are missing <sys/select.h> were previously provided a public `scm_std_select' C function that defined a version of `select', but unhappily it also provided its own incompatible definitions for FD_SET, FD_ZERO, and other system interfaces. Guile should not be setting these macros in public API, so this interface was removed on those plaforms (basically only MinGW). ** Numerics improvements `number->string' now reliably outputs enough digits to produce the same number when read back in. Previously, it mishandled subnormal numbers (printing them as "#.#"), and failed to distinguish between some distinct inexact numbers, e.g. 1.0 and (+ 1.0 (expt 2.0 -52)). These problems had far-reaching implications, since the compiler uses `number->string' to serialize numeric constants into .go files. `sqrt' now produces exact rational results when possible, and handles very large or very small numbers more robustly. A number (ahem) of operations involving exact rationals have been optimized, most notably `integer-expt' and `expt'. `exact->inexact' now performs correct IEEE rounding. ** New optimizations There were a number of improvements to the partial evaluator, allowing complete reduction of forms such as: ((let ((_ 10)) (lambda () _))) ((lambda _ _)) (apply (lambda _ _) 1 2 3 '(4)) (call-with-values (lambda () (values 1 2)) (lambda _ _)) `string-join' now handles huge lists efficiently. `get-bytevector-some' now uses buffered input, which is much faster. Finally, `array-ref', `array-set!' on arrays of rank 1 or 2 is now faster, because it avoids building a rest list. Similarly, the one-argument case of `array-for-each' and `array-map!' has been optimized, and `array-copy!' and `array-fill!' are faster. ** `peek-char' no longer consumes EOF As required by the R5RS, if `peek-char' returns EOF, then the next read will also return EOF. Previously `peek-char' would consume the EOF. This makes a difference for terminal devices where it is possible to read past an EOF. ** Gnulib update Guile's copy of Gnulib was updated to v0.0-7865-ga828bb2. The following modules were imported from Gnulib: select, times, pipe-posix, fstat, getlogin, poll, and c-strcase. ** `include' resolves relative file names relative to including file Given a relative file name, `include' will look for it relative to the directory of the including file. This harmonizes the behavior of `include' with that of `load'. ** SLIB compatibility restored Guile 2.0.8 is now compatible with SLIB. You will have to use a development version of SLIB, however, until a new version of SLIB is released. ** Better ,trace REPL command Sometimes the ,trace output for nested function calls could overflow the terminal width, which wasn't useful. Now there is a limit to the amount of space the prefix will take. See the documentation for ",trace" for more information. ** Better docstring syntax supported for `case-lambda' Docstrings can now be placed immediately after the `case-lambda' or `case-lambda*' keyword. See "Case-lambda" in the manual. ** Improved handling of Unicode byte order marks See "BOM Handling" in the manual for details. ** Update predefined character sets to Unicode 6.2 ** GMP 4.2 or later required Guile used to require GMP at least version 4.1 (released in May 2002), and now requires at least version 4.2 (released in March 2006). * Manual updates ** Better SXML documentation The documentation for SXML modules was much improved, though there is still far to go. See "SXML" in manual. ** Style updates Use of "iff" was replaced with standard English. Keyword arguments are now documented consistently, along with their default values. ** An end to the generated-documentation experiment When Guile 2.0 imported some modules from Guile-Lib, they came with a system that generated documentation from docstrings and module commentaries. This produced terrible documentation. We finally bit the bullet and incorporated these modules into the main text, and will be improving them manually over time, as is the case with SXML. Help is appreciated. ** New documentation There is now documentation for `scm_array_type', and `scm_array_ref', as well as for the new `array-length' / 'scm_c_array_length' / `scm_array_length' functions. `array-in-bounds?' has better documentation as well. The `program-arguments-alist' and `program-lambda-list' functions are now documented, as well as `and=>', `exit', and `quit'. The (system repl server) module is now documented (see REPL Servers). Finally, the GOOPS class hierarchy diagram has been regenerated for the web and print output formats. * New deprecations ** Deprecate generalized vector interface The generalized vector interface, introduced in 1.8.0, is simply a redundant, verbose interface to arrays of rank 1. `array-ref' and similar functions are entirely sufficient. Thus, `scm_generalized_vector_p', `scm_generalized_vector_length', `scm_generalized_vector_ref', `scm_generalized_vector_set_x', and `scm_generalized_vector_to_list' are now deprecated. ** Deprecate SCM_CHAR_CODE_LIMIT and char-code-limit These constants were defined to 256, which is not the highest codepoint supported by Guile. Given that they were useless and incorrect, they have been deprecated. ** Deprecate `http-get*' The new `#:streaming?' argument to `http-get' subsumes the functionality of `http-get*' (introduced in 2.0.7). Also, the `#:extra-headers' argument is deprecated in favor of `#:headers'. ** Deprecate (ice-9 mapping) This module, present in Guile since 1996 but never used or documented, has never worked in Guile 2.0. It has now been deprecated and will be removed in Guile 2.2. ** Deprecate undocumented array-related C functions These are `scm_array_fill_int', `scm_ra_eqp', `scm_ra_lessp', `scm_ra_leqp', `scm_ra_grp', `scm_ra_greqp', `scm_ra_sum', `scm_ra_product', `scm_ra_difference', `scm_ra_divide', and `scm_array_identity'. * New interfaces ** SRFI-41 Streams See "SRFI-41" in the manual. ** SRFI-45 exports `promise?' SRFI-45 now exports a `promise?' procedure that works with its promises. Also, its promises now print more nicely. ** New HTTP client procedures See "Web Client" for documentation on the new `http-head', `http-post', `http-put', `http-delete', `http-trace', and `http-options' procedures, and also for more options to `http-get'. ** Much more capable `xml->sxml' See "Reading and Writing XML" for information on how the `xml->sxml' parser deals with namespaces, processed entities, doctypes, and literal strings. Incidentally, `current-ssax-error-port' is now a parameter object. ** New procedures for converting strings to and from bytevectors See "Representing Strings as Bytes" for documention on the new `(ice-9 iconv)' module and its `bytevector->string' and `string->bytevector' procedures. ** Escape continuations with `call/ec' and `let/ec' See "Prompt Primitives". ** New procedures to read all characters from a port See "Line/Delimited" in the manual for documentation on `read-string' and `read-string!'. ** New procedure `sendfile' See "File System". ** New procedure `unget-bytevector' See "R6RS Binary Input". ** New C helper: `scm_c_bind_keyword_arguments' See "Keyword Procedures". ** New command-line arguments: `--language' and `-C' See "Command-line Options" in the manual. ** New environment variables: `GUILE_STACK_SIZE', `GUILE_INSTALL_LOCALE' See "Environment Variables". ** New procedures for dealing with file names See "File System" for documentation on `system-file-name-convention', `file-name-separator?', `absolute-file-name?', and `file-name-separator-string'. ** `array-length', an array's first dimension See "Array Procedures". ** `hash-count', for hash tables See "Hash Tables". ** `round-ash', a bit-shifting operator that rounds on right-shift See "Bitwise Operations". ** New foreign types: `ssize_t', `ptrdiff_t' See "Foreign Types". ** New C helpers: `scm_from_ptrdiff_t', `scm_to_ptrdiff_t' See "Integers". ** Socket option `SO_REUSEPORT' now available from Scheme If supported on the platform, `SO_REUSEPORT' is now available from Scheme as well. See "Network Sockets and Communication". ** `current-language' in default environment Previously defined only in `(system base language)', `current-language' is now defined in the default environment, and is used to determine the language for the REPL, and for `compile-and-load'. ** New procedure: `fluid->parameter' See "Parameters", for information on how to convert a fluid to a parameter. ** New `print' REPL option See "REPL Commands" in the manual for information on the new user-customizable REPL printer. ** New variable: %site-ccache-dir The "Installing Site Packages" and "Build Config" manual sections now refer to this variable to describe where users should install their `.go' files. * Build fixes ** Fix compilation against libgc 7.3. ** Fix cross-compilation of `c-tokenize.o'. ** Fix warning when compiling against glibc 2.17. ** Fix documentation build against Texinfo 5.0. ** Fix building Guile from a directory with non-ASCII characters. ** Fix native MinGW build. ** Fix --disable-posix build. ** Fix MinGW builds with networking, POSIX, and thread support. * Bug fixes ** Fix inexact number printer. () ** Fix infinite loop when parsing optional-argument short options (SRFI-37). () ** web: Support non-GMT date headers in the HTTP client. () ** web: support IP-literal (IPv6 address) in Host header. ** Avoid stack overflows with `par-map' and nested futures in general. () ** Peek-char no longer consumes EOF. () ** Avoid swallowing multiple EOFs in R6RS binary-input procedures. ** A fork when multiple threads are running will now print a warning. ** Allow for spurious wakeups from pthread_cond_wait. () ** Warn and ignore module autoload failures. () ** Use chmod portably in (system base compile). () ** Fix response-body-port for HTTP responses without content-length. () ** Allow case-lambda expressions with no clauses. () ** Improve standards conformance of string->number. () ** Support calls and tail-calls with more than 255 formals. ** ,option evaluates its right-hand-side. () ** Structs with tail arrays are not simple. () ** Make `SCM_LONG_BIT' usable in preprocessor conditionals. () ** Fix thread-unsafe lazy initializations. ** Allow SMOB mark procedures to be called from parallel markers. () ** Fix later-bindings-win logic in with-fluids. () ** Fix duplicate removal of with-fluids. () ** Support calling foreign functions of 10 arguments or more. () ** Let reverse! accept arbitrary types as second argument. () ** Recognize the `x86_64.*-gnux32' triplet. ** Check whether a triplet's OS part specifies an ABI. ** Recognize mips64* as having 32-bit pointers by default. ** Use portable sed constructs. () ** Remove language/glil/decompile-assembly.scm. () ** Use O_BINARY in `copy-file', `load-objcode', `mkstemp'. ** Use byte-oriented functions in `get-bytevector*'. ** Fix abort when iconv swallows BOM from UTF-16 or UTF-32 stream. ** Fix compilation of functions with more than 255 local variables. ** Fix `getgroups' for when zero supplementary group IDs exist. ** Allow (define-macro name (lambda ...)). ** Various fixes to the (texinfo) modules. ** guild: Gracefully handle failures to install the locale. ** Fix format string warnings for ~!, ~|, ~/, ~q, ~Q, and ~^. () ** Fix source annotation bug in psyntax 'expand-body'. ** Ecmascript: Fix conversion to boolean for non-numbers. ** Use case-insensitive comparisons for encoding names. ** Add missing cond-expand feature identifiers. ** A failure to find a module's file does not prevent future loading. ** Many (oop goops save) fixes. ** `http-get': don't shutdown write end of socket. () ** Avoid signed integer overflow in scm_product. ** http: read-response-body always returns bytevector or #f, never EOF. ** web: Correctly detect "No route to host" conditions. ** `system*': failure to execvp no longer leaks dangling processes. () ** More sensible case-lambda* dispatch. () ** Do not defer expansion of internal define-syntax forms. ()7uC1Maw8yP.pgp
Description: PGP signature | http://lists.gnu.org/archive/html/guile-user/2013-04/msg00037.html | CC-MAIN-2016-50 | refinedweb | 2,182 | 52.66 |
How to Build a Group Chat App with Vue.js
Oscar Castro
Updated on
・13 min read
Chat is everywhere and has ascended to one of the most important communication mediums across our daily lives. The number of chat app use cases is vast and continues to grow. And with today's technological advancements, we expect our messages to send and receive in realtime, instantaneously. It's not a nice-to-have, it's a requirement.
There are thousands of ways to build a chat app, and there are many things to consider: infrastructure, scalability, reliability, and security to name a few. With a vast amount of services, frameworks, and technologies to choose from, making that decision can be overwhelming!
In this tutorial, we're going to build a realtime group chat app in Vue.js. We'll power our app using PubNub, which takes care of the heavy work for us; all we have to worry about is developing the app, not the underlying infrastructure.
Tutorial Overview
Our application will send messages to all connected users in the group chat using publish, and receive messages using subscribe. Our messages will be stored using history, so users can see past or missed messages. To do all this, we will use the PubNub Vue.js SDK. This tutorial is broken into two sections: Publish/Subscribe (Pub/Sub) and History.
You can check out the complete project in the GitHub repository.
Setting up Pub/Sub Messaging
Before we start working on the app, sign up for a free PubNub account. You can get your unique pub/sub keys in the Admin Dashboard.
Next, we need to install two dependencies: vuex and pubnub-vue. We can use NPM to do so.
- npm install vuex --save
- npm install pubnub-vue --save
Since the PubNub Vue.js SDK is a wrapper of the PubNub JavaScript SDK, it offers all the same features. A few extra features, such as Trigger Events, are added to simplify the integration with Vue. One trigger event we'll be using is $pnGetMessage. We use $pnGetMessage with a reactive property so messages display as soon as they are received. To subscribe to a channel we use $pnSubscribe and to publish to a channel we use $pnPublish.
Initialize the PubNub Client API
In the main.js file, create a unique UUID for each user and replace the pub/sub keys with your keys. We include two plugins: PubNubVue and Vuex.
import Vue from 'vue' import App from './App' import store from './store'; import PubNubVue from 'pubnub-vue' Vue.config.productionTip = false; const publish_Key = 'YOUR_PUBLISH_KEY_HERE'; const subscribe_Key = 'YOUR_SUBSCRIBE_KEY_HERE'; // Make a unique uuid for each client const myUuid = fourCharID(); const me = { uuid: myUuid, }; try{ if(!publish_Key || !subscribe_Key){ throw 'PubNub Keys are missing.'; } } catch(err){ console.log(err); } Vue.use(PubNubVue, { subscribeKey: subscribe_Key, publishKey: publish_Key, ssl: true }, store); /* eslint-disable no-new */ new Vue({ el: '#app', store, components: { App }, template: '<App/>', created })
Next, we generate a random 4 character UUID for the user by making a call to the function fourCharID.
function fourCharID() { const maxLength = 4; const possible = 'abcdef0123456789'; let text = ''; for (let i = 0; i < maxLength; i++) { text += possible.charAt(Math.floor(Math.random() * possible.length)); } return text; }
It's recommended to use a standard 128-bit UUID in production apps, but the UUID can be a plain string as well, as is the case for this app. The constant ‘me’ holds the UUID. To commit the constant to the Vuex store, we add the function created.
function created(){ this.$store.commit('setMe', {me}); }
This function will execute when the Vue instance is created.
Setting Up the Vuex Store
For the store.js file, we set up the centralized store that holds and manages the application state. The file will contain a global state object along with a collection of mutation and getter functions. Since outside components cannot access the state directly, we commit a mutation every time we need to update the state.
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const state = { me: {}, }; const mutations = { setMe(state, {me}) { state.me = me; }, } const getters = { getMyUuid: (state) => state.me.uuid, }; export default new Vuex.Store({ state, getters, mutations, });
The getMyUuid getter is referenced in three of the components and is a global getter for the UUID.
ChatContainer Component
The ChatContainer component is the highest parent node of the UI. The markup includes custom HTML tags for the children components of ChatContainer, as well as Vue specific markup to reactively render data.
<template> <div class="chat-container"> <div class="heading"> <h1>{{title + '- User: ' + uuid }}</h1> </div> <div class="body"> <div class="table"> <chat-log></chat-log> <message-input></message-input> </div> </div> </div> </template>
The h1 curly braces bind two JavaScript variables, title and uuid, reactively evaluates the expressions and displays the text output as the text content in the tag. The variable title gets its value from the function data.
data() { return { title: 'PubNub & Vue Global Chat', }; },
Before we discuss the variable uuid, let’s discuss the imports and the two properties above data.
import ChatLog from '@/components/ChatLog'; import MessageInput from '@/components/MessageInput'; import {mapGetters} from 'vuex';
Since we are using the chat-log and message-input tags in the markup, we need to import the ChatLog and MessageInput components so the tags are rendered properly. We also import mapGetters to get the UUID from the store.
export default { name: 'chat-container', components: { ChatLog, MessageInput, },
The name property is ‘chat-container’ and it coincides with the kebab-case HTML tag name in the markup. We include the components property to tell Vue which components are being referenced in the markup. Now, getting back to the variable uuid in the h1 curly brace, we need to set up the computed property which uses mapGetters to map the getter ‘getMyUUID’ to uuid.
computed: { ...mapGetters({ uuid: 'getMyUuid', ), },
Since we are mapping the getter to a different name (uuid), we use an object. Finally, we include the function mounted to subscribe to the channel 'vueChat'.
mounted() { this.$pnSubscribe({ channels: ['vueChat'], }); },
We subscribe, using $pnSubscribe, to the channel once the Vue instance is mounted to the DOM.
MessageInput Component
We break this component into 4 parts:
- First, we check that the message body is not empty.
- Then, we get the user UUID from the store and assigned it to the variable userUUID.
- We publish the message, along with userUUID, to the channel 'vueChat'.
- Finally, we reset the text input.
Here is the template for the component.
<template> <div class="message-input"> <textarea ref="messageInput" placeholder="message..." maxlength="20000" @keydown.</textarea> </div> </template>
When the user types in the message body and presses enter, the function submitMessage is called to check that the message body is not empty. We include this function inside of methods. (Note: The rest of the code for MessageInput Component will be inside of submitMessage).
methods: { submitMessage(event) { if (!event.shiftKey) { event.preventDefault(); } else { return; } // If the message body is empty, do not submit if (event.target.value.length === 0) { return; }
We access the getter, getMyUUID, and assign it to the variable userUUID.
const userUUID = this.$store.getters.getMyUuid;
If the user presses enter and the message body is not empty, we publish to 'vueChat ' the text and the user’s UUID.
this.$pnPublish({ channel: 'vueChat', message: { text: event.target.value, uuid: userUUID, }, })
We reset the text input once the user presses enter.
event.target.value = '';
MessageBubble Component
The chat log will display the messages sent and received in a message bubble. We'll get to the chat log component in a bit, but for now, let’s focus on the message bubble component. When you send a message, the message bubble is shown on the right side of the chat log without displaying your UUID. The messages received from other users are shown on the left side of the chat log with the users UUID shown above the bubble. This follows the design logic of many group chat apps.
<template> <div class="message-bubble" : <span class="from" :uuid</span> <br : <span class="message-text" >text </span> </div> </template>
The class ‘me’ is bound to a class, such as ‘message-bubble’ or ‘from’, only if you send the message. When ‘me’ is bound to a class, the positioning and styling of the message bubble will change, as mentioned above. A computed property is used to check if the user is yourself or someone else.
export default { name: 'message-bubble', props: ['uuid','text'], computed: { me() { let result = false; // Check if the client uuid of the message received is your client uuid if (this.$store.getters.getMyUuid === this.uuid) { result = true; } // Render the message bubble on the right side if it is from this client return result ? 'me' : ''; }, }, data() { return {}; }, };
Besides the computed property, another important part in the script are the prop attributes that are registered to the MessageBubble component. The two values in the prop, ‘uuid’ and ‘text’, will be passed to MessgeBubble's parent component, ChatLog.
ChatLog Component
The chat log displays the messages once it’s received in the channel. Before we work on the template, let’s do the script section first.
import MessageBubble from '@/components/MessageBubble'; import {mapGetters} from 'vuex'; function scrollBottom() { this.$el.scrollTo(0, this.$el.scrollHeight); }
Since we'll be using the message-bubble tag in the markup, we need to import the MessageBubble component in the script so the tags are rendered properly. The scrollBottom function auto scrolls the chat log to the bottom whenever a message is received. This function is called in the watch property.
watch: { vueChatMsg: function(){ this.$nextTick(scrollBottom); } },
We use .$nextTick to make sure the scrollBottom function is called only after the DOM has been updated. Next, let’s add the name property, components and the data function.
name: 'chat-log', components: {MessageBubble}, data() { return { vueChatMsg: this.$pnGetMessage('vueChat'), } },
The data function returns vueChatMsg, which contains the new message payload from the channel. As mentioned before, since we are using $pnGetMessage, the messages will display as soon as they are received. We include the channel name as a parameter. The vueChatMsg property holds an array of objects where every object of the array is the Subscribe Message Response. For every message published, a new message response is added to the array. The objects in the message response includes information such as the channel name, the publisher, the message payload, the subscriber, and so on. We only want the message payload which includes the ‘uuid’ and ‘text’. We will implement this logic in the template.
<template> <div class="chat-log" ref="chatLogContainer" > <message-bubble</message-bubble> </div> </template>
We use v-for to iterate vueChatMsg with ‘msg.id’ as the unique key. We use v-bind to bind the two prop values, ‘uuid’ and ‘text’. Remember that we declared the prop in the child component MessageBubble. So for every iteration of the for loop, we only iterate the message payload and bind ‘msg.message.uuid’ and ‘msg.message.text’ to its corresponding prop attribute.
Let’s quickly summarize the above. Every time a message response is received, it is added as a new element to the array of objects, vueChatMsg, which is returned by the data function. When this happens, inside the message-bubble tag we iterate, using v-for, the new element in the array. Since we only want the message payload, v-for only checks for ‘message’ which contains the payload. The payload values ‘uuid’ and ‘text’ are bind to its appropriate props. Both values are then sent back to the child component, MessageBubble.
That’s all for the Pub/Sub section of this tutorial. Make sure that the code is correct and that you have installed the appropriate plugins. Get the CSS section of the four components from the repo. Run your program by typing 'npm install’ and ‘npm run dev’ in the terminal and your program should start on a localhost port. Type a message in the message input and you should see a blueish bubble on the right side of the chat log. Open another tab, or preferably window, and copy and paste the URL. Now type a new message in the message input and again, you should see the blueish bubble on the right side of the chat log. But now, you should also see the new message on the other chat log. This new message should be a greyish bubble on the left side of the chat log. Play around with both chat windows and see the messages appear in realtime on both screens.
Storing Chat Messages with the History API
While everything is set up and ready to use, there is one problem. If you reload the page, you will notice that all the messages disappear. This occurs because the Storage & Playback feature is not turned on. To turn it on, go to the PubNub Admin Dashboard and click on your application. Click on Keyset and scroll down to Application add-ons. Keep scrolling down until you get to Storage & Playback and toggle the switch to on. Keep the default values the same.
Now that it’s on, messages will persist in storage and can be retrieved later on. Messages can also be deleted from history to meet GDPR compliance. If you cloned the repo, then reload the page for the chat app and the messages should appear in oldest to newest order. If you didn’t clone the repo, the messages won’t appear since the history function, which fetches historical messages of a channel, has not been added to the code. Either way, in the next section, we will implement the history function so messages can be stored and retrieved.
Setting up History
Fetching the historical messages of our channel is not difficult to do. We need to make small modifications to three files: store.js, ChatContainer.vue, and ChatLog.vue. Let’s start with store.js.
Modify the Vuex State
In the state, we need to add a new property, history, with an empty array as the value.
const state = { ... history: [], };
In mutations, we add a new mutation, addHistory, with state as the first argument and history as the second argument.
const mutations = { ... addHistory(state, {history}){ history.forEach(element => { state.history.push(element.entry); }); }, }
We iterate the array history that contains the historical messages retrieved from the channel. Each element in the array contains two keys, timetoken and entry. We only want entry since it contains the text the user entered and their UUID. This is why in each iteration we push element.entry to the history array we added in state. We will only add one line to getters.
const getters = { ... getHistoryMsgs: (state) => state.history, };
Modify ChatContainer
Since we need to use the history function, import PubNubVue.
import PubNubVue from 'pubnub-vue';
Below the imports, we add a new function, fetchHistory, that will fetch 6 messages from the channel. You can change the number of messages to fetch with 100 being the max number.
function fetchHistory(store){ PubNubVue.getInstance().history( { channel: 'vueChat', count: 6, // how many items to fetch stringifiedTimeToken: true, // false is the default }, function(status, response) { const msgs = response.messages; // Iterate msgs array and save each element to history msgs.forEach(elem => { store.commit('addHistory', {history: [elem]}); }) } ) }
To commit the history payload, save response.messages to the constant variable ‘msgs’. The constant contains an array of objects where each object contains two keys (timetoken and entry). We don’t want to commit the whole array to the Vuex Store, rather, we want to iterate the array and commit each element. This will make it easier to fetch the necessary keys in the addHistory function. The last modification to include is in mounted which makes the call to fetchHistory.
mounted() { ... this.$nextTick(fetchHistory(this.$store)); },
We pass this.$store as a parameter so we can commit the changes to the store.
Modify ChatLog
This is the last file we need to update. We need to make changes to the template and the script. Let’s start with the script. We need to import mapGetters since we will be using it in the computed property.
import {mapGetters} from 'vuex';
In the computed property, we map the getter ‘getHistoryMsgs’ to history.
computed: { ...mapGetters({ history: 'getHistoryMsgs', }), },
In the template, we add another message-bubble tag.
<template> ... <message-bubble</message-bubble> ... </template>
This looks very similar to what we did earlier. We use v-for to iterate history. At every iteration, we retrieve the ‘uuid’ and ‘text’ from the array and bind it to its appropriate prop attributes. The messages will show in the chat log as message bubbles. That is all we need to do for history. Run the program again and you should see the last six messages from history in the chat log.
There are two things to take note of. The first thing is that the messages will persist in storage for 1 day only. After 1 day, the messages are removed from storage. You can change the time period a message is stored by changing the retention time, which is located in the Storage & Playback add-on. For the purpose of this tutorial, we leave the default value of 1 day.
The second thing to note is that the history messages will show on the left side of the chat log, even if the messages are from you. This is because we generate a random 4 character UUID every time the app instantiates. So when you reload the page, a new UUID is assigned to you and the previous messages you sent before the reload will now be seen as messages sent from another user. This is fine for this tutorial, but for real production, each user should have a unique UUID that is persistent. For a persistent UUID, the history messages that are sent by you will show on the right side of the chat log.
What's Next?
Now that you've got your basic messaging functionality implemented, it's time to add more features! Head over to our Chat Resource Center to explore new tutorials, best practices, and design patterns for taking your chat app to the next level.
The software industry moves fast. But if you keep up, you can have an incredible career.
Join DEV. 100% Free Forever.
Yes, you can build a chat app with 1x1 functionality with PubNub. You can find more information and tutorials to build a chat app with PubNub in the Chat Resource Center. Let me know if you have any more questions :) | https://practicaldev-herokuapp-com.global.ssl.fastly.net/pubnub/how-to-build-a-group-chat-app-with-vue-js-5d2g | CC-MAIN-2020-16 | refinedweb | 3,087 | 65.32 |
1. Overview
TP. Loading Data
We will be working with a dataset of flower pictures. The goal is to learn to categorize them into 5 flower types. Data loading is performed using the
tf.data.Dataset API. First, let us get to know the API.
Hands-on
Please open the following notebook, execute the cells (Shift-ENTER) and follow the instructions wherever you see a "WORK REQUIRED" label.
Fun with tf.data.Dataset (playground).ipynb
Additional information
About the "flowers" dataset
The dataset is organised in 5 folders. Each folder contains flowers of one kind. The folders are named sunflowers, daisy, dandelion, tulips and roses. The data is hosted in a public bucket on Google Cloud Storage. Excerpt:
gs://flowers-public/sunflowers/5139971615_434ff8ed8b_n.jpg gs://flowers-public/daisy/8094774544_35465c1c64.jpg gs://flowers-public/sunflowers/9309473873_9d62b9082e.jpg gs://flowers-public/dandelion/19551343954_83bb52f310_m.jpg gs://flowers-public/dandelion/14199664556_188b37e51e.jpg gs://flowers-public/tulips/4290566894_c7f061583d_m.jpg gs://flowers-public/roses/3065719996_c16ecd5551.jpg gs://flowers-public/dandelion/8168031302_6e36f39d87.jpg gs://flowers-public/sunflowers/9564240106_0577e919da_n.jpg gs://flowers-public/daisy/14167543177_cd36b54ac6_n.jpg
Why tf.data.Dataset?
Keras and Tensorflow accept Datasets in all of their training and evaluation functions. Once you load data in a Dataset, the API offers all the common functionalities that are useful for neural network training data:
dataset = ... # load something (see below) dataset = dataset.shuffle(1000) # shuffle the dataset with a buffer of 1000 dataset = dataset.cache() # cache the dataset in RAM or on disk dataset = dataset.repeat() # repeat the dataset indefinitely dataset = dataset.batch(128) # batch data elements together in batches of 128 AUTOTUNE = tf.data.AUTOTUNE dataset = dataset.prefetch(AUTOTUNE) # prefetch next batch(es) while training
You can find performance tips and Dataset best practices in this article. The reference documentation is here.
tf.data.Dataset basics
Data usually comes in multiple files, here images. You can create a dataset of filenames by calling:
filenames_dataset = tf.data.Dataset.list_files('gs://flowers-public/*/*.jpg') # The parameter is a "glob" pattern that supports the * and ? wildcards.
You then "map" a function to each filename which will typically load and decode the file into actual data in memory:
def decode_jpeg(filename): bits = tf.io.read_file(filename) image = tf.io.decode_jpeg(bits) return image image_dataset = filenames_dataset.map(decode_jpeg) # this is now a dataset of decoded images (uint8 RGB format)
To iterate on a Dataset:
for data in my_dataset: print(data)
Datasets of tuples
In supervised learning, a training dataset is typically made of pairs of training data and correct answers. To allow this, the decoding function can return tuples. You will then have a dataset of tuples and tuples will be returned when you iterate on it. The values returned are Tensorflow tensors ready to be consumed by your model. You can call
.numpy() on them to see raw values:
def decode_jpeg_and_label(filename): bits = tf.read_file(filename) image = tf.io.decode_jpeg(bits) label = ... # extract flower name from folder name return image, label image_dataset = filenames_dataset.map(decode_jpeg_and_label) # this is now a dataset of (image, label) pairs for image, label in dataset: print(image.numpy().shape, label.numpy())
Conclusion:loading images one by one is slow !
As you iterate on this dataset, you will see that you can load something like 1-2 images per second. That is too slow! The hardware accelerators we will be using for training can sustain many times this rate. Head to the next section to see how we will achieve this.
Solution
Here is the solution notebook. You can use it if you are stuck.
Fun with tf.data.Dataset (solution).ipynb
What we've covered
- 🤔 tf.data.Dataset.list_files
- 🤔 tf.data.Dataset.map
- 🤔 Datasets of tuples
- 😀 iterating through Datasets
Please take a moment to go through this checklist in your head.
5. Loading data fast
The Tensor Processing Unit (TPU) hardware accelerators we will be using in this lab are very fast. The challenge is often to feed them data fast enough to keep them busy. Google Cloud Storage (GCS) is capable of sustaining very high throughput but as with all cloud storage systems, initiating a connection costs some network back and forth. Therefore, having our data stored as thousands of individual files is not ideal. We are going to batch them in a smaller number of files and use the power of tf.data.Dataset to read from multiple files in parallel.
Read-through
The code that loads image files, resizes them to a common size and then stores them across 16 TFRecord files is in the following notebook. Please quickly read through it. Executing it is not necessary since properly TFRecord-formatted data will be provided for the rest of the codelab.
Flower pictures to TFRecords.ipynb
Ideal data layout for optimal GCS throughput
The TFRecord file format
Tensorflow's preferred file format for storing data is the protobuf-based TFRecord format. Other serialization formats would work too but you can load a dataset from TFRecord files directly by writing:
filenames = tf.io.gfile.glob(FILENAME_PATTERN) dataset = tf.data.TFRecordDataset(filenames) dataset = dataset.map(...) # do the TFRecord decoding here - see below
For optimal performance, it is recommended to use the following more complex code to read from multiple TFRecord files at once. This code will read from N files in parallel and disregard data order in favor of reading speed.
AUTOTUNE = tf.data.AUTOTUNE ignore_order = tf.data.Options() ignore_order.experimental_deterministic = False filenames = tf.io.gfile.glob(FILENAME_PATTERN) dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTOTUNE) dataset = dataset.with_options(ignore_order) dataset = dataset.map(...) # do the TFRecord decoding here - see below
TFRecord cheat sheet
Three types of data can be stored in TFRecords: byte strings (list of bytes), 64 bit integers and 32 bit floats. They are always stored as lists, a single data element will be a list of size 1. You can use the following helper functions to store data into TFRecords.
writing byte strings
# warning, the input is a list of byte strings, which are themselves lists of bytes def _bytestring_feature(list_of_bytestrings): return tf.train.Feature(bytes_list=tf.train.BytesList(value=list_of_bytestrings))
writing integers
def _int_feature(list_of_ints): # int64 return tf.train.Feature(int64_list=tf.train.Int64List(value=list_of_ints))
writing floats
def _float_feature(list_of_floats): # float32 return tf.train.Feature(float_list=tf.train.FloatList(value=list_of_floats))
writing a TFRecord, using the helpers above
# input data in my_img_bytes, my_class, my_height, my_width, my_floats with tf.python_io.TFRecordWriter(filename) as out_file: feature = { "image": _bytestring_feature([my_img_bytes]), # one image in the list "class": _int_feature([my_class]), # one class in the list "size": _int_feature([my_height, my_width]), # fixed length (2) list of ints "float_data": _float_feature(my_floats) # variable length list of floats } tf_record = tf.train.Example(features=tf.train.Features(feature=feature)) out_file.write(tf_record.SerializeToString())
To read data from TFRecords, you must first declare the layout of the records you have stored. In the declaration, you can access any named field as a fixed length list or a variable length list:
reading from TFRecords
def read_tfrecord(data): features = { # tf.string = byte string (not text string) "image": tf.io.FixedLenFeature([], tf.string), # shape [] means scalar, here, a single byte string "class": tf.io.FixedLenFeature([], tf.int64), # shape [] means scalar, i.e. a single item "size": tf.io.FixedLenFeature([2], tf.int64), # two integers "float_data": tf.io.VarLenFeature(tf.float32) # a variable number of floats } # decode the TFRecord tf_record = tf.io.parse_single_example(data, features) # FixedLenFeature fields are now ready to use sz = tf_record['size'] # Typical code for decoding compressed images image = tf.io.decode_jpeg(tf_record['image'], channels=3) # VarLenFeature fields require additional sparse.to_dense decoding float_data = tf.sparse.to_dense(tf_record['float_data']) return image, sz, float_data # decoding a tf.data.TFRecordDataset dataset = dataset.map(read_tfrecord) # now a dataset of triplets (image, sz, float_data)
Useful code snippets:
reading single data elements
tf.io.FixedLenFeature([], tf.string) # for one byte string tf.io.FixedLenFeature([], tf.int64) # for one int tf.io.FixedLenFeature([], tf.float32) # for one float
reading fixed size lists of elements
tf.io.FixedLenFeature([N], tf.string) # list of N byte strings tf.io.FixedLenFeature([N], tf.int64) # list of N ints tf.io.FixedLenFeature([N], tf.float32) # list of N floats
reading a variable number of data items
tf.io.VarLenFeature(tf.string) # list of byte strings tf.io.VarLenFeature(tf.int64) # list of ints tf.io.VarLenFeature(tf.float32) # list of floats
A VarLenFeature returns a sparse vector and an additional step is required after decoding the TFRecord:
dense_data = tf.sparse.to_dense(tf_record['my_var_len_feature'])
It is also possible to have optional fields in TFRecords. If you specify a default value when reading a field, then the default value is returned instead of an error if the field is missing.
tf.io.FixedLenFeature([], tf.int64, default_value=0) # this field is optional
What we've covered
- 🤔 sharding data files for fast access from GCS
- 😓 how to write TFRecords. (You forgot the syntax already? That's OK, bookmark this page as a cheat sheet)
Please take a moment to go through this checklist in your head.
6. Congratulations!
You can now feed a TPU with data. Please continue to the next lab
- [THIS LAB] TPU-speed data pipelines: tf.data.Dataset and TFRecords
- Your first Keras model, with transfer learning
- Convolutional neural networks, with Keras and TPUs
-_27<< | https://codelabs.developers.google.com/codelabs/keras-flowers-data/?hl=ko | CC-MAIN-2022-40 | refinedweb | 1,529 | 50.94 |
On Tue, 14 Jun 2011 22:50:14 +0200"Rafael J. Wysocki" <rjw@sisk.pl> wrote:> On Tuesday, June 14, 2011, Martin Schwidefsky wrote:> > Hi Rafael,> > > On Sun, 12 Jun 2011 14:41:34 +0200> > "Rafael J. Wysocki" <rjw@sisk.pl> wrote:> > > > > > diff -urpN linux-2.6/kernel/power/snapshot.c linux-2.6-patched/kernel/power/snapshot.c> > > > --- linux-2.6/kernel/power/snapshot.c 2011-06-06 11:14:39.000000000 +0200> > > > +++ linux-2.6-patched/kernel/power/snapshot.c 2011-06-06 11:14:43.000000000 +0200> > > > @@ -1022,6 +1022,137 @@ static inline void copy_data_page(unsign> > > > }> > > > #endif /* CONFIG_HIGHMEM */> > > > > > > > +#ifdef CONFIG_S390> > > > +/*> > > > + * For s390 there is one additional byte associated with each page,> > > > + * the storage key. The key consists of the access-control bits> > > > + * (alias the key), the fetch-protection bit, the referenced bit> > > > + * and the change bit (alias dirty bit). Linux uses only the> > > > + * referenced bit and the change bit for pages in the page cache.> > > > + * Any modification of a page will set the change bit, any access> > > > + * sets the referenced bit. Overindication of the referenced bits> > > > + * after a hibernation cycle does not cause any harm but the> > > > + * overindication of the change bits would cause trouble.> > > > + * Therefore it is necessary to include the storage keys in the> > > > + * hibernation image. The storage keys are saved to the most> > > > + * significant byte of each page frame number in the list of pfns> > > > + * in the hibernation image.> > > > + */> > > > > > Let me say that is not exactly straightforward. :-)> > > > > > One thing I don't really understand is where those storage keys are normally> > > stored so that they aren't present in the image without this additional> > > mechanism. Could you explain that a bit more, please?> > > > The storage keys are outside of the directly addressable memory, the only> > way to get to them is with special instructions:> > iske - insert storage key extended, ivsk - insert virtual storage key,> > sske - set storage key extended, and rrbe - reset reference bit extended.> > The storage key of a page has 7 bits, 4 bit for access-control, the> > fetch-protection-bit, the reference-bit and the change-bit. In Linux only> > the reference and change bits are used.> > OK, so it looks like we would only need to store 2 bits per page in additional> allocations.For now we'd only need two bits, but with KVM guests we will have to store thecomplete storage key. The guest OS could make use of all the bits in the storagekey, the KVM host needs to preserve them.> > These bits are per physical page, one of the major differences of the s390> > machines compared to other architectures. We had a number of interesting> > problems because of pte dirty & referenced vs page dirty & referenced.> > For e.g. x86 a page is implicitly clean if it has no mapper. On s390 is> > depends on the contents of the storage key. Which is why SetPageUptodate> > clears the storage key.> > > > In regard to hibernation the important aspect is that each and every write> > to a page sets the dirty bit even if it is done by I/O. The restore of the> > hibernation image therefore makes all pages dirty. To get the correct> > original combination of page content and storage key content the storage> > key needs to be set after the last access to the page content.> > What, in your opinion, is the right time for restoring the original storage> keys after the image has been loaded? It seems that should happen after> passing control to the hibernated kernel.Anytime after the final write of the page content completed and before thehibernated kernel gets control (or shortly after in the resume code of therestored kernel).> > > > +> > > > +/*> > > > + * Key storage is allocated as a linked list of pages.> > > > + * The size of the keys array is (PAGE_SIZE - sizeof(long))> > > > + */> > > > +struct page_key_data {> > > > + struct page_key_data *next;> > > > + unsigned char data[];> > > > +};> > > > > > This seems to be similar to the data structure for the saving of ACPI NVS> > > memory, so perhaps it's possible to combine the two.> > > > Almost the same, I thought about ways to merge them. I dropped the idea in> > order to keep the patch as small as possible.> > I think, however, that we really should try to merge them. The only> difference seems to be how the additionally allocated pages will be populated> and what's going to happen to their contents during restore.> > ACPI will simply copy the NVS memory to those pages, while S390 will save> the relevant storage key bits in there.One complication to keep in mind is that we need to know which storage keygoes to which page frame. We need something like the orig_bm/copy_bm orwe'd have to store the pfn with the key. Simply storing the key for everypage will make the array unnecessarily big.> > > > +#define PAGE_KEY_DATA_SIZE (PAGE_SIZE - sizeof(struct page_key_data *))> > > > +> > > > +static struct page_key_data *page_key_data;> > > > +static struct page_key_data *page_key_rp, *page_key_wp;> > > > +static unsigned long page_key_rx, page_key_wx;> > > > +> > > > +/*> > > > + * For each page in the hibernation image one additional byte is> > > > + * stored in the most significant byte of the page frame number.> > > > > > I'm not sure it's really worth the complication. If you simply store those> > > keys in separete pages, you'd need one additional page per PAGE_SIZE> > > page frames, so given PAGE_SIZE = 4096 that's one page per 16 MB of memory,> > > which is not a whole lot (64 extra pages per GB if I'm not mistaken).> > > > > > It seems that doing it will simplify things quite a git.> > > > One of the versions of the patch actually did that and it turned out to> > be much larger then the proposed solution. That older version had another> > step in snapshot_read_next / snapshot_write_next to copy the storage keys> > to pages allocated for that purpose. I had some trouble with the way how> > the code deals with the orig_bm and the copy_bm though. Not trivial code..> > Well, I'm sure we can handle that. :-)> > I thought of the following approach:> > * Allocate memory for saving the relevant bits of the storage keys before> the memory preallocation kicks in.> > * Save the storage key bits to that memory before creating the image (be> careful about the storage keys of the pages they are being stored into).> > * After getting control from the boot kernel, restore the storage key bits> saved before creating the image.> > * Free additional memory used for storing them.> > This way we wouldn't have to worry about any interactions with> snapshot_read_next / snapshot_write_next etc.Well before the preallocation kicked in we don't know which are the relevantstorage keys. The only other option would be to store all of them which Iconsider to be a inferior solution. -- blue skies, Martin."Reality continues to ruin my life." - Calvin. | https://lkml.org/lkml/2011/6/15/42 | CC-MAIN-2015-48 | refinedweb | 1,102 | 62.88 |
sxl Overview
This library is intended to help you deal with big Excel files from within Python. After trying pandas, openpyxl, xlwings, and even win32com it seems that none have the ability to iterate over large Excel files without loading them completely into memory. So when you are dealing with files that are extremely large, this can be burdensome (especially if you only want to examine a bit of the file – the first 10 rows say). This library solves that by parsing the SpreadsheetML / XML xlsx files using a streaming parser. So you can see the first ten rows of any tab within any Excel file extremely quickly.
Getting Started
There are no dependancies to install. You just need to:
pip install sxl
Once installed, you can iterate through the entire file without using much memory by doing the following:
from sxl import Workbook wb = Workbook("filepath") ws = wb.sheets['sheet name'] # or, for example, wb.sheets[1] for row in ws.rows: print(row)
Note that by default we assume the workbook is encoded with UTF-8. If you need to specifiy a different encoding, you can do so when opening the workbook:
wb = Workbook("filepath", encoding='cp1252')
If you are only interested in a few rows:
head = ws.head(5) print(head)
Running Tests
To run tests:
python -m tests.test_sxl
License
The project is licensed under the MIT License – see the LICENSE.md file for details | https://excelexamples.com/post/a-python-library-to-help-you-deal-with-big-excel-files/ | CC-MAIN-2022-21 | refinedweb | 239 | 63.7 |
by Roman Kazantsev
1. About the tool
The Intel® HTML5 App Porter Tool is an application that helps mobile application developers to port native iOS* code to HTML5 by automatically translating portions of the iOS code into HTML5. This tool does not automatically port 100% of iOS applications, but instead it speeds up the porting process by translating as much code and artifacts as possible.
It helps in the translation of the following artifacts:
- Objective-C* (and a subset of C) source code into JavaScript*
- iOS API types and calls into JavaScript/HTML5 objects and calls
- Layouts of views inside Xcode* Interface Builder (XIB) files into HTML + CSS files
- Xcode project files into Microsoft Visual Studio* 2012 projects
1.1 Architecture of translated applications
The translated application keeps the same high level structure as the original one. Constructs such as Objective-C interfaces, categories, C structures, functions, variables, and statements are kept without significant changes in the translated code but are expressed in JavaScript.
The Intel HTML5 App Porter Tool produces a set of files that can be divided in four groups:
- The translated app code: These are the JavaScript files that are created from the original app’s Objective-C files.
- For each translated module (i.e., each .m file) there should be a .js file with a matching name.
- The default.html file is the entry point for the HTML5 app, where all the other .js files are included.
- Additionally, there are some JavaScript files included in the \lib folder that correspond to 3rd party libraries and the Intel HTML5 App Porter Tool – BETA library which implements most of the functionality that is not available in HTML5.
- Translated .xib files (if any): For each translated .xib file there should be .html and .css files with matching names. These files correspond to their HTML5 version.
- “ToDo” JavaScript files: Because some of the APIs in the original app may not be translated by the current version, empty definitions are generated as placeholders for those not-mapped APIs in the translated HTML5 app. These “ToDo” files contain those placeholders and are named after the class of the not-mapped APIs. For instance, the placeholders for not-mapped methods of the NSData class would be located in a file named something like todo_api_js_apt_data.js or todo_js_nsdata.js.
- Resources: All the resources from the original iOS project will be copied to the root folder of the translated HTML5 app.
The generated JavaScript files have names that are practically the same as the original ones. For example, if you have a file called AppDelegate.m in the original application, you will end up with a file called AppDelegate.js in the translated output. Likewise, the names of interfaces, functions, fields, and variables are not changed, unless the differences between Objective-C and JavaScript require the tool to do so.
Also, underlying platforms (jQuery Mobile JavaScript framework and HTML5 technology) allow the Intel HTML5 App Porter tool to create cross-platform applications.
In short, the high level structure of the translated application is practically the same as the original one. Therefore, the design and structure of the original application will remain the same in the translated version.
1.2 Pipeline of translation of Objective-C into JavaScript
At a high level, the transformation pipeline looks like this:
This pipeline follows the following stages:
- Objective-C files are parsed into an intermediate AST (Abstract Syntax Tree)
- Supported iOS API calls are mapped into equivalent JavaScript calls
- Placeholder definitions are generated for unsupported API calls
- Finally, JavaScript and HTML5 files are generated
1.3 Current release and planned features in the next release
The latest release of the tool is the beta version, which you can find at:.
For support, comments, bug reports, feature requests, or general feedback you can use the HTML5 tools forums or send an email to app_porter_tool@intel.com..
Not sure what the first paragraph is saying. Is it: “A translated HTML5 project has a jsproj file that allows the application to run on Windows* 8. The jsproj file is a JavaScript project file that you can open with Visual Studio and continue development in case the translation produced some placeholders.”
Additionally, the translated project can be ported to Android*. To do so, you have to call HTML5 routines from Dalvik* code as follows:
package com.helloworld; public class HelloWebApp extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); WebView webView = (WebView)findViewById(R.id.webView); webView.getSettings().setJavaScriptEnabled(true); webView.setWebChromeClient(new WebChromeClient()); webView.loadUrl(""); } }
Also, you should add webView object in xml file for layout.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns: <WebView android: </LinearLayout>
3. Recap from one sample of translated application
I tried to translate one Xcode 3.2 project that has a GUI-based storyboard and a code snippet that used Social API modules.
To summarize:
- 76% of the iOS calls translated successfully
- The other 24% had placeholder declarations. The tool didn’t translate calls for swipe gesture handlers, file reading, font configuration, string appending, and unichar type.
- Beta version (the latest release) compared to the July demo version. The demo version could not parse some Objective-C files with synthesis and define directives for clang. The latest version parses them successfully. The percentage of placeholders was reduced by 20% in the latest version compared to the July demo.
The tool showed relatively good translation statistics but only for a set of minor iOS calls. Actually, I have no positive results in output. Most of the kernel parts in GUI and the social API were not translated on the whole.
3.1 The pros and cons of the beta version of HTML5 App Porter
- GUI translation. The tool can work with most UI elements such as UIButton, UILabel, UIImage, UITextField, etc. However, the tool can work only with View objects that consist of manually loaded UIObjects. The tool could not correctly translate the GUI in storyboards. And we have to redesign those parts using JavaScript.
- Standard types and their method translation. The tool supports C global functions and types such as NSString, NSArray, NSDictionary, etc., but only a small part of their methods can be translated. For instance, the methods stringByAppendingFormat and stringWithContentsOfFile of NSString are unsupported.
- Social API. Most mobile applications seem to use the social API, but unfortunately, the tool is unable to translate it. | http://software.intel.com/fr-fr/articles/intel-html5-porter-tool-introduction-for-android-developer | CC-MAIN-2013-48 | refinedweb | 1,067 | 55.34 |
Unlike a standard HTML
<form>, the
Form component does not update the page
props when the user submits the form. Instead, the
useFormSubmit hook should be used to consume any
pending or response data.
If you wish to have the same behavior between
<form> and
<Form> (update the
page on submit), then you can wrap your Next.js app component with our provider.
note: Using the hook is the recommended approach to update the page props. The whole purpose of this provider, is to force a full page update on state change. That might not be what you want.
When including our provider, the pages will initially render with GET data. Which is Next.js default behavior. Once the form is submitted, the handler result data is provided to the page component.
note: This provider is not needed when returning a `redirect` from mutation handlers. It's only needed when returning `json`, and you need to have that data in the page props.
Enough warnings, here are the implementation examples.
#Example without custom app component
Add the following code to
/pages/_app.js
import { withNextRuntime } from 'next-runtime/app'; export default withNextRuntime();
#Example with custom app component
Provide your App component as argument, if you're already using a custom one:
import { withNextRuntime } from 'next-runtime/app'; function MyApp({ Component, pageProps }) { return <Component {...pageProps} />; } export default withNextRuntime(MyApp); | http://next-runtime.meijer.ws/api/with-next-runtime | CC-MAIN-2022-33 | refinedweb | 228 | 58.48 |
#include <wx/html/helpdata.h>
This class is used by wxHtmlHelpController and wxHtmlHelpFrame to access HTML help items.
It is internal class and should not be used directly - except for the case you're writing your own HTML help controller.
Constructor.
Adds new book.
book_url is URL (not filename!) of HTML help project (hhp) or ZIP file that contains arbitrary number of .hhp projects (this zip file can have either .zip or .htb extension, htb stands for "html book").
Returns success.
Returns page's URL based on integer ID stored in project.
Returns page's URL based on its (file)name.
Returns array with help books info.
Returns reference to array with contents entries.
Returns reference to array with index entries.
Sets the temporary directory where binary cached versions of MS HTML Workshop files will be stored.
(This is turned off by default and you can enable this feature by setting non-empty temp dir.) | https://docs.wxwidgets.org/3.0/classwx_html_help_data.html | CC-MAIN-2019-09 | refinedweb | 155 | 77.74 |
Forums » Saxon/C Help and Discussions »
Managing Saxon/C's Java VM
Added by Aleksandar Jelenak about 6 years ago
Hello!
I am developing Python bindings for the Saxon/C HE library. The code is on GitHub ().
When running unit tests I get the error: "JNI_CreateJavaVM() failed with result: -5" when a SaxonProcessor object is created in more than one test. This error (JNI_EEXIST) indicates that a Java VM already exists by the time the second unit test is executed. Since I have never before used a C/C++ library built from its Java version I would like to know how to manage Saxon/C's Java VM. When is it started? When a first SaxonProcessor object is created? When is it terminated? If a SaxonProcessor object is destroyed, how does that affect the Java VM? Or is the Java VM terminated only when the executing process ends. Should I create and use a single SaxonProcessor object in all unit tests?
Thanks!
Aleksandar
Replies (4)
RE: Managing Saxon/C's Java VM
-
Added by O'Neil Delpratt about 6 years ago
Hi Aleksandar,
Interesting project you are undertaking and thanks for contacting us in regards to your issue. It is true the Java VM can only be created once per process. The VM is a static component that should be available for multiple instance of the SaxonProcessor object. As a safety measure I added a boolean variable to prevent it being created more than once (i.e. jvmCreatedCPP). I am a bit puzzled as to how you are getting that error. It is possible that you have discovered a bug here.
Please can you send your code for the unit tests so that I can better examine where things could be going wrong. Usually with a test harness I create the SaxonProcessor once and create multiple instances for any of the following engines XsltProcessor/XQueryProcessor/XPathProcessor/SchemaValidator via the SaxonProcessor object.
RE: Managing Saxon/C's Java VM
-
Added by Aleksandar Jelenak about 6 years ago
Hello!
Thanks for the prompt reply. These are the Python unit tests:
def test_create_bool(self): """Create SaxonProcessor object with a boolean argument""" from random import choice sp = SaxonProcessor(choice([True, False])) self.assertIsInstance(sp, SaxonProcessor) def test_create_procs(self): """Create XPathProcessor, XsltProcessor from SaxonProcessor object""" sp = SaxonProcessor(False) xp = sp.newXPathProcessor() xsl = sp.newXsltProcessor() self.assertIsInstance(xp, XPathProcessor) self.assertIsInstance(xsl, XsltProcessor)
These are very basic tests. If only one of them is run, there is no error. Here's the test log:
test_create_bool In SaxonProcessor.__cinit__() In SaxonProcessor.__dealloc__() PASSED test_create_procs In SaxonProcessor.__cinit__() JNI_CreateJavaVM() failed with result: -5
The @cinit()@ and @dealloc()@ are special methods called when Python creates and destroys SaxonProcessor extension type objects. The @cinit()@ method just calls the @SaxonProcessor(bool l)@ class constructor. The @dealloc()@ method calls the @void release()@ method and a @delete@ on the SaxonProcessor's C++ pointer. I can provide more information if required.
RE: Managing Saxon/C's Java VM
-
Added by O'Neil Delpratt about 6 years ago
Hi,
Thanks for sending your python code snippet. The release method called in dealloc() should only be called once at the end of your program. This is because the VM can only be created and destroyed once in the same process.
I will try now to answer your initial questions:
I would like to know how to manage Saxon/C's Java VM. When is it started? When a first SaxonProcessor object is created?
Yes. It is started when you call the constructor of the SaxonProcessor. It is a static variable so it is shared between instances of SaxonProcessor.
When is it terminated? The VM is destroyed when you call the release() method on SaxonProcessor. If there are multiple instances of the SaxonProcessor class alive then a reference count is used to prevent the release method destroying the VM until the last SAxonProcessor object has been destroyed.
If a SaxonProcessor object is destroyed, how does that affect the Java VM? Calling the destructor of SaxonProcessor does not affect the VM.
Or is the Java VM terminated only when the executing process ends. Should I create and use a single SaxonProcessor object in all unit tests?
You can have more than one SaxonProcessor, it all depends on the design of the program. In the PHP world you would have created a SaxonProcessor for each request. The reference counter is important in this case to keep track of how many SaxonProcessor object where created so we only call release when the last SaxonProcessor has been destroyed.
In the sample C++ code we see that a single SaxonProcessor is necessary when sharing commonalities between parsed XML documents.
See details of the Processor object for Java but relevant to C++:.
From
RE: Managing Saxon/C's Java VM
-
Added by Aleksandar Jelenak about 6 years ago
Thanks for clarification. I changed my code accordingly and now those simple tests work. | https://saxonica.plan.io/boards/4/topics/6399 | CC-MAIN-2022-27 | refinedweb | 819 | 57.67 |
im_hist - create a displayable histogram from an image
#include <vips/vips.h> int im_hist( in, plotofhist, bandno ) IMAGE *in, *plotofhist; int bandno;
im_hist() creates a displayable histogram file for the image held by the image descriptor in. The created displayable histogram is held in the IMAGE descriptor plotofhist. If bandno == -1 a displayable histogram of all input bands is created else the histogram of bandno only is created. See im_histplot(3) for rules on the size and scaling og the result.
All functions returns 0 on success and -1 on error.
im_histgr(3), im_histplot(3).
N. Dessipris
N. Dessipris - 10/05/1991 10 May 1991 | http://huge-man-linux.net/man3/im_hist.html | CC-MAIN-2017-30 | refinedweb | 105 | 74.19 |
History of Changes
Back
Download
Index
License
Install
Technologies
Infrastructure
User Guide
Dynamic XML
Caching
How it works
XML Links
XSP Processor
XSP WD
XMLFragments
ESQL Taglib
SQL Conn Pool
FP Taglib
LDAP Processor
SQL Processor
SQL Taglib
Contributing
3rd Party
Patch Queue
Changes
Todo
Live Sites
Cocoon Hosting
Bug Database
Code Repository
Mail Lists
Mail Archives
Cocoon 2.0 Site
Cocoon 2.1 Site
1.8.3-dev (July 9 2003)
Updated site style: removed generated images in the navigation bar and replaced with text. (VG)
The repository for Cocoon 1.x is now called "cocoon-1" (the old "xml-cocoon" repository is deprecated). (PF)
New SVG formatter based on Batik. (SW)
Workaround for XSP isCacheable bug. (RDG) Thanks to
Paul Nock
.
Fixed error reporting on some servlet engines for case where getWriter had already been called. (RDG) Thanks to
Ulrich Mayring
.
Two more xsl:params available in logicsheets - path and relative-filename. If the source filename is /home/greenrd/test.xml then path will be /home/greenrd and relative-filename will be test.xml. (RDG) Thanks to
Peter C. Verhage
.
XSP now allows periods (.) in namespaces for namespace-mapped logicsheets. (RDG) Thanks to
paint007@mc.duke.edu
.
Added ability to omit xml declaration from output (see cocoon.properties). (RDG) Thanks to
Sebastien Koechlin
.
Fixed default encoding bug introduced by the changes for FOP 0.16 below. (RDG) Thanks to
Jay Freeman
.
Non-default encodings in logicsheets should now work. (RDG) Thanks to
Krzysztof Zielinski
.
XSLTProcessor now recognises text/xml and application/xml mime-types in PIs as stylesheets, not just text/xsl. (RDG) Thanks to
Eric A. Sirois
.
Caching memory wastage fixes for XIncludeProcessor and ProducerFromFile (identical to the XSLTProcessor bug fix in a previous version). These bugs could theoretically have caused OutOfMemoryErrors, so upgrading is strongly recommended! (RDG)
Upgraded Ant from version 1.1 to version 1.3 and rewrote build.xml to use new syntax. (RDG) Thanks to
Phillipe Lavoie
.
Added "fastcutoff" setting to cocoon.properties to control sendRedirect, getOutputStream and getWriter behaviour for maximum flexibility and backward compatibility. (RDG) Thanks to
Donald Ball
.
Updated Cocoon for compatibility with FOP 0.16 and above. Backward compatibility to at least FOP 0.13 is still maintained. WARNING: The Formatter interface has been changed. Instead of taking a Writer it now takes an OutputStream. This makes more sense for output types like PDF. (RDG) Thanks to
Kelly Campbell
.
Stylesheets (but not logicsheets) can now access a COCOON-BROWSER-ID parameter to identify which browser they are serving (as an alternative to using different stylesheets for each browser, by declaring <xsl:param as a top-level element in the stylesheet. IMPORTANT WARNING: If you use this alternative technique for a cacheable page, you MUST set the HTTP Vary header as follows: response.setHeader ("Vary", "user-Agent"); This can be done either in an <xsp:logic> element in XSP, or in a Processor. If you don't do this, it will work fine when users are connecting directly to the server, but if they access it through a web proxy, the proxy will not know that different content should be served for different browsers, so it will serve the same content for all browsers. (RDG) Thanks to
Ingo Bruell
.
Added manifest to w3c.jar to fix startup problem on JRun 3.0. (RDG) Thanks to
Torsten Curdt
.
Fixed command-line mode (again!) (RDG) Thanks to
Nicol?Lichtmaier
.
Fixed bug in Util.getAllPIs (RDG) Thanks to
Antonia Arena
. Fixes
bug 642
.
Fixed SVG sample for IE5.5. (RDG) Thanks to
David Cittadini
.
XSLTProcessor checks for null headers which previously caused errors. (RDG) Thanks to
Dafang Zhang
. Fixes
bug 541
.
LinkEncodingProcessor now encodes frames in framesets as well. (RDG)
Fixed Utils.getLocationResource to use parent ClassLoader instead of System ClassLoader, but fallback to System if resource not found. (RDG)
Changed default XSP encoding to UTF8, so that all characters are supported. (RDG)
Upgraded to Xerces 1.2.3 and Xalan 1.2.2 (RDG)
Removed DCP since it needed maintenance but no-one appears to be using it, and it is obsoleted by XSP. (RDG)
Added SAXONTransformer (DB) Thanks to
Steffen Stundzig
.
1.8.2 (January 26 2001)
Built with all options enabled, correcting the missing classes problem in the previous two releases. (RDG)
Fixed one of the xinclude samples; others are outdated and still use the old spec. (RDG) Thanks to
Sergio Carvalho
.
Added XMLFragment page to documentation. (RDG) Thanks to
Sylvain Wallez
.
Fixed JRun 3.0 installation instructions. (RDG) Thanks to
Roberto Viana
.
Fixed syntax errors in <request:is-user-in-role> (RDG) Thanks to
Werner Guttmann
.
response.sendRedirect no longer throws an Exception; processing is instead stopped inside the Cocoon Engine for that request, after this processor/producer returns. This is needed to fix a redirect problem with Tomcat (see below). (RDG)
Fixed undeclared var in <response:contains-header>. (RDG) Thanks to
Steffen Stundzig
.
Added notes on each jar, with details of which are required, to Installing documentation. (RDG)
Patched XSPProcessor - it was instantiating a XSPLogicSheet with sheetBase 'null', causing problems with SAXON. (DB) Thanks to
Steffen Stundzig
.
Patched XIncludeProcessor to handle non-DOM2 nodes resulting from XSLT transformation. (DB) Thanks to
Kirk Woerner
.
Patched FOP2PDFFormatter to work with JDK-1.1. (DB) Thanks to
Peter Haight
.
Patched XSPJavaPreprocessor for Xalan2. (RDG) Thanks to
Steffen Stundzig
.
1.8.1 (January 19 2001)
XSLTProcessor caching now ignores query string, as it should. (RDG) Thanks to
Wayne Bayever
.
Removed headers from cache key because this was breaking caching in 90% of static cases. This is a quick fix - will fix properly later. (RDG)
Added <?cocoon-disable-caching?> processing instruction to disable caching for a page. This is most useful for cases like samples/fp, which behaves strangely without it, because of Last-Modified support introduced in Cocoon 1.8.1. (RDG)
Obsolete XObject now replaced by org.apache.cocoon.xml.XMLFragment. This change was necessitated by the move to SAX2 in Cocoon 2. XObject is deprecated and will stop working in Cocoon 2. (RDG)
Reversed store cleanup algorithm mistake. The store cleanup thread now works exactly as before. (RDG)
At long last, FIXED the Internet Explorer PDF bug! In fact there were at least 3 bugs involved here, and YOU STILL NEED TO USE THE ?dummy=test.pdf WORKAROUND - see the FAQ for more details. But, generated PDF files now show up perfectly in all versions of Internet Explorer - as far as we know! (RDG)
Added EXPERIMENTAL support for xsp:variable declaration and code generation to xsp core logicsheet, and method calling to util taglib. This is designed to automatically pass through required environment variables such as xspCurrentNode. Need to uncomment the templates at the end of xsp-java.xsl to use this. (DB)
In esql, encoding is now an element not an attribute, to allow passthru. (DB)
Fixed second and third XSL:FO examples for FOP 0.15 conformance. (RDG) Thanks to
Steve Coffman
.
Added installation instructions for Inprise Application Server and Dynamo. (RDG) Thanks to
Michele Bianchi
.
Removed obsolete reference to ProducerFromRequest in EngineWrapper.java (RDG)
Fixes to Tomcat installation instructions. (RDG)
Fixes to Weblogic installation instructions. (RDG) Thanks to
Jamie Mascherino
.
Added very brief notes on ESQL to documentation (RDG)
Checked for NoSuchMethodError at XSPProcessor startup and added link to FAQ. If you don't want to use XSP and want to get rid of this error, just comment out XSP in cocoon.properties. (RDG)
Added user-agent option (-A) to command-line mode. (RDG) Thanks to
Ovidiu Predescu
.
Fixed command-line mode. (RDG) Thanks to
Ovidiu Predescu
.
Added multi-encoding support to esql. Even tables using multiple encodings can be read from! However, this will only work if your JDBC driver returns a byte array with the string in the given encoding when getBytes() is called. (RDG)
You can now override options in cocoon.properties, in web.xml or zone.properties. (RDG) Thanks to
Nicolas Lichtmaier
.
Workaround for Websphere classloader: URL handler bug (RDG) Thanks to
Berin Loritsch
.
Added encoding support to util:get-file-contents and various similar XSPUtil methods (RDG)
Fixed xsp:pi to add PI before document element instead of after. (RDG) Thanks to
Gerard Maas
.
Added LinkEncodingProcessor, designed to encode all links with session ids if necessary, using response.encodeUrl(). (RDG)
Added removeValue template and remove duplicate putValue template from session taglib, which should now be complete. (RDG) Thanks to
Corey O'Donovan
.
Passed extra parameters to style- and logic- sheets - XSP-ENVIRONMENT ("Cocoon 1.8.3-dev") and XSP-VERSION (1.0) (RDG) Thanks to
Donald Ball
.
Added inefficient workaround for using Xalan 1.x with FOP > 0.13. See src/org/apache/cocoon/formatter/FO2PDFFormatter.java. YOU NOW NEED FOP 0.14 OR GREATER TO BUILD COCOON, but earlier versions will still work as before at runtime. (RDG)
XSLTProcessor now invalidates its monitor whenever reapplying a stylesheet, in case the URI of the stylesheet being applied has changed since last time. Also, a second monitor is now used for cached stylesheets, for the same reason. This could be made more efficient. (RDG) Thanks to
Tagunov Anthony
.
Added HTTP Vary header to responses where a selection is made by Cocoon on the basis of a User-Agent header, in order to give correct proxy behaviour. (RDG)
Request headers (prefixed by R_) and cookies (prefixed by C_) are now passed to stylesheets, as well as request parameters. (RDG) Thanks to
Ovidiu Predescu
.
Made caching dependent on all request headers, not just user agent. (RDG) Thanks to
Ovidiu Predescu
.
Fixed XSLTProcessor and XalanTransformer to allow embedded stylesheets. (RDG)
Fixed response.sendRedirect problem with Tomcat. (RDG)
Renamed xsp:cacheable to util:cacheable because this is Cocoon-specific and should not be part of the core XSP namespace. (RDG) Thanks to
Matt Sergeant
.
New caching interface introduced - org.apache.cocoon.framework.Cacheable and corresponding xsp tag xsp:cacheable. Incomplete cacheing documentation page added. Requests that there is no point in cacheing, will now not be cached. This was partly in response to LastModified oddities, and partly to improve memory usage efficiency. (RDG)
*** NOTE - this was later reversed - see above! *** Made store cleanup algorithm more aggressive. Hopefully this should clear up some of the OutOfMemoryErrors people have been having. (RDG)
Workaround for an AbstractMethodError bug on some JDKs. (RDG) Thanks to
Mike Ehlers
.
Added ability for Engine components to implement org.apache.cocoon.framework.DestroyListener and be notified for cleanup purposes if/when the Cocoon servlet is destroyed. (RDG)
Fixed zombie caching bug where old versions of pages would reappear after certain errors. (RDG) Thanks to
Tagunov Anthony
.
Simple (manual!) contributions management system for contributions to Cocoon. See documentation. (RDG)
Added ability to get tailored Configurations for superclasses and support classes. (RDG)
Fixed XInclude problem with local absolute URLs. (RDG) Thanks to
Claude Warren
.
Cocoon will now stop with an error if any namespace-mapped logicsheet is not well-formed or missing, instead of just logging a warning message to the servlet logger and throwing a NPE when the logicsheet is invoked. This aids debugging. (RDG)
Line numbers are now reported in XML parsing errors. On some JDKs it may be necessary to put the sax-bugfix.jar before xerces.jar on the CLASSPATH. (RDG)
Added list of sites providing cocoon webhosting to docs. (RDG)
IMPORTANT: Made esql default to inner-method="false" since the inner-method facility is not always needed and causes confusion. (RDG)
Cocoon now sets a Last-Modified HTTP header based on the time the result was generated (either now or when the result was last changed in the cache). (RDG)
Fixed fp.xsl, to work better when mixed with other taglibs. (JQ) Thanks to
Konstantin Piroumian
.
Fixed fp.xsl, to hopefully allow use of config elements properly. (JQ)
Fixed XSPProcessor to pick up correct classpath and compile on Tomcat 3.3 and Catalina (Tomcat 4). (RDG) Thanks to
Paul Lamb
.
Added WebSphere installation script to docs. (RDG) Thanks to
Gordon Weakliem
.
Fixed slides sample to work on all browsers. (RDG)
Fixed package name problem in calendar taglib. (RDG)
New mail-archives page added in documentation (RDG)
Fixed XSPUtil.toMarkup to encode attributes correctly (RDG) Thanks to
Maik Schmidt
.
LDAP processor now accepts byte arrays without throwing a ClassCastException (RDG) Thanks to
Jeff Turner
.
Added installation instructions for JRun 3.0 (RDG) Thanks to
Mahe Vincent
.
Added installation instructions for BEA Weblogic Server 6.0 (beta) (RDG) Thanks to
James Scott
.
get-header-names now works in request taglib. (RDG) Thanks to
Drasko Kokic
.
Fixed so that XSLT document() function resolves correctly when two arguments used (RDG) Thanks to
Didier Villevalois
.
Fixed some stupid bugs in response taglib (RDG) Thanks to
Reichel Volker
.
added code to esql logicsheet to deal with queries that return an update count (DB)
fixed esql logicsheet - stack and session should only declare once now even when interacting with other logicsheets (DB)
updates to mail logicsheet - get flags, better parsed email address info, bug fixes (DB) Thanks to
Ugo Cei
.
Better error determination for Jikes. (RDG) Thanks to
Francisco Jr.
.
More informative exception information is now produced by taglibs. (RDG)
Turned off Xerces schema checking so that validation does not require a schema. (RDG) Thanks to
Gabi Brysch
.
Added put-value to session taglib for JServ compatibility. (RDG) Thanks to
Terry Paddy
.
Spaces are now trimmed from class names read from cocoon.properties (by Engine or Router) so that extra spaces won't create odd startup errors. (RDG) Thanks to
Hao Wang
.
Made xincludeprocessor default to parse="xml" (DB) Thanks to
Peter Verhage
.
Put heapsize line back into cocoon.properties (DB)
A doozy of a patch to esql - i made it so that you can execute queries either in their own special methods or inlined code - both on the same page even (can't imagine why you'd want to though) (DB)
A couple of bugs fixed in esql, plus i added the first bit of prepared statement support. Nothing but strings yet, but it works. (DB)
Changed default WML output encoding to iso-8859-1. (RDG) Thanks to
Marco Pauck
.
Improvements to mail logicsheet - specifically, now you can retrieve a set of messages by index, you can get the sent date, and some bugs were fixed. (DB) Thanks to
Ugo Cei
.
1.8 (September 22 2000)
Cleaned up docs, especially how-it-works and FAQ; added new questions and answers to FAQ. (RDG)
Changed XSPPage to only clone nodes where necessary, enhancing performance for complex pages. (RDG)
Changed <xsp:pi> back to use target= instead of name= in order not to break existing users' code (which there is a lot of!). Changed XSP docs to reflect correct usage. (RDG)
Added very primitive profiler (see cocoon.properties) (RDG)
Fixed some synchronization errors in Engine. You can now call a Cocoon page from a Cocoon page, if you really want (this is inefficient and a bad architecture, but it's possible.) (RDG)
Made response taglib work on Servlet API 2.0 engines (RDG)
Added xspdoc comments to esql logicsheet and added xspdoc to document convertor in the xml.apache.org site skin directory. god only knows how i'm supposed to add it to the build procedure... help? (DB)
Added error handling to esql logicsheet and documented its use in esql sample. (DB)
Fixed encoding problem with xinclude processor (DB) Thanks to
Tagunov Anthony
.
Fixed problem with XSP and PIs (now follows the correct name="xml-stylesheet" syntax) (SM) Thanks to
Kevin Sonney
.
Upgraded Xerces to 1.2 because previous version had a bug which meant it couldn't build the Cocoon documentation. (SM)
Added esql logicsheet (DB)
Upgraded xalan to 1_2_D02 (DB)
Added installation instructions for iPlanet. (SM) Thanks to
Paul Terray
.
Fixed a typo in session taglib (RR) Thanks to
Jens Lorenz
.
Added namespace preservation to Java code-generation taglib (RR)
Fixed a NPE in XIncludeProcessor on win32 systems (DB) Thanks to
Darren Smith
.
Added java compiler abstraction for XSP compilation (now we can use Jikes to improve XSP compilation speed). (SM) Thanks to
Juergen Sonnauer
.
Patched the cookie XSP taglib and the LDAP processor. (SM) Thanks to
Kevin Sonney
.
Implemented blocking in Engine to make Cocoon run better under heavy load. (SM) Thanks to
Mark Washeim
.
Added Solaris8 and improved Win2k installation case documentation. (SM) Thanks to
Mark Evans
.
Made XSP SQL processor do array to string conversion when using a Format object on a text column (DB)
Brought XInclude processor into conformance (mostly) with the 2000-07-17 version of the working draft. (DB)
Fixed problem with unresolved SystemID URIs that cause problems with latest Xerces. (SM)
Updated to latest Xerces and Xalan. (SM)
Included FP form-handling taglib for XSP. (SM) Thanks to
Jeremy Quinn
.
Fixed the bug that prevented compiled XSP to be cacheable with hasChanged(). (SM) Thanks to
Mark Washeim
.
Fixed the bug that xsp:expr does not accept DocumentFragments. (SM) Thanks to
Robin Green
.
Updated Cocoon installation case document. (SM) Thanks to
Mark Evans
.
Removed normalize-space from sql logicsheet's get-nested-string template (DB)
Changed turbine libraries to just include connection pool stuff, added connection pool docs (DB) Thanks to
Brian Millett
.
Fixed stupid bug in XInclude processor's handling of local files introduced in last patch (DB) Thanks to
John Morrison
.
Added connection pool (and turbine) to sql logicsheet (DB) Thanks to
Brian Millett
.
Added support for site-absolute links in xinclude processor (DB)
Fixed stupid bug in absolute href support in xinclude processor. also now set system ids on included xml resources. (DB) Thanks to
Ulrich Mayring
.
Fixed typo on util.xsl that generated XSP compilation problems for the util taglib. (SM) Thanks to
Matthias Brunner
.
Patched sql processor documentation to be fully up to date! Hoorah! (DB) Thanks to
Peter Seiderer
.
Added connection cache to sql processor (DB) Thanks to
Peter Seiderer
.
Disabled "created by cocoon" comment for HTTP HEAD requests. (DB) Thanks to
Jeremy Quinn
.
Added HTTP method to Utils.encode so HEAD and GET are distinguishable (DB) Thanks to
Jeremy Quinn
.
XIncludeProcessor now strips document type nodes from included documents (DB) Thanks to
Daniel Schneider
.
Added new installation case that should provide insights for newbies. (SM) Thanks to
Mark Evans
.
fixed null pointer exception in XIncludeProcessor. (DB) Thanks to
Antonio Cabezuelo Vivo
.
Added printer friendly skin so the documentation can now be generated to be printer friendly when needed. (stylesheets are pretty crappy right now, but hopefully some nice guy will improve them) (SM)
1.7.4 (May 19 2000)
fixed xpath position() problem that caused the slideshow example to behave strangely. Weird. (SM)
fixed a problem with memory store sweeping idle time declared as seconds and used as milliseconds which caused heavy CPU usage for undetectable misconfiguration. (SM) Thanks to
Kevin Burton
.
fixed bug in SQL taglib when doc-element was missing (DB)
fixed bug in SQL taglib's count rows query (DB) Thanks to
Giacomo Pati
.
Work around context.getRealPath() that fails on some engines. (SM) Thanks to
Bill Parkinson
.
Fixed problem with getResource() not implemented on some servlet engine. Now we test for Servlet 2.2 (SM) Thanks to
Paul Lamb
.
Fixed backslash escaping in text node strings (RR) Thanks to
Ulrich Mayring
.
Fixed invalid code for <util:include-file>. Added debug info to <util:include-uri> (RR) Thanks to
Ulrich Mayring
.
Added SVG formatting properties. (SM)
Changed behavior for absolute stylesheet hrefs which now point to absolute URI addresses. (SM)
Changed "create-session" attribute in <xsp:page> to accept only "true" and "false" as dictated by the XML Schema boolean datatype (RR) Thanks to
Kevin Burton
.
Added namespace preservation for XSP pages. To preserve namespaces in an XSP page, add an "xsp:xxx" attribute to the page's root element, where "xxx" is the namespace and the attribute value is the namespace URI (RR)
Added boolean attribute "create-session" to <xsp:page> in order to allow for the automatic creation of servlet sessions without intervening <xsp:logic> (RR)
Added "java.net.*" to the list of default XSP page Java imports (RR)
Added synchronization on code generation, compilation and loading (RR) Thanks to
Robin Green
.
Added support for charset encodings in code generation and compilation. Tested only with Russian under Blackdown's JDK1.2 (RR) Thanks to
Pavel Karassev
.
Fixed bug resulting in multiple <xsp:page> top elements (RR)
1.7.3 (May 5 2000)
Added code to XSLTProcessor to not import request parameters whose names are not valid XML Qnames and code to XalanTransformer to quote request parameter values to bypass the expression parsing routines. (DB)
Added column formatting to XSP SQL taglib. (DB)
Documented all XSP SQL taglib configuration options. (DB)
Added ability to recognize Servlet 2.1 container and get cocoon.properties as a ServletContext resource. This should ease installation on Tomcat. (SM) Thanks to
Paul Lamb
.
Cleaned the docs a little, fixed some typos and extended the cocoon2 sitemap example. (SM)
Patched engine creation to allow several instances of Cocoon in the same JVM. (SM) Thanks to
Manfred Riem
.
Added code to XSP SQL library to automatically choose execute update v.s. execute query (DB) Thanks to
Kevin Sonney
.
Added SMIL formatter. (SM)
Added XHTML formatter. (SM)
Fixed other encoding problems (hopefully last ones). (SM) Thanks to
Pawel Pesz
.
Updated build scripts (mostly esthetics for easier administration). (SM)
Fixed some typos and mistakes in documentation. (SM) Thanks to
Mike Rossellini
.
Fixed a problem with the cache monitor that was not updating the timestamp after a change so the cache was disabled after one of multiple stylesheets where updated. Now it works as expected. (SM)
Fixed possible encoding problem in stylesheet loading. (SM)
Updated Xalan to version 1.0.1. (SM)
Added new samples. (SM)
Fixed a problem with XSP where PIs contained the string
xsp
. (SM) Thanks to
Raphaël Luta
.
Fixed a problem with XSP packages containing dots and also fixes a problem with package generation. (SM) Thanks to
Roberto Moreda
. Fixes
bug 112
.
Improved error message when XSP repository directory is not writable. (SM) Fixes
bug 102
.
Added an improved memory store that checks for memory overflow in the background. (SM) Thanks to
Michel Lehon
.
Fixed a number of NPE when using Cocoon from the command line. (SM) Thanks to
Ovidiu Predescu
.
Fixed xsp:pi that now can work with included xsp:expr for dynamically generated PIs in XSP. (SM) Thanks to
Robin Green
.
Fixed xsp:expr [XSPPage.xspExpr()] to ensure that node values are created by the same document instance. (RR)
Fixed problem with Sun ProjectX compilation that failed on some platforms. (SM) Thanks to
Andrew Sheehan
.
Fixed problem with LDAP examples. (SM) Thanks to
James Birchfield
.
Fixed a problem with DocumentDTD that defined the "role" attribute twice and triggered validation problems on some parsers. (SM) Thanks to
Maurice Galland
.
Fixed a problem with document stylesheets that messed up anchors. (SM) Fixes
bug 91
.
Added ability to specify formatting information from the cocoon property file instead of having to create a custom formatter every time. Also fixed the output encoding problem since now a specific encoding for the output stream can be forced. (SM) Fixes
bug 90
.
Added XML encoding prediction to fix the encoding problem for ProducerFromFile. Cocoon should now work with all encoding supported by the XML parser used. (SM) Fixes
bug 83
.
Added ability to call "hasChanged" from inside the XSP engine to avoid dynamic page regeneration even XSP pages. (SM) Thanks to
Robin Green
.
1.7.2 (March 31 2000)
Changes prior to 1.7.2 are no longer listed in the docs - a fuller list may be found in changes.xml in the Cocoon distribution. (RDG) | http://cocoon.apache.org/1.x/changes.html | CC-MAIN-2015-27 | refinedweb | 3,925 | 61.33 |
curry = f => curried = (...args) => { if (args.length >= f.length) { return f(...args) } let outerArgs = args; return (...innerArgs) => { return curried(...outerArgs, ...innerArgs) } // We get 0 arguments? Let's not do this one } const f = (x, y, z) => x + y + z const g = curry(f) console.log("f(1, 2, 3): " + f(1, 2, 3)) console.log("g(1, 2, 3): " + g(1, 2, 3)) console.log("g(1)(2, 3): " + g(1)(2, 3)) console.log("g(1)(2)(3): " + g(1)(2)(3)) const k = (a, b, c, d, e, f) => a + b + c + d + e + f + " hi" const l = curry(k) console.log("l(3, 4, 5, 6, 7, 8):" + l(3, 4, 5, 6, 7, 8)); console.log("l(3)(4)(5, 6)(7, 8):" + l(3)(4)(5, 6)(7, 8));
Also see: Tab Triggers | https://codepen.io/niels_bom/pen/EdegGv?editors=0011 | CC-MAIN-2020-45 | refinedweb | 138 | 80.99 |
Introduction¶
bobtemplates.plone provides a mr.bob template to generate packages for Plone projects.
To create a package like
collective.myaddon:
$ pip install bobtemplates.plone $ mrbob -O collective.myaddon bobtemplates:plone_addon
You can also create a package with nested namespace:
$ mrbob -O collective.foo.myaddon bobtemplates:plone_addon
Options¶
On creating a package you can choose from the following options. The default value is in [square brackets]:
- Package Type? [Basic]
- Options are Basic, Dexterity and Theme.
- Author's name
- Should be something like 'John Smith'.
- Author's email
- Should be something like 'john@plone.org'.
- Author's github username
- Should be something like 'john'.
- Package description [An add-on for Plone]
- One-liner describing what this package does. Should be something like 'Plone add-on that ...'.
- Plone version [4.3.7]
- Which Plone version would you like to use?
Features¶
Package created with
bobtemplates.plone use the current best-practices when creating an addon.
- Buildout
- The package is contained in a buildout that allows you to build Plone with the new package installed for testing-purposes.
- Tests
- The package comes with a test setup and some tests for installing the package. It also contains a robot-test that tests logging in. The buildout also contains a config to allow testing the package on travis that sends notifications by email to the package autor.
- Profile
- The package contains a Generic Setup Profile that installs a browserlayer. For Plone 5 it also contains a uninstall-profile.
- Locales
- The package registers a directory for locales.
- Template-Overrides
- The package registers the folder
browser/overridesas a directory where you can drop template-overrides using z3c.jbot.
- Setuphandler
- The package contains a setuphandlers.py where you can add code that is executed on installing the package. For Plone 5 there is also a method in setuphandler.py that is run on uninstalling.
The package-types Dexterity and Theme add the following to Basic:
- Dexterity
- Adds a simple content-type (you get asked about its name) in
profiles/default/types/with a python-schema in
interfaces.py.
- Theme
- Adds a simple bootstrap-based Diazo theme in the folder
theme/and registers it in
profiles/default/theme.xml
Compatibility¶
Addons created with
bobtemplates.plone are tested to work in Plone 4.3.x and Plone 5.
They should also work with older versions but that was not tested.
It should work on Linux, Mac and Windows.
Installation¶
Use in a buildout¶
[buildout] parts += mrbob [mrbob] recipe = zc.recipe.egg eggs = mr.bob bobtemplates.plone
This creates a mrbob-executeable in your bin-directory.
Call it from the
src-directory of your Plone project like this.:
$ ../bin/mrbob -O collective.foo bobtemplates:plone_addon
Installation in a virtualenv¶ -O collective.foo bobtemplates:plone_addon
See mr.bob documentation for further information. | https://docs.plone.org/4/en/develop/addons/bobtemplates.plone/README.html?highlight=mrbob | CC-MAIN-2020-50 | refinedweb | 460 | 53.98 |
This module is just like regular Moo, except it also imports strictures and namespace::clean, along with a couple of standard types modules. In addition, it sweetens the Moo's has subroutine to allow for more concise attribute declarations....ZOFFIX/Mew-1.001005 - 06 Dec 2015 13:35
- Moops::Manual::Objects101 - an introduction to object oriented programming using Moops
*Vim::X* provides two tools to make writing Perl functions for Vim a little easier: it auto-exports functions tagged by the attribute ":Vim" in Vim-space, and it defines a slew of helper functions and objects that are a little more *Do What I Mean* t...YANICK/Vim-X-1.3.0 - 17 Nov 2015 02:30:16 GMT - Search in distribution
tr...INGY/Spiffy-0.46 1(3 reviews) - 16 Aug 2014 19:19:54 GMT - Search in distribution
DBD::Pg is a Perl module that works with the DBI module to provide access to PostgreSQL databases....TURNSTEP/DBD-Pg-3.5.3 4(12 reviews) - 01 Oct 2015 14:06:04 GMT - Search in distributionthrtut - Tutorial on threads in Perl...JSTOWE/XML-XSLT-0.48 - 20 Feb 2004 08:45:38
"dlock" makes the specified variable immutable like Readonly. Unlike Readonly which implements immutability via "tie", "dlock" makes use of the internal flag of perl SV so it imposes almost no penalty. Like Readonly, "dlock" locks not only the variab...DANKOGAI/Data-Lock-1.03 - 07 Mar 2014 18:28:20 5(4 reviews) - 15 Apr 2015 09:01:31 GMT - Search in distribution
Amazon Elastic Compute Cloud Amazon Elastic Compute Cloud (Amazon EC2) provides resizable computing capacity in the Amazon Web Services (AWS) cloud. Using Amazon EC2 eliminates your need to invest in hardware up front, so you can develop and deploy a...JLMARTIN/Paws-0.21 - 15 Dec 2015 23:31:16 GMT - Search in distribution
This class exists to provide a way for quick and sloppy prototyping of a web application. It is a wrapper for Kelp, which imports several keywords, making it easier and less verbose to create a quick web app. It's called "Less", because there is less...MINIMAL/Kelp-0.9071 5(3 reviews) - 11 Aug 2015 06:50:14 GMT - Search in distribution
JENDA/XML-Rules-1.16 5(1 review) - 13 Dec 2012 21:20:26 GMT - Search in distribution - Search in distribution | https://metacpan.org/search?q=Attribute-Imports | CC-MAIN-2016-07 | refinedweb | 394 | 51.28 |
Thanks to everyone that attended today's webcast session on class libraries with Visual Basic .NET. Today was Part 3 of the 22-part webcast series, Visual Basic .NET Soup to Nuts.
Here are some resources for this webcast:
We also showed some tools you get when you download the .NET Framework SDK. You can download SDKs (and other stuff) from here. Also, be sure to visit the .NET Framework Developer Center.
From these two sites, you can drill into the documentation for the .NET Framework and Visual Basic. For instance, we talked about the System Namespace today, and here's the documentation for it. You may also want to review the namespace naming guidelines for guidance on how to name your own namespaces in your custom class libraries.
I also showed how the My Namespace in Visual Basic 2005 makes it easier to include common functionality in our apps. Read more about the My Namespace here.
Happy coding! | http://blogs.msdn.com/b/ron_cundiff/archive/2007/02/19/visual-basic-net-soup-to-nuts-webcast-series-part-3-class-libraries-wrap-up.aspx | CC-MAIN-2015-22 | refinedweb | 159 | 68.67 |
I am not sure if that is feasible, but I need to cast a function pointer to long in order to map C level code back to java code.
a pointer's value is a integer,you just need know what exactly you are doing and alloc enough storage to store the pointer's value.(int a 32bit os,pointer occupy 32bit storage,int a 64bit os,pointer occupy 64bit storage).
a c example:
#include <stdio.h> void fun() { printf("fun\n"); return; } typedef void (*fun_type)(); int main() { long long int a = (long long int)fun; fun_type func_point = (fun_type)a; func_point(); return 0; } | https://codedump.io/share/6Gl3CVkuuWT9/1/cast-a-function-pointer-to-a-long | CC-MAIN-2017-04 | refinedweb | 103 | 61.46 |
We can write value inside a cell in a worksheet in Selenium. Excel is a spreadsheet which is saved with the .xlsx extension. An excel workbook has multiple sheets and each sheet consists of rows and columns.
Out of all the worksheets, while we are accessing a particular sheet that is called as an active sheet. Each cell inside a sheet has a unique address which is a combination of row and column numbers.
The column number starts from alphabetic character A and row number starts from the number 1. A cell can contain numerous types of values and they are the main component of a worksheet.
To work with excel in Selenium with python, we need to take help of OpenPyXL library. This library is responsible for reading and writing operations on Excel, having the extensions like xlsx, xlsm, xltm, xltx.
To install OpenPyXL library, we have to execute the command pip install openpyxl. This is because OpenPyXL does not come by default with python. After this we should import openpyxl in our code and then we should be ready to interact with excel.
To write the value inside the worksheet, first of all we need to load the entire workbook by specifying the path where it is located. This is achieved with load_workbook() method. Next we need to identify the active sheet among all the worksheets with the help of active method.
To access a cell inside the active worksheet, we need the help of row and column number and the cell method [which accepts the row and column number as arguments]. For example, to point to the cell corresponding to row 2 and column 3, we need to mention sheet.cell(row=2,column=3).
After identification of the cell, we need to use a value method to set the value inside the cell.
wrkbk = load_workbook("C:\\work\\SeleniumPython.xlsx") # to identify the active sheet sh = wrkbk.active # identify the cell row 2 and column 3 c=sh.cell(row=2,column=3) # set the value in row 2 and column 3 sh.cell(row=2,column=3).value = "Tutorialspoint"
Coding Implementation to set value in a particular cell.
import openpyxl # load excel with its path wrkbk = load_workbook("C:\\work\\SeleniumPython.xlsx") # to get the active work sheet sh = wrkbk.active # get the value of row 2 and column 3 c=sh.cell(row=2,column=3) # to set the value in row 2 and column 3 sh.cell(row=2,column=3).value = "Tutorialspoint" | https://www.tutorialspoint.com/how-to-write-value-inside-a-cell-in-a-worksheet-in-selenium-with-python | CC-MAIN-2022-21 | refinedweb | 418 | 56.66 |
This chapter covers the most basic (X)HTML elementst" " loose.dtd">:
If desired, type <?xml version="1.0" encoding="UTF-8"?> to declare that your document is an XML document and that its encoding is UTF-8.
Type <!DOCTYPE html PUBLIC "-//W3C //DTD XHTML 1.0 Transitional//EN" " xhtml1-transitional.dtd"> to declare that you're using transitional XHTML in your Web page.
Type <html xmlns=" 1999/xhtml"> to begin the XHTML portion of your page and declare its namespace.
Leave a few spaces for creating the rest of your page (using the rest of this book).
Type </html>.
Tips
Both the DOCTYPE and the html element are optional in HTML (even strict HTML). XHTML requires both (with the name-space declaration in the opening html tag). Note that there is no xhtml element.
Figure 3.2 Here's the DOCTYPE for a transitional XHTML document, the opening html tag and required namespace declaration, and the closing html tag. Ugh!
I've only shown how to write the DOCTYPE for transitional HTML and XHTML. You can find a list of common DOCTYPE declarations on my Web site (see page 24) or at. For help choosing an appropriate DOCTYPE, see page 38.
Create a template with the appropriate DOCTYPE declaration and html tag as a starting point for all your pages.
Declaring a DOCTYPE with a URL at the top of your Web page generally puts current browsers in standards modeletting you use standards-compliant code in order to have more control over the display of your Web page (see page 39).
If you start an XHTML page with the xml declaration, IE 6 for Windows goes into quirks mode. That's a huge bug. The workaround? Skip the (optional) declaration and declare the encoding with the meta tag instead (see page 63) .
If you use non-standard HTML tags, there's no point in specifying a DOCTYPE. Just enclose your page in opening and closing html tags. Current browsers will use quirks mode when displaying your pages, letting you take advantage of old, soon-to-be-obsolete bugs (see page 39).
Declaring the appropriate DOCTYPE tells validators which specifications to compare your code against (see page 394).
Note that the word DOCTYPE (since it actually originated from another language called SGML) is typed in all uppercase letters, both in HTML and in XHTML.
Find extra tips, the source code for examples, and more at | http://www.peachpit.com/articles/article.aspx?p=31340&seqNum=6 | CC-MAIN-2018-26 | refinedweb | 404 | 73.58 |
What’s New In Python 3.4
This article explains the new features in Python 3.4, compared to 3.3. Python 3.4 was released on March 16, 2014. For full details, see the changelog.
Summary – Release Highlights
New syntax features:
- No new syntax features were added in Python 3.4.
Other new features:
- pip should always be available (PEP 453).
- Newly created file descriptors are non-inheritable (PEP 446).
- command line option for isolated mode (issue 16499).
- improvements in the handling of codecs that are not text encodings (multiple issues).
- A ModuleSpec Type for the Import System (PEP 451). (Affects importer authors.)
- The marshal format has been made more compact and efficient (issue module primitives (part of PEP 3156).
- statistics: A basic numerically stable statistics library (PEP 450).
- tracemalloc: Trace Python memory allocations (PEP 454).
Significantly improved library modules:
- Single-dispatch generic functions in functools (PEP 443).
- New pickle protocol 4 (PEP 3154).
- multiprocessing now has an option to avoid using os.fork on Unix (issue 8713).
- email has a new submodule, contentmanager, and a new Message subclass (EmailMessage) that simplify MIME handling (issue 18891).
- The inspect and pydoc modules are now capable of correct introspection of a much wider variety of callable objects, which improves the output of the Python help() system.
- The ipaddress module API has been declared stable
Security improvements:
- Secure and interchangeable hash algorithm (PEP 456).
- Make newly created file descriptors non-inheritable (PEP 446) to avoid leaking file descriptors to child processes.
- New command line option for isolated mode, (issue 16499).
- multiprocessing now has an option to avoid using os.fork on Unix. spawn and forkserver are more secure because they avoid sharing data with child processes.
- multiprocessing child class (issue 18214).
- Configurable memory allocators (PEP 445).
- Argument Clinic (PEP 436).
Please read on for a comprehensive list of user-facing changes, including many other smaller improvements, CPython optimizations, deprecations, and potential porting issues.
New Features
PEP 453: Explicit Bootstrapping of PIP in Python Installations
Bootstrapping pip By Default issue 7475, issue 17827, issue 17828 and issue 19619)
PEP 451: A ModuleSpec Type for the Import System issue 18111.)
- Module objects are now weakref‘able.
- Module __file__ attributes (and related values) should now always contain absolute paths by default, with the sole exception of __main__.__file__ when a script has been executed directly using a relative path (Contributed by Brett Cannon in issue 18416).
- All the UTF-* codecs (except UTF-7) now reject surrogates during both encoding and decoding unless the surrogatepass error issue 12892.
- New German EBCDIC codec cp273. (Contributed by Michael Bierenfeld and Andrew Kuchling in issue 1097797.)
- New Ukrainian codec cp1125. (Contributed by Serhiy Storchaka in issue 19668.)
- bytes.join() and bytearray.join() now accept arbitrary buffer objects as arguments. (Contributed by Antoine Pitrou in issue 15958.)
- The int constructor now accepts any object that has an __index__ method for its base argument. (Contributed by Mark Dickinson in issue 16772.)
- Frame objects now have a clear() method that clears all references to local variables from the frame. (Contributed by Antoine Pitrou in issue 17934.)
- memoryview is now registered as a Sequence, and supports the reversed() builtin. (Contributed by Nick Coghlan and Claudiu Popa in issue 18690 and issue 19078.)
- Signatures reported by help() have been modified and improved in several cases as a result of the introduction of Argument Clinic and other changes to the inspect and pydoc modules.
- __length_hint__() is now part of the formal language specification (see PEP 424). (Contributed by Armin Ronacher in issue 16148.)
New Modules
asyncio
The new enum module (defined in PEP 435) provides a standard implementation of enumeration types, allowing other modules (such as socket) to provide more informative error messages and better debugging support by replacing opaque integer constants with backwards compatible enumeration values.
pathlib
The new selectors module (created as part of implementing PEP 3156) allows high-level and efficient I/O multiplexing, built upon the select module primitives.
statistics
The new statistics module (defined in PEP 450) offers some core statistics functionality directly in the standard library. This module supports calculation of the mean, median, mode, variance and standard deviation of a data series.
tracemalloc
abc
New function abc.get_cache_token() can be used to know when to invalidate caches that are affected by changes in the object graph. (Contributed by Łukasz Langa in issue issue 16049.)
aifc
The getparams() method now returns a namedtuple rather than a plain tuple. (Contributed by Claudiu Popa in issue 17818.)
aifc.open() now supports the context manager protocol: when used in a with block, the close() method of the returned object will be called automatically at the end of the block. (Contributed by Serhiy Storchacha in issue 16486.)
The writeframesraw() and writeframes() methods now accept any bytes-like object. (Contributed by Serhiy Storchaka in issue 8311.)
argparse
The FileType class now accepts encoding and errors arguments, which are passed through to open(). (Contributed by Lucas Maystre in issue 11175.)
audioop
audioop now supports 24-bit samples. (Contributed by Serhiy Storchaka in issue 12866.)
New byteswap() function converts big-endian samples to little-endian and vice versa (Contributed by Serhiy Storchaka in issue 19641).
All audioop functions now accept any bytes-like object. Strings are not accepted: they didn’t work before, now they raise an error right away. (Contributed by Serhiy Storchaka in issue 16685.)
base64
The encoding and decoding functions in base64 now accept any bytes-like object in cases where it previously required a bytes or bytearray instance. (Contributed by Nick Coghlan in issue issue 17618.)
collections
The ChainMap.new_child() method now accepts an m argument specifying the child map to add to the chain. This allows an existing mapping and/or a custom mapping type to be used for the child. (Contributed by Vinay Sajip in issue 16613.)
colorsys issue 14323.)
contextlib
The new contextlib.suppress context manager helps to clarify the intent of code that deliberately suppresses exceptions from a single statement. (Contributed by Raymond Hettinger in issue 15806 and Zero Piraeus in issue issue 15805)
The contextlib documentation has also been updated to include a discussion of the differences between single use, reusable and reentrant context managers.
dbm
dbm.open() objects now support the context management protocol. When used in a with statement, the close method of the database object will be called automatically at the end of the block. (Contributed by Claudiu Popa and Nick Coghlan in issue 19282.)
dis issue 11816 and Claudiu Popa in issue 17916)
New function stack_effect() computes the effect on the Python stack of a given opcode and argument, information that is not otherwise available. (Contributed by Larry Hastings in issue 19722.)
doctest
A new option flag, FAIL_FAST, halts test running as soon as the first failure is detected. (Contributed by R. David Murray and Daniel Urban in issue issue 11390.)
doctest will now find doctests in extension module __doc__ strings. (Contributed by Zachary Ware in issue issue 18600.)
New method as_bytes() added to produce a bytes representation of the message in a fashion similar to how as_string produces a string representation. It does not accept the maxheaderlen argument, but does accept the unixfrom and policy arguments. The Message __bytes__() method calls it, meaning that bytes(mymsg) will now produce the intuitive result: a bytes object containing the fully formatted message. (Contributed by R. David Murray in issue 18600.)
The Message.set_param() message now accepts a replace keyword argument. When specified, the associated header will be updated without changing its location in the list of headers. For backward compatibility, the default is False. (Contributed by R. David Murray in issue 18891.)
A pair of new subclasses of Message have been added (EmailMessage and Examples using the Provisional API. issue 18891.)
filecmp issue 18149.)
New module attribute DEFAULT_IGNORES provides the list of directories that are used as the default value for the ignore parameter of the dircmp() function. (Contributed by Eli Bendersky in issue 15442.)
functools issue issue 10042.)
A pure-python version of the partial() function is now in the stdlib; in CPython it is overridden by the C accelerated version, but it is available for other implementations to use. (Contributed by Brian Thorne in issue 12428.)
gc
New function get_stats() returns a list of three per-generation dictionaries containing the collections statistics since interpreter startup. (Contributed by Antoine Pitrou in issue 16351.)
glob
A new function escape() provides a way to escape special characters in a filename so that they do not become part of the globbing expansion but are instead matched literally. (Contributed by Serhiy Storchaka in issue 8402.)
hashlib
A new hashlib.pbkdf2_hmac() function provides the PKCS#5 password-based key derivation function 2. (Contributed by Christian Heimes in issue issue 18532.)
hmac issue issue 17276.)
With the addition of block_size and name attributes (and the formal documentation of the digest_size attribute), the hmac module now conforms fully to the PEP 247 API. (Contributed by Christian Heimes in issue 18775.)
html
New function unescape() function converts HTML5 character references to the corresponding Unicode characters. (Contributed by Ezio Melotti in issue issue 13633)
The strict argument of HTMLParser is now deprecated. (Contributed by Ezio Melotti in issue 15114)
http issue 12921.)
The http.server command line interface now has a -b/--bind option that causes the server to listen on a specific address. (Contributed by Malte Swart in issue 17764.)
importlib
The InspectLoader ABC defines a new method, source_to_code() that accepts source data and a path and returns a code object. The default implementation is equivalent to compile(data, path, 'exec', dont_inherit=True). (Contributed by Eric Snow and Brett Cannon in issue 15627.)
InspectLoader also now has a default implementation for the get_code() method. However, it will normally be desirable to override the default implementation for performance reasons. (Contributed by Brett Cannon in issue 18072.)
The reload() function has been moved from imp to importlib as part of the imp module deprecation. (Contributed by Berker Peksag in issue 18193.)
importlib.util now has a MAGIC_NUMBER attribute providing access to the bytecode version number. This replaces the get_magic() function in the deprecated imp module. (Contributed by Brett Cannon in issue 18192.)
New importlib.util functions cache_from_source() and source_from_cache() replace the same-named functions in the deprecated imp module. (Contributed by Brett Cannon in issue 18194.)
The importlib bootstrap NamespaceLoader now conforms to the InspectLoader ABC, which means that runpy and python -m can now be used with namespace packages. (Contributed by Brett Cannon in issue issue 19152.)
inspect
The inspect module now offers a basic command line interface to quickly display source code and other information for modules, classes and functions. (Contributed by Claudiu Popa and Nick Coghlan in issue 18626)
unwrap() makes it easy to unravel wrapper function chains created by functools.wraps() (and any other API that sets the __wrapped__ attribute on a wrapper function). (Contributed by Daniel Urban, Aaron Iles and Nick Coghlan in issue 13266)
As part of the implementation of the new enum module, the inspect module now has substantially better support for custom __dir__ methods and dynamic class attributes provided through metaclasses (Contributed by Ethan Furman in issue 18929 and issue issue 17481)
signature() now supports duck types of CPython functions, which adds support for functions compiled with Cython. (Contributed by Stefan Behnel and Yury Selivanov in issue 17159)
ipaddress issue 17400.)
logging
The TimedRotatingFileHandler has a new atTime parameter that can be used to specify the time of day when rollover should happen. (Contributed by Ronald Oussoren in issue issue 16110.)
Logging configuration data received from a socket via the logging.config.listen() function can now be validated before being processed by supplying a verification function as the argument to the new verify keyword argument. (Contributed by Vinay Sajip in issue 15452.)
marshal issue 16475, with additional speedups by Antoine Pitrou in issue 19219.)
mmap
mmap objects can now be weakrefed. (Contributed by Valerie Lambert in issue 4885.)
multiprocessing issue issue 18999.)
Except when using the old fork start method, child processes no longer inherit unneeded handles/file descriptors from their parents (part of issue issue 19946)
operator
New function length_hint() provides an implementation of the specification for how the __length_hint__() special method should be used, as part of the PEP 424 formal specification of this language feature. (Contributed by Armin Ronacher in issue 16148.)
There is now a pure-python version of the operator module available for reference and for use by alternate implementations of Python. (Contributed by Zachary Ware in issue 16694.)
os issue 17914.)
os.path.samestat() is now available on the Windows platform (and the os.path.samefile() implementation is now shared between Unix and Windows). (Contributed by Brian Curtin in issue 11939.)
os.path.ismount() now recognizes volumes mounted below a drive root on Windows. (Contributed by Tim Golden in issue issue 18673 and Benjamin Peterson, respectively.)
pdb
pdb.)
pickle issue 14455).
poplib issue 4473.)
pprint issue 19132.)
Long strings are now wrapped using Python’s normal line continuation syntax. (Contributed by Antoine Pitrou in issue 17150).
pty
pty.spawn() now returns the status value from os.waitpid() on the child process, instead of None. (Contributed by Gregory P. Smith.)
pydoc issue 19674)
The pydoc module no longer displays the self parameter for already bound methods. Instead, it aims to always display the exact current signature of the supplied callable (Contributed by Larry Hastings in issue help().
re issue issue 13592 and issue 17087.)
resource issue 16595.)
On Linux kernel version 2.6.36 or later, there are there are also some new Linux specific constants: RLIMIT_MSGQUEUE, RLIMIT_NICE, RLIMIT_RTPRIO, RLIMIT_RTTIME, and RLIMIT_SIGPENDING. (Contributed by Christian Heimes in issue 19324.)
On FreeBSD version 9 and later, there some new FreeBSD specific constants: RLIMIT_SBSIZE, RLIMIT_SWAP, and RLIMIT_NPTS. (Contributed by Claudiu Popa in issue 19343.)
epoll objects now support the context management protocol. When used in a with statement, the close() method will be called automatically at the end of the block. (Contributed by Serhiy Storchaka in issue 16488.)
devpoll objects now have fileno() and close() methods, as well as a new attribute closed. (Contributed by Victor Stinner in issue 18794.)
shelve
Shelf instances may now be used in with statements, and will be automatically closed at the end of the with block. (Contributed by Filip Gruszczyński in issue 13896.)
shutil
copyfile() now raises a specific Error subclass, SameFileError, when the source and destination are the same file, which allows an application to take appropriate action on this specific error. (Contributed by Atsuo Ishimoto and Hynek Schlawack in issue 1492704.)
smtpd issue 11959.)
smtplib issue 2118).
socket
The socket module now supports the CAN_BCM protocol on platforms that support it. (Contributed by Brian Thorne in issue issue 7171.)
sqlite3
A new boolean parameter to the connect() function, uri, can be used to indicate that the database parameter is a uri (see the SQLite URI documentation). (Contributed by poq in issue 13773.)
ssl issue issue 19689.)
SSLContext method load_verify_locations() accepts a new optional argument cadata, which can be used to provide PEM or DER encoded certificates directly via strings or bytes, respectively. (Contributed by Christian Heimes in issue issue issue 18147.)
If OpenSSL 0.9.8 or later is available, SSLContext has issue 8813.)
New SSLContext method load_default_certs() loads a set of dfault issue 19292.)
Two new windows-only functions, enum_certificates() and enum_crls() provide the ability to retrieve certificates, certificate information, and CRLs from the Windows cert store. (Contributed by Christian Heimes in issue 17134.)
Support for server-side SNI (Server Name Indication) using the new ssl.SSLContext.set_servername_callback() method. (Contributed by Daniel Black in issue 8109.)
The dictionary returned by SSLSocket.getpeercert() contains additional X509v3 extension items: crlDistributionPoints, calIssuers, and OCSP URIs. (Contributed by Christian Heimes in issue 18379.)
stat
The stat module is now backed by a C implementation in _stat. A C implementation is required as most of the values aren’t standardized and are platform-dependent. (Contributed by Christian Heimes in issue 11016.)
The module supports new ST_MODE flags, S_IFDOOR, S_IFPORT, and S_IFWHT. (Contributed by Christian Hiemes in issue 11016.)
struct
New function iter_unpack and a new struct.Struct.iter_unpack() method on compiled formats provide streamed unpacking of a buffer containing repeated instances of a given format of data. (Contributed by Antoine Pitrou in issue 17804.)
subprocess
check_output() now accepts an input argument that can be used to provide the contents of stdin for the command that is run. (Contributed by Zack Weinberg in issue 16624.)
getstatus() and getstatusoutput() now work on Windows. This change was actually inadvertently made in 3.3.4. (Contributed by Tim Golden in issue 10197.)
sunau
The getparams() method now returns a namedtuple rather than a plain tuple. (Contributed by Claudiu Popa in issue 18901.)
sunau.open() now supports the context manager protocol: when used in a with block, the close method of the returned object will be called automatically at the end of the block. (Contributed by Serhiy Storchaka in issue 18878.)
AU_write.setsampwidth() now supports 24 bit samples, thus adding support for writing 24 sample using the module. (Contributed by Serhiy Storchaka in issue 19261.)
The writeframesraw() and writeframes() methods now accept any bytes-like object. (Contributed by Serhiy Storchaka in issue 8311.)
sys issue issue 5845.)
tarfile
The tarfile module now supports a simple Command Line Interface when called as a script directly or via -m. This can be used to create and extract tarfile archives. (Contributed by Berker Peksag in issue 13477.)
textwrap issue 18585 and issue 18725.)
threading
The Thread object representing the main thread can be obtained from the new main_thread() function. In normal conditions this will be the thread from which the Python interpreter was started. (Contributed by Andrew Svetlov in issue 18882.)
traceback
A new traceback.clear_frames() function takes a traceback object and clears the local variables in all of the frames it references, reducing the amount of memory consumed. (Contributed by Andrew Kuchling in issue 1565525).
types issue 19030.)
urllib
urllib.request now supports data: URLs via the DataHandler class. (Contributed by Mathias Panzenböck in issue 16423.)
The http method that will be used by a Request class can now be specified by setting a method class attribute on the subclass. (Contributed by Jason R Coombs in issue‘s url rather than recomputing it from scratch. There is also a new remove_header() method that can be used to remove headers from a Request. (Contributed by Alexey Kachayev in issue 16464, Daniel Wozniak in issue 17485, and Damien Brecht and Senthil Kumaran in issue 17272.)
HTTPError objects now have a headers attribute that provides access to the HTTP response headers associated with the error. (Contributed by Berker Peksag in issue 15701.)
unittest issue 16997.)
unittest.main() now accepts an iterable of test names for defaultTest, where previously it only accepted a single test name as a string. (Contributed by Jyrki Pulliainen in issue 15132.)
If SkipTest is raised during test discovery (that is, at the module level in the test file), it is now reported as a skip instead of an error. (Contributed by Zach Ware in issue 16935.)
discover() now sorts the discovered files to provide consistent test ordering. (Contributed by Martin Melin and Jeff Ramnani in issue issue issue 18937.)
Test discovery now works with namespace packages (Contributed by Claudiu Popa in issue 17457.)
unittest.mock objects now inspect their specification signatures when matching calls, which means an argument can now be matched by either position or name, instead of only by position. (Contributed by Antoine Pitrou in issue 17015.)
mock_open() objects now have readline and readlines methods. (Contributed by Toshio Kuratomi in issue 17467.)
venv
venv now includes activation scripts for the csh and fish shells (Contributed by Andrew Svetlov in issue 15417.)
EnvBuilder and the create() convenience function take a new keyword argument with_pip, which defaults to False, that controls whether or not EnvBuilder ensures that pip is installed in the virtual environment. (Contributed by Nick Coghlan in issue 19552 as part of the PEP 453 implementation.)
wave
The getparams() method now returns a namedtuple rather than a plain tuple. (Contributed by Claudiu Popa in issue 17487.)
wave.open() now supports the context manager protocol. (Contributed by Claudiu Popa in issue 17616.)
wave can now write output to unseekable files. (Contributed by David Jones, Guilherme Polo, and Serhiy Storchaka in issue 5202.)
The writeframesraw() and writeframes() methods now accept any bytes-like object. (Contributed by Serhiy Storchaka in issue 8311.)
weakref
New WeakMethod class simulates weak references to bound methods. (Contributed by Antoine Pitrou in issue 14631.)
New finalize class makes it possible to register a callback to be invoked when an object is garbage collected, without needing to carefully manage the lifecycle of the weak reference itself. (Contributed by Richard Oudkerk in issue 15528)
The callback, if any, associated with a ref is now exposed via the __callback__ attribute. (Contributed by Mark Dickinson in issue 17643.)
xml.etree
A new parser, XMLPullParser, allows a non-blocking applications to parse XML documents. An example can be seen at Pull API for non-blocking parsing. (Contributed by Antoine Pitrou in issue issue 14377.)
zipfile issue 19274.)
The allowZip64 parameter to ZipFile and PyZipfile is now True by default. (Contributed by William Mallard in issue 17201.)
CPython Implementation Changes
PEP 445: Customization of CPython Memory Allocators
PEP 445 adds new C level interfaces to customize memory allocation in the CPython interpreter.
PEP 442: Safe Object Finalization
PEP 456 follows up on earlier security fix work done on Python’s hash algorithm to address certain DOS attacks to which public facing APIs backed by dictionary lookups may be subject. (See issue
- The new PyType_GetSlot() function has been added to the stable ABI, allowing retrieval of function pointers from named type slots when using the limited API. (Contributed by Martin von Löwis in issue 17162)
- The new Py_SetStandardStreamEncoding() pre-initialization API allows applications embedding the CPython interpreter to reliably force a particular encoding and error handler for the standard streams (Contributed by Bastien Montagne and Nick Coghlan in issue 16129)
- Most Python C APIs that don’t mutate string arguments are now correctly marked as accepting const char * rather than char * (Contributed by Serhiy Storchaka in issue 1772673).
- A new shell version of python-config can be used even when a python interpreter is not available (for example, in cross compilation scenarios).
- PyUnicode_FromFormat() now supports width and precision specifications for %s, %A, %U, %V, %S, and %R. (Contributed by Ysj Ray and Victor Stinner in issue 7330.)
- New function PyStructSequence_InitType2() supplements the existing PyStructSequence_InitType() function. The difference is that it returns 0 on success and -1 on failure.
- The CPython source can now be compiled using the address sanity checking features of recent versions of GCC and clang: the false alarms in the small object allocator have been silenced. (Contributed by Dhiru Kholia in issue 18596.)
- The Windows build now uses Address Space Layout Randomization and Data Execution Prevention. (Contributed by Christian Heimes in issue 16632.)
- New function PyObject_LengthHint() is the C API equivalent of operator.length_hint(). (Contributed by Armin Ronacher in issue 16148.)
Other Improvements
- The python command has a new option, -I, which causes it to run in “isolated mode”, which means that sys.path contains neither the script’s directory nor the user’s site-packages directory, and all PYTHON* environment variables are ignored (it implies both -s and issue issue 5845.)
- Invoking the Python interpreter with --version now outputs the version to standard output instead of standard error (issue 18338). Similar changes were made to argparse (issue 18920) and other modules that have script-like invocation capabilities (issue 18922).
- The CPython Windows installer now adds .py to the PATHEXT variable when extensions are registered, allowing users to run a python script at the windows command prompt by just typing its name without the .py extension. (Contributed by Paul Moore in issue 18569.)
- A new make target coverage-report will build python, run the test suite, and generate an HTML coverage report for the C codebase using gcov and lcov.
- The -R option to the python regression test suite now also checks for memory allocation leaks, using sys.getallocatedblocks(). (Contributed by Antoine Pitrou in issue 13390).
- python -m now works with namespace packages.
- The stat module issue 16421.)
- A new opcode, LOAD_CLASSDEREF, has been added to fix a bug in the loading of free variables in class bodies that could be triggered by certain uses of __prepare__. (Contributed by Benjamin Peterson in issue 17853.)
- A number of MemoryError-related crashes were identified and fixed by Victor Stinner using his PEP 445-based pyfailmalloc tool (issue 18408, issue 18520).
- The pyvenv command now accepts a --copies option to use copies rather than symlinks even on systems where symlinks are the default. (Contributed by Vinay Sajip in issue 18807.)
- The pyvenv command also accepts a --without-pip option to suppress the otherwise-automatic bootstrapping of pip into the virtual environment. (Contributed by Nick Coghlan in issue 19552 as part of the PEP 453 implementation.)
- The encoding name is now optional in the value set for the PYTHONIOENCODING environment variable. This makes it possible to set just the error handler, without changing the default encoding. (Contributed by Serhiy Storchaka in issue 18818.)
- The bz2, lzma, and gzip module open functions now support x (exclusive creation) mode. (Contributed by Tim Heaney and Vajrasky Kok in issue 19201, issue 19222, and issue 19223.)
Significant Optimizations
- The UTF-32 decoder is now 3x to 4x faster. (Contributed by Serhiy Storchaka in issue issue 18771.)
- The interpreter starts about 30% faster. A couple of measures lead to the speedup. The interpreter loads fewer modules on startup, e.g. the re, collections and locale modules and their dependencies are no longer imported by default. The marshal module has been improved to load compiled Python code faster. (Contributed by Antoine Pitrou, Christian Heimes and Victor Stinner in issue 19219, issue 19218, issue 19209, issue 19205 and issue 9548)
- bz2.BZ2File is now as fast or faster than the Python2 version for most cases. lzma.LZMAFile has also been optimized. (Contributed by Serhiy Storchaka and Nadeem Vawda in issue 16034.)
- random.getrandbits() is 20%-40% faster for small integers (the most common use case). (Contributed by Serhiy Storchaka in issue 16674).
- By taking advantage of the new storage format for strings, pickling of strings is now significantly faster. (Contributed by Victor Stinner and Antoine Pitrou in issue 15596.)
- A performance issue in io.FileIO.readall() has been solved. This particularly affects Windows, and significantly speeds up the case of piping significant amounts of data through subprocess. (Contributed by Richard Oudkerk in issue 15758.)
- html.escape() is now 10x faster. (Contributed by Matt Bryant in issue 18020.)
- On Windows, the native VirtualAlloc is now used instead of the CRT malloc in obmalloc. Artificial benchmarks show about a 3% memory savings.
- os.urandom() now uses a lazily-opened persistent file descriptor so as to avoid using many file descriptors when run in parallel from multiple threads. (Contributed by Antoine Pitrou in issue 18756.)
Deprecated
- As mentioned in PEP 451: A ModuleSpec Type for the Import System, a number of importilb methods ABC load_module methods (importlib.abc.Loader.load_module(), importlib.abc.InspectLoader.load_module(), importlib.abc.FileLoader.load_module(), importlib.abc.SourceLoader.load_module()) should no longer be implemented, instead loaders should implement an exec_module method module is pending deprecation. To keep compatibility with Python 2/3 code bases, the module’s removal is currently not scheduled.
- The formatter module is pending deprecation and is slated for removal in Python 3.6.
- MD5 as the default digestmod for the hmac.new() function is deprecated. Python 3.6 will require an explicit digest name or constructor as digestmod argument.
- The internal Netrc class in the ftplib module has been documented as deprecated in its docstring for quite some time. It now emits a DeprecationWarning and will be removed completely in Python 3.5.
- The undocumented endtime argument to subprocess.Popen.wait() should not have been exposed and is hopefully not in use; it is deprecated and will mostly likely be removed in Python 3.5.
- The strict argument of HTMLParser is deprecated.
- The plistlib readPlist(), writePlist(), readPlistFromBytes(), and writePlistToBytes() functions are deprecated in favor of the corresponding new functions load(), dump(), loads(), and dumps(). Data() is deprecated in favor of just using the bytes constructor.
- The sysconfig key SO is deprecated, it has been replaced by EXT_SUFFIX.
- The U mode accepted by various open functionsParser should be passed by keyword.
Deprecated Features
- Running IDLE with the -n flag (no subprocess) is deprecated. However, the feature will not be removed until issue 18823 is resolved.
- The site module adding a “site-python” directory to sys.path, if it exists, is deprecated (issue 19375).
Removed
Operating Systems No Longer Supported
Support for the following operating systems has been removed from the source and build tools:
- OS/2 (issue 16135).
- Windows 2000 (changeset e52df05b496a).
- Windows systems where COMSPEC points to command.com (issue 14470).
- VMS (issue 16136).
API and Feature Removals
The following obsolete and previously deprecated APIs and features have been removed:
- The unmaintained Misc/TextMate and Misc/vim directories have been removed (see the devguide for suggestions on what to use instead).
- The SO makefile macro is removed (it was replaced by the SHLIB_SUFFIX and EXT_SUFFIX macros) (issue 16754).
- The PyThreadState.tick_counter field has been removed; its value has been meaningless since Python 3.2, when the “new GIL” was introduced (issue 19199).
- PyLoader and PyPycLoader have been removed from importlib. (Contributed by Taras Lyapun in issue 15641.)
- The strict argument to HTTPConnection and HTTPSConnection has been removed. HTTP 0.9-style “Simple Responses” are no longer supported.
- The deprecated urllib.request.Request getter and setter methods add_data, has_data, get_data, get_type, get_host, get_selector, set_proxy, get_origin_req_host, and is_unverifiable have been removed (use direct attribute access instead).
- Support for loading the deprecated TYPE_INT64 has been removed from marshal. (Contributed by Dan Riti in issue 15480.)
- inspect.Signature: positional-only parameters are now required to have a valid name.
- object.__format__() no longer accepts non-empty format strings, it now raises a TypeError instead. Using a non-empty string has been deprecated since Python 3.2. This change has been made to prevent a situation where previously working (but incorrect) code would start failing if an object gained a __format__ method, which means that your code may now raise a TypeError if you are using an 's' format code with objects that do not have a __format__ method that handles it. See issue 7994 for background.
- difflib.SequenceMatcher.isbjunk() and difflib.SequenceMatcher.isbpopular() were deprecated in 3.2, and have now been removed: use x in sm.bjunk and x in sm.bpopular, where sm is a SequenceMatcher object (issue 13248).
Code Cleanups
- The unused and undocumented internal Scanner class has been removed from the pydoc module.
- The private and effectively unused _gestalt module has been removed, along with the private platform functions _mac_ver_lookup, _mac_ver_gstalt, and _bcd2str, which would only have ever been called on badly broken OSX systems (see issue 18393).
- The hardcoded copies of certain stat constants that were included in the tarfile module namespace have been removed.
Porting to Python 3.4
This section lists previously described changes and other bugfixes that may require changes to your code.
Changes in ‘python’ Command Behavior
- In a posix shell, setting the PATH environment variable to an empty value is equivalent to not setting it at all. However, setting PYTHONPATH to an empty value was not equivalent to not setting it at all: setting PYTHONPATH to an empty value was equivalent to setting it to ., which leads to confusion when reasoning by analogy to how PATH works. The behavior now conforms to the posix convention for PATH.
- The [X refs, Y blocks] output of a debug (--with-pydebug) build of the CPython interpreter is now off by default. It can be re-enabled using the -X showrefcount option. (Contributed by Ezio Melotti in issue 17323.)
- The python command and most stdlib scripts (as well as argparse) now output --version information to stdout instead of stderr (for issue list see Other Improvements above).
Changes in the Python API
- The ABCs defined in importlib.abc now either raise the appropriate exception or return a default value instead of raising NotImplementedError blindly. This will only affect code calling super() and falling through all the way to the ABCs. For compatibility, catch both NotImplementedError or the appropriate exception as needed.
- The module type now initializes the __package__ and __loader__ attributes to None by default. To determine if these attributes were set in a backwards-compatible fashion, use e.g. getattr(module, '__loader__', None) is not None. (issue (issue__') (issue is set to 'frozen', check if the loader is a subclass of importlib.machinery.FrozenImporter, or if Python 2 compatibility is necessary you can use imp.is_frozen().
- py_compile.compile() now raises FileExistsError if when the source code being loaded triggers a SyntaxError or UnicodeDecodeError. As ImportErrorFinder now passes on the current working directory to objects in sys.path_hooks for the empty string. This results in sys.path_importer_cache never containing '', thus iterating through sys.path_importer_cache based on sys.path will not find all keys. A module’s __file__ when imported in the current working directory will also now have an absolute path, including when using -m with the interpreter (except for __main__.__file__ when a script has been executed directly using a relative path) (Contributed by Brett Cannon in issue 18416). is specified on the command-line) (issue 18416).
- The removal of the strict argument to HTTPConnection and HTTPSConnection changes. (issue 17434).
- ssl.SSLSocket.getpeercert() and ssl.SSLSocket.do_handshake() now raise an OSError with ENOTCONN when the SSLSocket is not connected, instead of the previous behavior of raising an AttributError. In addition, getpeercert() will raise a ValueError if the handshake has not yet been done.
- base64.b32decode() now raises a binascii.Error when the input string contains non-b32-alphabet characters, instead of a TypeError. This particular TypeError was missed when the other TypeErrors were converted. (Contributed by Serhiy Storchaka in issue 18011.) Note: this change was also inadvertently applied in Python 3.3.3.
- The file attribute is now automatically closed when the creating cgi.FieldStorage instance is garbage collected. If you were pulling the file object out separately from the cgi.FieldStorage instance and not keeping the instance alive, then you should either store the entire cgi.FieldStorage instance or read the contents of the file before the cgi.FieldStorage instance is garbage collected.
- Calling read or write on a closed SSL socket now raises an informative ValueError rather than the previous more mysterious AttributeError (issue 9177).
- slice.indices() no longer produces an OverflowError for huge values. As a consequence of this fix, slice.indices() now raises a ValueError if given a negative length; previously it returned nonsense values (issue 14794).
- The complex constructor, unlike the cmath functions, was incorrectly accepting float values if an object’s __complex__ special method returned one. This now raises a TypeError. (issue 16290.)
- The int constructor in 3.2 and 3.3 erroneously accepts float values for the base parameter. It is unlikely anyone was doing this, but if so, it will now raise a TypeError (issue 16772).
- Defaults for keyword-only arguments are now evaluated after defaults for regular keyword arguments, instead of before. Hopefully no one wrote any code that depends on the previous buggy behavior (issue 16967).
- Stale thread states are now cleared after fork(). This may cause some system resources to be released that previously were incorrectly kept perpetually alive (for example, database connections kept in thread-local storage). (issue 17094.)
- Parameter names in __annotations__ dicts are now mangled properly, similarly to __kwdefaults__. (Contributed by Yury Selivanov in issue 20625).
- hashlib.hash.name now always returns the identifier in lower case. Previously some builtin hashes had uppercase names, but now that it is a formal public interface the naming has been made consistent (issue 18532).
- Because unittest.TestSuite now drops references to tests after they are run, test harnesses that re-use a TestSuite to re-run a set of tests may fail. Test suites should not be re-used in this fashion since it means state is retained between test runs, breaking the test isolation that unittest is designed to provide. However, if the lack of isolation is considered acceptable, the old behavior can be restored by creating a TestSuite subclass that defines a _removeTestAtIndex method that does nothing (see TestSuite.__iter__()) (issue 11798).
- unittest now uses argparse for objects functions now raise an error immediately if passed string input, instead of failing randomly later on (issue 16685).
- The new convert_charrefs argument to HTMLParser currently defaults to False for backward compatibility, but will eventually be changed to default to True. It is recommended that you add this keyword, with the appropriate value, to any HTMLParser calls in your code (issue 13633).
- Since the digestmod argument to the hmac.new() function will in the future have no default, all calls to hmac.new() should be changed to explicitly specify a digestmod (issue 17276).
- Calling sysconfig.get_config_var() with the SO key, or looking SO up in the results of a call to sysconfig.get_config_vars() is deprecated. This key should be replaced by EXT_SUFFIX or SHLIB_SUFFIX, depending on the context (issue 19555).
- Any calls to open functions that specify U should be modified. U is ineffective in Python3 and will eventually raise an error if used. Depending on the function, the equivalent of its old Python2 behavior can be achieved using either a newline argument, or if necessary by wrapping the stream in TextIOWrapper to use its newline argument (issue 15204).
- If you use pyvenv in a script and desire that pip not be installed, you must add --without-pip to (issue 16333).
- doctest now looks for doctests in extension module __doc__ strings, so if your doctest test discovery includes extension modules that have things that look like doctests in them you may see test failures you’ve never seen before when running your tests (issue 3158).
- The collections.abc module has been slightly refactored as part of the Python startup improvements. As a consequence of this, it is no longer the case that importing collections automatically imports collections.abc. If your program depended on the (undocumented) implicit import, you will need to add an explicit import collections.abc (issue 20784).
Changes in the C API
- when its msg argument is not set. Previously only NULL was returned with no exception set.
- The result of the PyOS_ReadlineFunctionPointer callback must now be a string allocated by PyMem_RawMalloc() or PyMem_RawRealloc(), or NULL if an error occurred, instead of a string allocated by PyMem_Malloc() or PyMem_Realloc() (issue 16742)
- PyThread_set_key_value() now always set the value. In Python 3.3, the function did nothing if the key already exists (if the current value is a non-NULL pointer).
- The f_tstate (thread state) field of the PyFrameObject structure has been removed to fix a bug: see issue 14432 for the rationale. | https://documentation.help/Python-3.4/3.4.html | CC-MAIN-2019-51 | refinedweb | 6,494 | 58.38 |
accessible
Skip over Site Identifier
Skip over Generic Navigation
Skip over Search
Skip over Site Explorer
Site ExplorerSite Explorer
Posts: 21
Rating:
(1)
Joined: 10/17/2006
Last visit: 5/31/2021
Posts: 97
(16)
Posts: 1275
(122)
Hi.as i read the user archive application starts only on winccserver.it is known way to switch on in startup on the client the application. but there are no possibilties to do it because of it grey color of checkbox (deactivated by system).
#include "apdefap.h"void OnClick(char* lpszPictureName, char* lpszObjectName, char* lpszPropertyName)
{UAHCONNECThConnect;UAHARCHIVEhArchive;
char* date; char filter[80]="",temp[10]=""; BOOL ack; SYSTEMTIME st;
if ( uaConnect ( &hConnect ) == FALSE){ printf("Error calling uaConnect: %d \n", uaGetLastError() ); return;}
if (hConnect==NULL){printf ("Handle UACONNECT equals 0\n");}
if ( uaQueryArchiveByName ( hConnect, "Incoming", &hArchive) == FALSE){ printf("Error calling uaQueryArchiveByName: %d \n", uaGetLastError() ); \\this errorshowed on client uaDisconnect ( hConnect ); return;} ...
Posts: 3149
(169)
Hi"..so you are using MultiClients??? Did you generate packages for your MultiClients and load them?"yes, yes. the project could be started.i receive the data to the online table, but couldn't open archivebyname with c-action listed above.it gives us an error 101.
Joined: 5/19/2006
Last visit: 6/10/2021
Posts: 542
(104)
NemoHiso you are using MultiClients??? Did you generate packages for your MultiClients and load them?nemo
WinCC Controls for displaying messages and process data receive their data from specific servers with server prefix.
Components that do not receive their data from servers with server prefix refer to the standard server specified here.
Note:
If no standard server is programmed for a component, an attempt is made for this component to access the WinCC Client data store locally (e.g. internal tags). If there is no local data store on the WinCC Client (such as with messages and archives), the access is denied with an error message.
we supposed problem due to installation but WinCC installed properly. and change/remove of WinCC in Add/remove programm shows us that ua installed. so the question is the same as above
i can use the online table user archive control and can see contains of the user archive with table. but couldn't open archive throw the c-action.it says that possible to use :: for addressing. does somebody knows what is the syntaxis for using? | https://support.industry.siemens.com/tf/ww/en/posts/open-user-archive-by-name-on-wincc-client/8282?page=0&pageSize=10 | CC-MAIN-2021-25 | refinedweb | 392 | 55.74 |
Well, I am not quite sure it is a bug, but I lost one day to find where my
problem was, so it may be helpful :)
When the context name contains a space character (' ') everything works fine ,
except that the session object in the request is null (and a new session is
created when getSession is invoked ) even if a session has already been initialized.
For example:
public class MyServlet extends HttpServlet {/html");
PrintWriter out = response.getWriter();
out.println("<html><body><a href=\"MyServlet\"> click me!</a><br>");
out.println(request.getSession().getAttribute("hello"));
out.println("</body></html>");
request.getSession().setAttribute("hello", "Hello!");
}
}
When the context name contains a space (fo example: "Sample Project") and you
load the page and click on the link, the result is always :
click me
null
When you change the name to "SampleProject", the problem is gone.
Where are you defining this context name? In the web.xml (display-name
attribute)? In the context.xml file for the context? Or explicitly by making
it a directory in the webapps directory?
In the server.xml.
I am using Eclipse and a tomcat plugin for it. It defines the context in the
server.xml file.
Can you attach your server.xml file to this report please?
Created attachment 12843 [details]
server.xml
Created attachment 12844 [details]
The Eclipse project for testing
I've verified your bug outside Eclipse, and I'm attaching a WAR that lets one
reproduce it on an out-of-the-box tomcat. Deploying this war as
SessionSpace.war versus "Session Space.war" shows the bug.
I'm updating the comopnent, platform, OS, version fields of the bug report as
well.
Created attachment 12851 [details]
WAR to reproduce bug
This is due to browsers not recognizing spaces in the session cookie's path. See
the headers from two hits to the example (from the war file by Yoav Shapira).
I'm attaching a patch to fix this.
Tested with MSIE 6 and Mozilla 1.7.2
Headers ========================================================
Cache-Control: max-age=0
HTTP/1.x 200 OK
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=33047CF84AA4E7159F1262C21D4FEA83; Path=/Sample App
Content-Type: text/html;charset=ISO-8859-1
Content-Length: 165
Date: Wed, 13 Oct 2004 01:31:50 GMT
----------------------------------------------------------:
Cache-Control: max-age=0
HTTP/1.x 200 OK
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=82313411257D1DA54FDFD741D4E1FE78; Path=/Sample App
Content-Type: text/html;charset=ISO-8859-1
Content-Length: 165
Date: Wed, 13 Oct 2004 01:32:03 GMT
----------------------------------------------------------
Created attachment 13058 [details]
Patch to encode spaces in session cookie path
Good investigation and finding, OK patch. OK because replaceAll is in JDK 1.4,
so I can use the patch as-is for Tomcat 5.5, but for Tomcat 5.0 we need the
same thing in JDK 1.3-compatible format. Maybe I'll just URLEncoder.encode the
cookie's path?
Ahh, good point.
I originally went with the URLEncoder but it was encoding the "/" at the
beginning.
So, to go this route, I would either need to strip out the "/" before encoding or
do a replace afterwards.
If characters other than spaces don't need to be considered, maybe use this
patch on 5.5x. and use the URLEncoder for the older release?
Note: The Request class doesn't import URLEncoder yet so this means one more
object created for each request. This needs to be added to the object creation
involved with pulling and replacing the "/". Probably trivial but I know there
is a lot of effort being made to increase performance and it's a shame to add
more overhead just to support spaces in a context path.
Maybe add a URL encoded path field on the Context. (URL encoding stuff all the
time is a bit expensive, and it could be needed)
I'll try it later today.
BTW, before making any changes: cookie values should be URL encoded then ? I
don't remember that, but maybe it's true. Can anyone confirm ?
Actually, I think cookies shouldn't be URL encoded. See the ServerCookie class,
and in particular the maybeQuote and isToken methods. Now ' ' isn't part of the
"special" list anymore, for some reason.
OTOH, the Cookie class from the servlet API includes:
private static final String tspecials = ",; ";
I think the bug will only need a change there.
IMHO, Remy's idea is best. But it will throw an IAE since the session cookie
is v0. Probably we could just remove the version check in maybeQuote, since
I'm guessing that most UAs probably support quoted values, even if they don't
support all of RFC2019.
Using the JDK1.3 j.n.URLEncoder is going to cause more problems then it will
ever solve, given that it uses the platform encoding (which is unlikely to be
utf-8 :). If you have to encode the path, use the UEncoder in the Response.
Ah, yes, I missed that "small" point. I thought I had a really good idea here ;)
BTW, can you explain the tspecials descrepancy between the two cookies classes
for the tspecial field ?
It looks like the ServerCookie value is the one from jakarta-servletapi (aka
servlet-2.2), and simply hasn't been updated.
After discussion on the tomcat-dev list, I'm closing this as WONTFIX because
it's a contrived use-case: the browser will never send a request with a space
character in it (it'd be encoded as %20, which is handled fine by Tomcat).
Yes, but the problem is that TC will set a cookie based on the unencoded path,
and the browser doesn't make the association between that and the URL (somehow).
In theory, we would need to URL encode the context path using straight conversion.
.
It is fixed now, but the fix assumes UTF-8 encoding for URLs. I guess even if it
doesn't work always, it's better than it it never works.
Forgot to mention: for really tricky situations (i18n ...), you can also choose
to set the cookie path to "/" by using emptySessionPath="true" on the Connector. | https://bz.apache.org/bugzilla/show_bug.cgi?id=31090 | CC-MAIN-2020-40 | refinedweb | 1,015 | 66.94 |
...one of the most highly
regarded and expertly designed C++ library projects in the
world. — Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
By now you should know how to use Boost.Python to call your C++ code from Python. However, sometimes you may need to do the reverse: call Python code from the C++-side. This requires you to embed the Python interpreter into your C++ program.
Currently, Boost.Python does not directly support everything you'll need when
embedding. Therefore you'll need to use the Python/C
API to fill in the gaps. However, Boost.Python already makes embedding
a lot easier and, in a future version, it may become unnecessary to touch the
Python/C API at all. So stay tuned...
To be able to embed python into your programs, you have to link to both Boost.Python's as well as Python's own runtime library.
Boost.Python's library comes in two variants. Both are located in Boost's
/libs/python/build/bin-stage subdirectory. On Windows, the
variants are called
boost_python.lib (for release builds)
and
boost_python_debug.lib (for debugging). If you can't
find the libraries, you probably haven't built Boost.Python yet. See Building and Testing on how to do this.
Python's library can be found in the
/libs subdirectory
of your Python directory. On Windows it is called pythonXY.lib where X.Y is
your major Python version number.
Additionally, Python's
/include subdirectory has to be added
to your include path.
In a Jamfile, all the above boils down to:
projectroot c:\projects\embedded_program ; # location of the program # bring in the rules for python SEARCH on python.jam = $(BOOST_BUILD_PATH) ; include python.jam ; exe embedded_program # name of the executable : #sources embedded_program.cpp : # requirements <find-library>boost_python <library-path>c:\boost\libs\python $(PYTHON_PROPERTIES) <library-path>$(PYTHON_LIB_PATH) <find-library>$(PYTHON_EMBEDDED_LIBRARY) ;
Being able to build is nice, but there is nothing to build yet. Embedding the Python interpreter into one of your C++ programs requires these 4 steps:
<boost/python.hpp>
_main_module.
(Of course, there can be other C++ code between all of these steps.)
Now that we can embed the interpreter in our programs, lets see how to put it to use...
As you probably already know, objects in Python are reference-counted. Naturally,
the
PyObjects of the Python C API are also reference-counted.
There is a difference however. While the reference-counting is fully automatic
in Python, the Python C API requires you to do it by
hand. This is messy and especially hard to get right in the presence
of C++ exceptions. Fortunately Boost.Python provides the handle
and object class templates to
automate the process.
Boost.python provides three related functions to run Python code from C++.
object eval(str expression, object globals = object(), object locals = object()) object exec(str code, object globals = object(), object locals = object()) object exec_file(str filename, object globals = object(), object locals = object())
eval evaluates the given expression and returns the resulting value. exec executes the given code (typically a set of statements) returning the result, and exec_file executes the code contained in the given file.
The
globals and
locals parameters are
Python dictionaries containing the globals and locals of the context in which
to run the code. For most intents and purposes you can use the namespace
dictionary of the
_main_
module for both parameters.
Boost.python provides a function to import a module:
object import(str name)
import imports a python module (potentially loading it into the running process first), and returns it.
Let's import the
_main_
module and run some Python code in its namespace:
object main_module = import("__main__"); object main_namespace = main_module.attr("__dict__"); object ignored = exec("hello = file('hello.txt', 'w')\n" "hello.write('Hello world!')\n" "hello.close()", main_namespace);
This should create a file called 'hello.txt' in the current directory containing a phrase that is well-known in programming circles.
Often we'd like to have a class to manipulate Python objects. But we have
already seen such a class above, and in the previous
section: the aptly named
object class and its
derivatives. We've already seen that they can be constructed from a
handle.
The following examples should further illustrate this fact:
object main_module = import("__main__"); object main_namespace = main_module.attr("__dict__"); object ignored = exec("result = 5 ** 2", main_namespace); int five_squared = extract<int>(main_namespace["result"]);
Here we create a dictionary object for the
_main_
module's namespace. Then we assign 5 squared to the result variable and read
this variable from the dictionary. Another way to achieve the same result
is to use eval instead, which returns the result directly:
object result = eval("5 ** 2"); int five_squared = extract<int>(result);
If an exception occurs in the evaluation of the python expression, error_already_set is thrown:
try { object result = eval("5/0"); // execution will never get here: int five_divided_by_zero = extract<int>(result); } catch(error_already_set const &) { // handle the exception in some way }
The
error_already_set exception class doesn't carry any
information in itself. To find out more about the Python exception that occurred,
you need to use the exception
handling functions of the Python C API in your catch-statement. This
can be as simple as calling PyErr_Print()
to print the exception's traceback to the console, or comparing the type
of the exception with those of the standard
exceptions:
catch(error_already_set const &) { if (PyErr_ExceptionMatches(PyExc_ZeroDivisionError)) { // handle ZeroDivisionError specially } else { // print all other errors to stderr PyErr_Print(); } }
(To retrieve even more information from the exception you can use some of the other exception handling functions listed here.) | http://www.boost.org/doc/libs/1_46_1/libs/python/doc/tutorial/doc/html/python/embedding.html | CC-MAIN-2015-27 | refinedweb | 931 | 56.25 |
gcc .
Recall that
gcc does multiple steps, not just one. Here is a brief explanation of their meaning:
gccoutputs warning or error messages during this stage as the analyzer parses and finds any mistakes in your code. If any optimization is requested,
gccwill analyze your code further to find the possible spots and manipulate them further. This work is done in multipass style, which demonstrates that it sometimes takes more than one scan through the source code to optimize. [2]
The
gcc parameters described here directly and indirectly touch all those four stages, so for clarity, this article is organized as follows:
Before that, let's meet the accompanying tools that will help us to sneak inside the resulting code:
objdumpand
readelf. They parse ELF information for us.
Oprofile, one of the de facto ways to collect hardware performance counters. We need this tool to see certain aspects of the code's performance.
time, a simple way to collect total runtime of a program.0(O zero) to
-O3. "0" means no optimization, while "3" is highest optimization level. "1" and "2" are between these extreme edges. If you just use -O without specifying any number, implicitly it means
-O1.
-Os. Tells
gccto optimize for size. Basically, it is similar to
-O2, but skips some steps that might enlarge the size.:
-O0.
-O1.
-O2.
-O3..
gcc basically offers you several ways to manage how a function is called. Let's take a look at inlining first. By inlining, you reduce the cost of a function call because the body of the function is directly substituted into the caller. Please note that this is not done by default, only when you use
-O3 or at least
-finline-functions.
How does the finished binary look when
gcc does inlining? Observe Listing 2:
#include<stdio.h> inline test(int a, int b, int c) { int d; d=a*b*c; printf("%d * %d * %d is %d\n",a,b,c,d); } static inline test2(int a, int b, int c) { int d; d=a+b+c; printf("%d + %d + %d is %d\n",a,b,c,d); } int main(int argc, char *argv[]) { test(1,2,3); test2(4,5,6); }
Listing 2. Inline in action
Compile Listing 2 using the following parameter:
$ gcc -S -O3 -o <result-file.s> <listing-2.c>
-S makes
gcc stop right after compilation stage (we'll cover it later in this article). The results are as follows:
.... test: pushl %ebp movl %esp, %ebp pushl %ebx .... main: leal 4(%esp), %ecx andl $-16, %esp pushl -4(%ecx) ... movl $6, 16(%esp) movl $3, 12(%esp) movl $2, 8(%esp) movl $1, 4(%esp) movl $.LC0, (%esp) call printf ... movl $15, 16(%esp) movl $6, 12(%esp) movl $5, 8(%esp) movl $4, 4(%esp) movl $.LC1, (%esp) call printf ...
Both
test() and
test2() are indeed inlined, but you also see
test(), which stays outside
main(). This is where the
static keyword plays a role. By saying a function is static, you tell
gcc that this function won't be called by any outside object file, so there is no need to emit the codes on its own. Thus, it is a space saver if you can mark them as static whenever possible. On the other hand, be wise when deciding which function should be inlined. Increasing size for a small speedup isn't always worthwhile.
With certain heuristics,
gcc decides whether a function should be inlined or not. One of the considerations is the function size in term of pseudo-instructions. By default, the limit is 600. You can change this limit via
-finline-limit. Experiment to find better inline limits for your own case. It is also possible to override the heuristics so
gcc always inlines the function. Simply declare your function like this:
__attribute__((always_inline)) static inline test(int a, int b, int c)
Now, on to parameter passing. In x86 architectures, parameters are pushed to the stack and later popped inside the function for further processing. But
gcc gives you a chance to change this behavior and instead use registers. Functions with up to three parameters could use this feature by passing
-mregparm=<n>, where <n> is the number of registers we want to use. If we apply this parameter (n=3) to Listing 2, take out the
inline attribute, and use no optimization, we get this:
... test: pushl %ebp movl %esp, %ebp subl $56, %esp movl %eax, -20(%ebp) movl %edx, -24(%ebp) movl %ecx, -28(%ebp) ... main: ... movl $3, %ecx movl $2, %edx movl $1, %eax call test
Instead of stack, it uses EAX, EDX, and ECX to hold the first, second, and third parameter. Because register access time is faster than RAM, it is one way to reduce runtime. However, you must pay attention to these issues:
-mregparmregister number. Otherwise, you will have trouble calling functions on another object file since they assume different calling conventions.
-mregparm, you basically break the Intel x86-compatible Application Binary Interface (ABI). Therefore, you should mention it when you distribute your software in binary only form.
You probably notice this kind of sequence at the beginning of every function:
push %ebp mov %esp,%ebp sub $0x28,%esp
This sequence, also known as the function prologue, is written to set up the frame pointer (EBP). It is useful to help the debugger do a stack trace. The structure below helps you visualize this [6]:
Can we omit it? Yes, with
-fomit-frame-pointer, the prologue will be shortened so the function just begins with a stack reservation (if there are local variables):
sub $0x28,%esp
If the function gets called very frequently, cutting out the prologue saves your program several CPU cycles. But be careful: by doing this, you also make it hard for the debugger to investigate the stack. For example, let's add
test(7,7,7) at the end of
test2() and recompile with
-fomit-frame-pointer and no optimization. Now fire up
gdb to inspect the binary:
$ gdb inline (gdb) break test (gdb) r Breakpoint 1, 0x08048384 in test () (gdb) cont Breakpoint 1, 0x08048384 in test () (gdb) bt #0 0x08048384 in test () #1 0x08048424 in test2 () #2 0x00000007 in ?? () #3 0x00000007 in ?? () #4 0x00000007 in ?? () #5 0x00000006 in ?? () #6 0x0000000f in ?? () #7 0x00000000 in ?? ()
On the second call of
test, the program is stopped and
gdb prints the stack trace. Normally,
main() should come up in Frame #2, but we only see question marks. Recall what I said about the stack layout: the absence of a frame pointer prevents
gdb from finding the location of the saved return address in Frame #2..
Using
readelf, you notice that there are 28 sections inside the non-debug version of Listing 1:
$ readelf -S ./non-optimized
But the debug version has 36 sections. The new sections added are:
You don't need to dig into all of the above sections; taking a look into
.debug_line is enough for quick observation. The command you need is:
$ produce native stabs format, while
-gstabs+includes specific
-gcoff.
-gxcoff. If you prefer to include GNU extensions,
.
However, things do not always go smoothly. When you combine
-O and
-g, it is necessary for line information to relate to the actual code in the mentioned address offset. An example can clarify this--take a file (I use Listing 1 again) and compile.
For learning purposes, sometimes you want to know how your source code is transformed into an executable. Fortunately,
gcc provides you options to stop at any processing stage. Recall that
gcc has several stages to be accomplished--for example, linking. The options are:
-cstops at assembly phase but skips linking. The result is an object code.
-Estops after preprocessing stage. All preprocessing directives are expanded so you only see plain code.
-Sstops after compilation. It leaves you with assembler code
-c is mostly used when you have multiple source files and combine them to create the final executable. So, instead of:
$ gcc -o final-binary test1.c test2.c
it would be better to split them as:
$ gcc -c -o test1.o test1.c
$ gcc -c -o test2.o test2.c
and then:
$ gcc -o final-binary ./test1.o ./test1.o
You probably notice the same sequence if you build the program using a Makefile. The advantage of using
-c is clear: you only need to recompile the changed source files. The only phase that has to be redone is linking all the object files, and that greatly saves time, especially in large projects. An obvious example of this is the Linux kernel.
-E is useful if you want to see how your code really looks after macros, definitions, and such are expanded. Take Listing 3 as an example.
#include<stdio.h> #define A 2 #define B 4 #define calculate(a,b) a*a + b*b void plain_dummy() { printf("Just a dummy\n"); } static inline justtest() { printf("Hi!\n"); } int main(int argc, char *argv[]) { #ifdef TEST justtest(); #endif printf("%d\n", calculate(A,B)); return 0; }
Listing 3. Code contains #define and #ifdef
We compile it like this:
$ gcc -E -o listing2.e listing2.c
Notice that we don't pass any
-D parameters, which means
TEST is undefined. So what do we have in the preprocessed file?
void plain_dummy() { printf("Just a dummy\n"); } static inline justtest() { printf("Hi!\n"); } int main(int argc, char *argv[]) { printf("%d\n", 2*2 + 4*4); return 0; }
Where is the call to
justtest() inside
main()? Nowhere.
TEST is undefined--that's why the code is eliminated. You can also see that the
calculate() macro is already expanded into multiplication and addition of constant numbers. In final executable form, this number will be replaced with the operation result. As you see,
-E is quite handy to double-check the correctness of directives.
Notice that
plain_dummy() is still there even though it is never called. No surprise since no compilation happens here, therefore dead code elimination doesn't happen at this stage.
stdio.h is also expanded but it isn't shown in the above listing.
I found an interesting application of
-E as an HTML authoring tool [11]. In short, it helps you to adopt common programming practices such as code modularization and macros into the HTML world--something that cannot be done using plain HTML coding.
-S gives you assembly code, much like what you see with
objdump -d/-D. However, with
-S, you still see directives and symbol names, which makes it easier to study the code. For example, a call like
printf("%d\n", 20) could be transformed into:
.section .rodata.str1.1,"aMS",@progbits,1 .LC0: .string "%d\n" ... movl $20, 4(%esp) movl $.LC0, (%esp) call printf
You can see that
format string %d is placed in a read-only data section (
.rodata). Also, you can confirm that arguments are pushed to the stack from right to left, with the format string at the top of the stack.
gcc gives us many useful options to make our code into whatever we like. By understanding what these options really do, we can make the program faster and slimmer. However, do not depend entirely on them: you should pay more attention to writing efficient and well-structured code.
I would like to thank the communities in the OFTC chat room (#kernelnewbies and #gcc) and #osdev (Freenode) for their valuable ideas.
gcconline documentation
Mulyadi Santosa is a freelance writer who lives in Indonesia.
Return to ONLamp.com. | http://www.linuxdevcenter.com/lpt/a/6968 | CC-MAIN-2016-26 | refinedweb | 1,920 | 65.52 |
ASF Bugzilla – Bug 40897
String comparisons using '==' causes validation errors with some parsers
Last modified: 2010-10-17 14:55:21 UTC
There has already been discussion on this issue on the project mailing list.
here's the email thread:
----------------------------------------------------------------------------
Hi Sean,
The penalty hit is taken when the strings are not equal, sadly of the
same length.
And have a lot of common begging characters. That is sadly a common
problem with namespaces URI, they are more or less equal in length and
have a lot of damn... or urn:....: whatever at the
begining. And that is why Xerces and other DOM implementations intern
namespaces URI.
I have profile and it takes a lot of time.
My point is that all the parsers I know do the intern (or it did when
I do the implementation). And this is an old commit 8 months old(it is
true that it is not yet on a official release), and it takes a
measurable hit if not use in small messages(the kind of one that are
in xml protocols).
So I will first check other options (change the configuration of the
offending parser with a
feature[] ).
If it does not work I will change from == to equals, but I will let
this as last resort.
On 10/5/06, Sean Mullan <Sean.Mullan@sun.com> wrote:
> String.equals will work for both interned and non-interned Strings,
> since it first checks if they are a reference to the same object. So
> using String.equals seems safer and should be comparable performance I
> would think. But maybe I'm missing something?
>
> --Sean
>
> Vishal Mahajan wrote:
> > Do others also have views on this discussion?
> >
> > Thanks,
> > Vishal
> >
> > Vishal Mahajan wrote:
> >> Hi Raul,
> >>
> >> The parser that I am working with clearly doesn't intern element
> >> namespace strings which is the reason I ran into this problem. And
> >> actually I am not sure whether it's a good idea for a parser to intern
> >> element namespace strings given that there could be huge number of
> >> elements being parsed and there's a potential risk of running out of
> >> memory. Also you mention that xerces might be interning namespace
> >> stings but looking at their code I was unable to find that. Can you
> >> point me to the relevant piece of code?
> >>
> >> Thanks,
> >>
> >> Vishal
> >>
> >> Raul Benito wrote:
> >>> Vishal the problem is that this codes is called gazillion of times,
> >>> and even it
> >>> seems a small thing, it takes a lot of accumulated time, I even think
> >>> in remove this checking altogether or control it by a property.
> >>> Perhaps there is a feature set in your DOM parser that interns the
> >>> namespaces. I have test with several DOM parsers (xerces, xmlbeans,
> >>> jaxb) and all of them the namespaces strings are interns.
> >>> If you are not able too toggle the behavior, We can begin to think in
> >>> other possibilities (create code on the fly, create an interface with
> >>> one implementation or the other a let the JVM inline it). But I think
> >>> will be the last resort.
> >>>
> >>> Regards,
> >>> Raul
> >>>
> >>> On 10/2/06, Vishal Mahajan <vmahajan@amberpoint.com> wrote:
> >>>> Any signature verification was failing for me, and I have a different
> >>>> DOM implementation in my environment, so probably you are right. It was
> >>>> such a basic error that it had to be something like this. In any
> >>>> case, I
> >>>> think we should keep string comparison safe.
> >>>>
> >>>> Vishal
> >>>>
> >>>> Raul Benito wrote:
> >>>> > Hi Vishal,
> >>>> >
> >>>> > The namespaces strings are intern, at least in xerces.
> >>>> >
> >>>> > Can you post the code that is failing?
> >>>> >
> >>>> > On 10/2/06, Vishal Mahajan <vmahajan@amberpoint.com> wrote:
> >>>> >> This problem was not allowing successful creation of signature space
> >>>> >> elements. Fix attached.
> >>>> >>
> >>>> >> Vishal
----------------------------------------------------------------------------
Created attachment 21336 [details]
First draft for a pluggable string checker.
Please take a look a the patch, I want feed back on the solution.Also I don't
have anyother DOM parser that don't intern namespaces, this should fix the
problem, but perhaps there are more places where this problem arise.
I've run into this problem while running under WebLogic (the same app runs fine on Tomcat).
Would it be possible to do a quick == comparison, and then only do .equals if it fails?
Would interning all namespaces mean that an attacker could cause the server to run out of memory by sending requests which contain lots of random namespaces?.
(In reply to comment #3)
>.
>
I have do a lot of benchamark and really this is a huge improve. I can tell you why but it will be a big post. And I have do my exercises, and i benchmark the whole operation. Anyway 2 releases ago it was plain impossible to use another parser than xerces (and really a concrete one), we have improve it til the way that now, only this is possible and works with different ones that intern namespaces.
Anyway i think that sadly for a fully spec compliant there is no other options than a special xalan+xerces (for xpath transformations).
But I still that if a parser doesn't intern namespaces will be hit by a lot of just a difference in the end, that happens with versioning in xml. I just create the patch in order to disable the NS comparison.
*** Bug 45573 has been marked as a duplicate of this bug. ***
*** Bug 46681 has been marked as a duplicate of this bug. ***
In rev 1023243 I committed an update that I believe catches all the places that
== is used for string comparisons and replaces it with equals(). I also
deprecated org.apache.xml.security.utils.ElementChecker and
org.apache.xml.security.utils.ElementCheckerImpl which were used to attempt to
hide the difference between equals() and ==
This should resolve this issues unless I missed an occurrence. It would be
really helpful if those individuals who commented on this issues who are not
using Xerces could run unit test
org.apache.xml.security.test.c14n.implementations.Canonicalizer20010315ExclusiveTest
and let us know if this issue isn't resolved.
*** Bug 48681 has been marked as a duplicate of this bug. ***
*** Bug 44874 has been marked as a duplicate of this bug. *** | https://bz.apache.org/bugzilla/show_bug.cgi?id=40897 | CC-MAIN-2016-22 | refinedweb | 1,022 | 71.95 |
0
I am currently working on a program that takes one measurement of a circle and then gives the rest although i came across a problem while trying to make it loop back if you input an invalid number and my compiler keeps saying i have an error with were my while is placed ( I highlighted the important area in red!) thanks in advance you guys are the best!
#include <iostream> #include <conio.h> #include <cmath> using namespace std; double radius; double circumfrence; double area; double diameter; int radiusfunction(); int circumfrencefunction(); int areafunction(); int diameterfunction(); int main() { int choice; do{ cout << "I can find measurments on a circle!" << endl; cout << "which measurment do you have for me?" << endl; cout << "1.) radius" << endl; cout << "2.) circumfrence" << endl; cout << "3.) area" << endl; cout << "4.) diameter" << endl; cin >> choice; if (choice == 1){ radiusfunction(); } else{ if (choice == 2){ circumfrencefunction(); } else{ if (choice == 3){ areafunction(); } else{ if (choice == 4){ diameterfunction(); } else{ system("cls"); }while (choice != 1, 2, 3, 4); } } } } return 0; }
:icon_confused: | https://www.daniweb.com/programming/software-development/threads/357833/c-help-with-a-while-loop | CC-MAIN-2016-50 | refinedweb | 167 | 64.71 |
How To Deploy Temporal to Azure Kubernetes Service (AKS)
In my article A Practical Approach to Temporal Architecture, I outlined the various Temporal components and how they interact. Today’s blog builds on this knowledge and demonstrates an example of deploying Temporal to Kubernetes and, more specifically, to Azure Kubernetes Service (AKS).
My example is self-contained: it provisions a full environment with all the required Azure resources, Temporal service, and application deployment artifacts. Here is a diagram of the cloud infrastructure:
Deployment architecture
This sample deployment is implemented as a Pulumi program in TypeScript. You can find the full code in my GitHub.
Application Code
The
workflow folder contains all of the application code. The application is written with Go and consists of two source files:
helloworld.go- defines a workflow & activity
main.go- application entry point.
The example deploys a “Hello World” Temporal application copied from this Go sample. Once you get it up and running, you can certainly customize the code with your own workflow and activities.
The
main.go file does two things.
First, it spins up a worker:
w := worker.New(c, "hello-world", worker.Options{}) w.RegisterWorkflow(helloworld.Workflow) w.RegisterActivity(helloworld.Activity)
Second, it launches an HTTP server in the same process. The server exposes endpoints to start workflows. The
/async?name=<yourname> endpoint starts a new workflow and immediately returns, while the
/sync?name=<yourname> blocks and waits for the result of the execution and returns the response.
You can find the implementation in the
start function. Note that this simplistic starter is specifc to the “Hello World” workflow as it expects one argument and one result, both strings.
Deployment Structure
My program combines three component resources: a MySQL Database, an AKS cluster, and a Temporal deployment. As a result, the main file deploy all of these resources to a single Azure Resource Group:
const resourceGroup = new resources.ResourceGroup("resourceGroup", { resourceGroupName: resourceGroupName, location: "WestEurope", }); const database = new MySql("mysql", { resourceGroupName: resourceGroup.name, location: resourceGroup.location, administratorLogin: "mikhail", administratorPassword: mysqlPassword, }); const cluster = new AksCluster("aks", { resourceGroupName: resourceGroup.name, location: resourceGroup.location, kubernetesVersion: "1.16.13", vmSize: "Standard_DS2_v2", vmCount: 3, }); const temporal = new Temporal("temporal", { resourceGroupName: resourceGroup.name, location: resourceGroup.location, version: "1.1.1", storage: { type: "mysql", hostName: database.hostName, login: database.administratorLogin, password: database.administratorPassword, }, cluster: cluster, app: { namespace: "temporal", folder: "./workflow", port: 8080, }, }); export const webEndpoint = temporal.webEndpoint; export const starterEndpoint = temporal.starterEndpoint;
The rest of the article gives an overview of the building blocks of these three components.
Docker Image
Since the application is deployed to Kubernetes, we need to produce a custom Docker image. The
Dockerfile builds the Go application and exposes port
8080 to the outside world so we can access the starter HTTP endpoints.
Pulumi deploys this
Dockerfile to Azure in three steps:
- Deploy an Azure Container Registry.
- Retrieve the registry’s admin credentials generated by Azure.
- Publish the application image to the registry.
MySQL Database
There are several persistence options supported by Temporal. A straightforward option for Azure users is to deploy an instance of Azure Database for MySQL. It’s a fully managed database service where Azure is responsible for uptime and maintenance, and users pay a flat fee per hour.
My example provisions an instance of MySQL 5.7 at the Basic tier. The database size is limited to 5 GB.
A final tweak is to add a firewall rule for the IP address
0.0.0.0, which enables network access to MySQL from any Azure service. Note that this option isn’t secure for production workloads: read more in Connecting from Azure.
Azure Kubernetes Cluster
The example creates a new AKS cluster and deploys the Temporal service and applications components to that cluster.
The
AksCluster component:
- Sets up an Azure Active Directory Application and a Service Principal.
- Creates an SSH key for the cluster’s admin user profile.
- Provisions a managed Kubernetes cluster base on VM Scale Sets node pool. Feel free to adjust the VM size, count, and the Kubernetes version.
- Builds the Kubeconfig YAML to connect to the cluster and deploy application components.
Temporal Service and Web Console
Next, we deploy the Temporal Service and Temporal Web Console as two Kubernetes services.
We start with sound groundwork:
- Declare a custom Pulumi Kubernetes provider and point it to the Kubeconfig string that we retrieved from the managed cluster.
- Grant permission for the managed cluster’s service principal to access images from the Azure Container Registry.
- Define a new Kubernetes namespace that contains all Temporal deployments and services.
Then, we can deploy the Temporal Service:
- Stores the MySQL password as a Kubernetes secret.
- Refers to the
temporalio/auto-setupDocker image provided by Temporal. The image automatically populates the database schema during the first run.
- Sets up environment variables to connect to MySQL.
- Deploys a
ClusterIPservice using port
7233.
The Web Console follows:
- Refers to the
temporalio/webDocker image provided by Temporal.
- Connects to the gRPC endpoint of the Temporal Service.
- Deploys a
ClusterIPservice using port
8088.
Temporal Worker
The final component is a Temporal worker that runs application workflows and activities. In my setup, the worker is a Kubernetes deployment that pulls the custom Docker image from the container registry.
The application component:
- Refers to the custom Docker image created above.
- Connects to the gRPC endpoint of the Temporal Service.
- Deploys a
ClusterIPservice using port
8080.
The Pulumi Command-Line Interface (CLI) runs the deployment. Install Pulumi, navigate to the folder where you have the example cloned, and run the following commands:
- Create a new stack (a Pulumi deployment environment):
pulumi stack init dev
az login
- Install NPM dependencies:
npm install
- Run
pulumi upand confirm when asked if you want to deploy. Azure resources are provisioned:
$ pulumi up... Performing changes:... Outputs: starterEndpoint: "" webEndpoint : "" Resources:+ 27 created Duration: 6m46s
- The output above prints the endpoints to interact with the application. Run the following command to start a “Hello World” workflow:
curl $(pulumi stack output starterEndpoint)WorldStarted workflow ID=World, RunID=b4f6db00-bb2f-498b-b620-caad81c91a81%
Now, open the
webEndpoint URL in your browser and find the workflow (it’s probably already in the Completed state).
Cost, Security, and Further Steps
The deployment above provisions real Azure resources, so be mindful of the related costs. Here is an estimated calculation for the “West US 2” region:
- Azure Database for MySQL Gen5 Basic with 1 vCore and 5 GB of storage = $25.32/month
- Azure Kubernetes Cluster of 3 VMs type Standard_DS2_v2: 3 x $83.22/month = $249.66/month (but feel free to adjust to your needs)
- Azure Container Registry Basic = $5.00/month
The total cost for this example is approximately $280 per month.
Whenever you are done experimenting, run
pulumi destroy to delete the resources. Note that all the data will be lost after destruction.
You can find the full code in my GitHub.
Responses | https://mikhail.io/2020/11/how-to-deploy-temporal-to-azure-kubernetes-aks/ | CC-MAIN-2022-40 | refinedweb | 1,143 | 50.43 |
TripleO Quickstart¶
We need a common way for developers/CI systems to quickly stand up a virtual environment.
Problem Description¶
The tool we currently document for this use case is instack-virt-setup. However this tool has two major issues, and some missing features:
There is no upstream CI using it. This means we have no way to test changes other than manually. This is a huge barrier to adding the missing features.
It relies on a maze of bash scripts in the incubator repository[1] in order to work. This is a barrier to new users, as it can take quite a bit of time to find and then navigate that maze.
It has no way to use a pre-built undercloud image instead of starting from scratch and redoing the same work that CI and every other tripleo developer is doing on every run. Starting from a pre-built undercloud with overcloud images prebaked can be a significant time savings for both CI systems as well as developer test environments.
It has no way to create this undercloud image either.
There are other smaller missing features like automatically tagging the fake baremetals with profile capability tags via instackenv.json. These would not be too painful to implement, but without CI even small changes carry some amount of pain.
Proposed Change¶
Overview¶
Import the tripleo-quickstart[2] tool that RDO is using for this purpose. This project is a set of ansible roles that can be used to build an undercloud.qcow2, or alternatively to consume it. It was patterned after instack-virt-setup, and anything configurable via instack-virt-setup is configurable in tripleo-quickstart.
Use third-party CI for self-gating this new project. In order to setup an environment similar to how developers and users can use this tool, we need a baremetal host. The CI that currently self gates this project is setup on ci.centos.org[3], and setting this up as third party CI would not be hard.
Alternatives¶
One alternative is to keep using instack-virt-setup for this use case. However, we would still need to add CI for instack-virt-setup. This would still need to be outside of tripleoci, since it requires a baremetal host. Unless someone is volunteering to set that up, this is not really a viable alternative.
Similarly, we could use some other method for creating virtual environments. However, this alternative is similarly constrained by needing third-party CI for validation.
Other End User Impact¶
Using a pre-built undercloud.qcow2 drastically symplifies the virt-setup instructions, and therefore is less error prone. This should lead to a better new user experience of TripleO.
Performance Impact¶
Using a pre-built undercloud.qcow2 will shave 30+ minutes from the CI gate jobs.
Other Deployer Impact¶
There is no reason this same undercloud.qcow2 could not be used to deploy real baremetal environments. There have been many production deployments of TripleO that have used a VM undercloud.
Implementation¶
Work Items¶
Import the existing work from the RDO community to the openstack namespace under the TripleO umbrella.
Setup third-party CI running in ci.centos.org to self-gate this new project. (We can just update the current CI[3] to point at the new upstream location)
Documentation will need to be updated for the virtual environment setup.
Dependencies¶
Currently, the only undercloud.qcow2 available is built in RDO. We would either need to build one in tripleo-ci, or use the one built in RDO.
Testing¶
We need a way to CI the virtual environment setup. This is not feasible within tripleoci, since it requires a baremetal host machine. We will need to rely on third party CI for this. | https://specs.openstack.org/openstack/tripleo-specs/specs/mitaka/tripleo-quickstart.html | CC-MAIN-2021-04 | refinedweb | 622 | 57.98 |
>
Hi,
I'm have a ton of trouble successfully calling this function. I believe I have it set up right, and my code matches other 'solutions' I've found already. Everything compiles, but Unity doesn't call the function, and gives me this error:
I have made sure that the CameraShake script is attached to the MainCamera in the scene (only camera in the scene.)
This is my code:
As you can see, the "test shake" prints, but the error happens when it tries to call that next line. Also, I tried declaring it like this, which had the same outcome: CameraShake shake = this.gameObject.GetComponent();
Any insight would be greatly appreciated.
Upon further inspection, I see that the issue is becasue the CameraShake script was not attached to the bricks -- the objects which have the sfript that is calling the CameraShake cript. the problem is now that I'm not able to attach the scripts to either the prefab, or the instances of the bricks. I get the "Ghost Buster/No Smoking" symbol when I try.
Answer by wibble82
·
Dec 22, 2015 at 01:06 PM
Hi
You don't set the 'shake' variable anywhere.
As a result, it is 'null' (i.e. not set), and you are getting a 'null reference exception' - this is the scripts way of telling you that you are are trying to reference an object that is null.
Assuming CameraShake is a component of the same object as Brick, you could add the line:
shake = gameObject.GetComponent<CameraShake>();
to the Start function.
Note that this must be done int he Start function - not as part of the variable definition. If you place it in the variable definition, it is executed when your component is first created in memory, and there is no guarantee anything else has been created at that time!
If this doesn't work, then your brick object probably doesn't have a camera shake component attached.
p.s. in future always post code using the code formatting option in the help forums - see the little 101010 icon in the text editor!
-Chris
Thanks for responding!
I now have the code:
public class Brick : MonoBehaviour {
public Sprite[] hitSprites;
public static int breakableCount = 0;
public AudioClip crack;
public GameObject smoke;
//public CameraShake shake;
public CameraShake shake;
private int timesHit;
private LevelManager levelManager;
private bool isBreakable;
void Start () {
shake = gameObject.GetComponent<CameraShake>();
isBreakable = (this.tag == "Breakable");
if (isBreakable) {
breakableCount++;
}
timesHit = 0;
levelManager = GameObject.FindObjectOfType<LevelManager> ();
}
It still gives the error, and I see that the brick gameObject is still asking for something to be added to it, but will not allow me to.
Answer by UnverifiedBacon
·
Dec 22, 2015 at 01:41 PM
I found that if I manually add a NewScript > CameraShake, the code works. I deleted "public" in front of CameraShake shake; when I declared it, so that the brick was no longer asking for it to be attached. In any case, I have my.
I cant call function another script !
1
Answer
how do i keep an item destroyed when i change the scene c#
0
Answers
Unable to call function from another script
0
Answers
How to rotate RigidBodyFPSController (C#)
1
Answer
HELP! How to make Update function start after delay? C#
2
Answers | https://answers.unity.com/questions/1116104/unable-to-call-a-function-from-another-script.html | CC-MAIN-2019-13 | refinedweb | 544 | 70.73 |
Software.
Despite its familiarity this explicitness kind of stands in the way of what a piece of object oriented code is supposed to accomplish. It´s something you´ve to concern yourself with although it does not add to the raw functionality you want to achieve. And by being imperative it´s prone be done incorrectly. A more declarative way to do in-memory transactions and less explicitness thus would be nice now that objects have become transactional and automatically threadsafe in general.
I thought about that from the being when I started to work on NSTM. Microsofts STM implementation SXM shows, how transactionality could be made more declarative and "invisible": With SXM you just adorn a class with the attribute [Atomic] to make its instances transactional. That´s cool - but so far I did not consider it for NSTM, since it seemed to require fiddling around with proxies. That´s why with SXM you need to instanciate transactional objects through a factory which you´ve to create for each transactional class:
1 [Atomic]
2 public class Node
3 {
4 private int value;
5 private Node next;
6 ...
7 }
8 ...
9 XObjectFactory factory = new XObjectFactory(typeof(Node));
10 Node node = (Node)factory.Create(value);
The benefits of using an attribute to make classes transactional to me seem to be lost through this cumbersome instanciation process. That´s why I did not go down this road until now.
PostSharp to the rescue
But then one day - lo and behold! - a very, very cool tool was revealed to me by InfoQ (which I´ve come to like as much as theserverside.net):
PostSharp from Gael Fraiteur is a godsend! It´s one of those technologies you´ve waited for all along without really knowing. It´s a technology that will change how you approach software development. At least that´s what his done for me since I first read about it.
What PostSharp does is not new, though. It´s a kind of Aspect Oriented Programming (AOP) weaver. And it´s a tool to alter the MSIL code in assemblies. But there are already several APO frameworks out there - also for .NET -, so why another one? There are already tools to alter assemblies like Phoenix from Microsoft and Cecil from the Mono project.
What makes PostSharp so remarkable to me, though, is in which way it combines AOP with MSIL modification. It makes it so dead easy!
- You´re not forced to learn MSIL.
- The weaving is done automagically for you by an invisible post build step.
- No factories needed to instanciate classes annotated with aspects, because no proxies are used.
- For many common types of aspects (e.g. pre/post processing of method calls, field access interception) there are templates that help you get your own aspects up and running in just a few minutes.
Congratulations Gael! And thanks for being so responsive to questions and bug reports!
Aspect oriented transactions
The first thing I tried with PostSharp to make NSTM transactions declarative. This seemed to be easy to do and would result in an also familiar transactional programming model. COM+/EnterpriseServices, ASMX, and not WCF all sport some attribute to make methods transactional. Here´s an excerpt from Juval Löwy´s article [1] on that topic:
1 [ServiceContract]
2 interface IMyContract
3 {
4 [OperationContract]
5 [TransactionFlow(TransactionFlowOption.Mandatory)]
6 void MyMethod(...);
7 }
8
9 class MyService : IMyContract
10 {
11 [OperationBehavior(TransactionScopeRequired = true)]
12 public void MyMethod(...)
13 {
14 ...
17 }
18 }
MyMethod in the service contract is declared as to be wrapped in a mandatory transaction. The service implementation does not have to do anything imperatively for that. The WCF infrastructure will create a new System.Transactions transaction if necessary behind the scene.
That´s what I wanted for NSTM, too, and what now seemed within reach through PostSharp. And indeed it was very easy to implement. Here´s my transactional aspect whipped up in some 30 minutes after downloading PostSharp:
1 [Serializable]
2 [AttributeUsage(AttributeTargets.Method |
3 AttributeTargets.Property |
4 AttributeTargets.Constructor)]
5 public class NstmAtomicAttribute : OnMethodBoundaryAspect
6 {
7 private NstmTransactionScopeOption transactionScope;
8 private NstmTransactionIsolationLevel isolationLevel;
9 private NstmTransactionCloneMode cloneMode;
10 private bool createdNewTx;
...
35 public override void OnEntry(MethodExecutionEventArgs eventArgs)
36 {
37 NstmMemory.BeginTransaction(this.transactionScope,
38 this.isolationLevel,
39 this.cloneMode,
40 out this.createdNewTx);
41 }
42
43 public override void OnException(MethodExecutionEventArgs eventArgs)
44 {
45 if (this.createdNewTx) NstmMemory.Current.Rollback();
46 }
47
48 // will always be called, also after OnException()
49 public override void OnExit(MethodExecutionEventArgs eventArgs)
50 {
51 // only commit, if no exception has been thrown
52 if (eventArgs.Exception == null && this.createdNewTx)
53 NstmMemory.Current.Commit();
54 }
55 }
How does it work? First have a look at some code which uses this attribute:
1 static INstmObject<int> myAccount, yourAccount;
2
3 static void Main()
4 {
5 myAccount = NstmMemory.CreateObject<int>(1000);
6 yourAccount = NstmMemory.CreateObject<int>(500);
7
8 try
9 {
10 TransferMoney(350);
11 }
12 catch (Exception ex)
13 {
14 Console.WriteLine("*** {0}", ex.Message);
15 }
16
17 Console.WriteLine("my account: {0}", myAccount.Read());
18 Console.WriteLine("your account: {0}", yourAccount.Read());
19 }
20
21 [NstmAtomic()]
22 static void TransferMoney(int amountToTransfer)
23 {
24 myAccount.Write(myAccount.Read() - amountToTransfer);
25 yourAccount.Write(yourAccount.Read() + amountToTransfer);
26 throw new ApplicationException("Money transaction failed!");
27 }
The method TransferMoney() does not open explicitly a transaction. Rather this is done by the NSTM infrastructure because the method is adorned with the [NstmAtomic()] attribute. The default then is to commit the transaction when the method returns; but it´s aborted if the method throws an unhandled exception.
Of course, if you like, you can pass a transaction scope or isolationlevel etc. to the attribute to influence how the transaction is created. By default the scope is Required so nested calls don´t each created new transactions.
Now, how is this magic woven (sic!) by PostSharp? I won´t explain PostSharp in depth here, but a quick glimpse behind the curtain won´t hurt, wouldn´t it ;-)
Remember, PostSharp modifies the original assembly in a post build step like an O/R Mapper´s enhancer (e.g. Vanatec OpenAccess) or an obfuscator (e.g. Xenocode). So here´s the "enhanced" TransferMoney() method as seen through Reflector:
private static void TransferMoney(int amountToTransfer)
{
MethodExecutionEventArgs args;
try
{
object[] arguments = new object[] { amountToTransfer };
args = new MethodExecutionEventArgs(methodof(Program.TransferMoney, Program), null, arguments);
~PostSharp~Laos~Implementation.~aspect~1.OnEntry(args);
if (args.FlowBehavior != FlowBehavior.Return)
{
myAccount.Write(myAccount.Read() - amountToTransfer);
yourAccount.Write(yourAccount.Read() + amountToTransfer);
throw new ApplicationException("Money transaction failed!");
~PostSharp~Laos~Implementation.~aspect~1.OnSuccess(args);
}
}
catch (Exception exception)
{
args.Exception = exception;
~PostSharp~Laos~Implementation.~aspect~1.OnException(args);
switch (args.FlowBehavior)
{
case FlowBehavior.Continue:
case FlowBehavior.Return:
return;
}
throw;
}
finally
{
~PostSharp~Laos~Implementation.~aspect~1.OnExit(args);
}
}
I greyed out the original method body so you can more clearly what PostSharp has woven around it. Basically it´s a try-catch-block which calls the On...() methods of NstmAtomicAttribute. Where .NET needs context bound objects and proxies at runtime to let you intercept calls PostSharp does it by statically inserting code which calls your interception methods.
Aspect oriented transactional data
Since success was so easy to gain with PostSharp I did not want to stop with transactional methods. Wouldn´t it be nice to hide transactionality almost altogether? If enhancer based O/R Mappers can hide persistence behind an attribute and don´t require object creation through factories, why shouldn´t I be able to do the same? If SXM falls short of this, that´s not my problem ;-)
So I set down with PostSharp and had a close look at the different kinds of aspect it provides out of the box. And really there was a way to accomplish what O/R Mapper enhancers have done before. I just had to combine a "generic field" aspect with a "type composition" aspect using a "compound" aspect. And here´s the result:
1 [NstmTransactional]
2 public class Account
3 {
4 private int amount;
5 private int maxOverdraftAmount;
6
7 public Account()
8 {
9 this.amount = 0;
10 this.maxOverdraftAmount = 0;
11 }
12
13 public Account(int initialAmount, int maxOverdraftAmount)
14 {
15 this.amount = initialAmount;
16 this.maxOverdraftAmount = maxOverdraftAmount;
17 }
18
19 public int Amount
20 {
21 get
22 {
23 return this.amount;
24 }
25 set
26 {
27 if (value < maxOverdraftAmount)
28 throw new ApplicationException(...);
29 this.amount = value;
30 }
31 }
32 }
Put the [NstmTransactional] on an ordinary class to make it transactional. That´s it. It´s the same as wrapping INstmObject<T> around it. NSTM will care for buffering writes to instances and committing any changes at the end of a transaction. The money transfer example thus looses almost any trait of its transactionality:
35 static Account myAccount, yourAccount;
36
37 static void Main()
38 {
39 myAccount = new Account(1000, 0);
40 yourAccount = new Account(500, 0);
41
42 try
43 {
44 TransferMoney(1001);
45 }
46 catch (Exception ex)
47 {
48 Console.WriteLine("*** {0}", ex.Message);
49 }
50
51 Console.WriteLine("my account: {0}", myAccount.Amount);
52 Console.WriteLine("your account: {0}", yourAccount.Amount);
53 }
54
55
56 [NstmAtomic()]
57 static void TransferMoney(int amountToTransfer)
58 {
59 myAccount.Amount -= amountToTransfer;
60 yourAccount.Amount += amountToTransfer;
61 }
This is just ordinary object oriented code. (Please don´t get too critical with my account business logic ;-) With PostSharp´s AOP the impact of Software Transactional Memory on your code is reduced to two attributes: make classes transactional with [NstmTransactional] and wrap transactions around methods with [NstmAtomic].
If you don´t have a class you want to make transactional, but just a scalar type or a struct, then use NstmTransactional<T>:
1 static NstmTransactional<int> myAccount, yourAccount;
2
3 static void Main()
4 {
5 myAccount = 1000;
6 yourAccount = 500;
7
8 try
9 {
10 TransferMoney(1001);
11 }
12 catch (Exception ex)
13 {
14 Console.WriteLine("*** {0}", ex.Message);
15 }
16
17 Console.WriteLine("my account: {0}", myAccount.Value);
18 Console.WriteLine("your account: {0}", yourAccount.Value);
19 }
20
21
22 [NstmAtomic()]
23 static void TransferMoney(int amountToTransfer)
24 {
25 myAccount.Value -= amountToTransfer;
26 yourAccount.Value += amountToTransfer;
27
28 if (myAccount < 0)
29 throw new ApplicationException("No overdraft allowed!");
30 }
NstmTransactional<T> works almost like Nullable<T>. It´s just for scalar and value types. However NstmTransactional<T> is a class, not a struct! This is due to the need for identity and addressability of transactional data. When a transaction commits it needs to update a memory location it knows the address of. That´s not possible for value types which live on the stack. So if you want a value type to be transactional you need to be make it into an object.
Please note: [NstmAtomic] keeps only track of changes to one level of an object hierarchy! If you want to make more than one level transactional, you need to put [NstmAtomic] on all classes on all levels!
In this example a contact has an address. If you want to work transactionally with both, it´s not sufficient to just adorn the Contact class with [NstmAtomic], though! The attribute does not cause NSTM to track changes recursively on all objects pointed to by a Contact. Rather you need to make Address also transactional.
1 [NstmTransactional]
2 class Contact
3 {
4 private string name;
5
6 public string Name
7 {
8 get { return name; }
9 set { name = value; }
10 }
11
12 private Address location;
13
14 public Address Location
15 {
16 get { return location; }
17 set { location = value; }
18 }
19 }
20
21 [NstmTransactional]
22 class Address
23 {
24 private string city;
25
26 public string City
27 {
28 get { return city; }
29 set { city = value; }
30 }
31 }
With all levels of the object model made transactional code like this works correctly:
1 Contact c = new Contact();
2 c.Name = "John Doe";
3 c.Location = new Address();
4 c.Location.City = "Hamburg";
5
6 using (INstmTransaction tx = NstmMemory.BeginTransaction())
7 {
8 c.Name = "Peter Doe";
9 c.Location.City = "Berlin";
10 }
11
12 Console.WriteLine(c.Name);
13 Console.WriteLine(c.Location.City);
Neither the contact name nor the location´s city are changed, since the transaction is aborted.
This of course means, you cannot use the .NET collection classes as is. For example you could set up a contact with several addresses like this:
1 [NstmTransactional]
2 class ContactWithManyAddresses
3 {
4 private string name;
5 private List<Address> addresses;
6
7 public ContactWithManyAddresses()
8 {
9 this.addresses = new List<Address>();
10 }
11
12 public string Name
13 {
14 get { return name; }
15 set { name = value; }
16 }
17
18 public List<Address> Addresses
19 {
20 get { return this.addresses; }
21 }
22 }
Then you would want to be able to do the following:
100 ContactWithManyAddresses c = new ContactWithManyAddresses();
101 c.Name = "John Doe";
102 Address a = new Address();
103 a.City = "Hamburg";
104 c.Addresses.Add(a);
105
106 using (INstmTransaction tx = NstmMemory.BeginTransaction())
107 {
108 c.Name = "Peter Doe";
109 c.Addresses[0].City = "Berlin";
110
111 a = new Address();
112 a.City = "Munich";
113 c.Addresses.Add(a);
114 }
115
116 Console.WriteLine(c.Name);
117 foreach (Address b in c.Addresses)
118 Console.WriteLine(b.City);
But the output at the end of this code would surprise you:
The name of the contact and the city of the first address were rolled back correctly. But there is a second city in the list of addresses without a name. That´s the object to which the code assigned "Munich" and which was added to the address collection. The city of this address also got rolled back correctly, but the entry in the ArrayList was not. That´s because standard .NET collections are not transactional.
So, how then should you model 1:n relationships between transactional objects? True transactional collections are needed. I´m already working on some, so stay tuned. Or start building your own transactional list, queue, stack, tree etc. and let me know.
Preliminary conslusion
I´ve presented you my view of Software Transactional Memory for .NET. NSTM is written in C#, so it´s fully managed code. You can download the sources and play around with it. What will it gain you in terms of ease, productivity, or performance? Find out yourself. It´s programming model at least promises to make many multithreading tasks much easier. No need to think about locking, but rather work on on graphs of objects like on databases: open a transaction, do your work, commit the transaction. If something goes wrong, no changes are visible. That´s also an interesting propsal for GUI programming where you often want to display objects in dialogs, let the user enter changes, but also let him discard all changes. Especially with nested dialogs the nested NSTM transactions could help quite a bit to keep the frontend code straightforward, where IEditableObject falls short.
Enjoy!
PS: NSTM is not finished, of course. I´ll continue working on transactional collections. And there are some concepts from STM research I´d like to add, like a Retry() operation and blocking reads and notifications.
Download
You can download NSTM (short for .NET Software Transactional Memory) from the Google project hosting site.
Enjoy - and let me know how you like it, how it performs for you, or what you think needs to be improved.
Installation
- Download PostSharp from and install it.
- Download NSTM and install it by unzipping the file.
- Open the solution in the NSTM directory and try to compile it.
(It might fail due to incorrect references to PostSharp assemblies. The remedy is to update the PostSharp.Laos and PostSharp.Public references in the NSTM projects.)
There are a lot of NUnit compatible tests in the source code. You can use Testrunner like I do to run them in VS2005, or you can use NUnit itself. If you want to throw out all tests, just compile in Release mode.
Resources
[1] Juval Löwy, WCF Transaction Propagation, | http://weblogs.asp.net/ralfw/software-transactional-memory-vi-becoming-aspect-oriented-with-postsharp | CC-MAIN-2014-42 | refinedweb | 2,653 | 50.73 |
Mogre Basic Tutorial 0
From Ogre Wiki
Todo on this page:
- Update depencies for current Mogre version (use links from here)
- Some informations are redundant here and in MOGRE Installation
- Maybe merge or remove them?
- Maybe on this page only description for release version to reduce
information flood?
Basic Tutorial 0: Setting up a Mogre Application
Original version by Clay Culver.
Getting Started
Prerequisites
This tutorial assumes you have knowledge of C# programming and are able to setup and compile a standard C# application. You should have Visual C# 8.0 installed (the free Express Version will work fine).
Introduction
In this tutorial we will be going over how to install Mogre and how to setup and run an Mogre application. We will also go over some of the pitfalls of Mogre and how to avoid them, as well as proper Ogre exception handling. If you have questions about this tutorial, or Mogre in general, you should ask the question in the Mogre Forums.
Installation
Downloading Mogre
You can download the latest version of Mogre from the Mogre SourceForge project page. I suggest downloading the prebuilt SDK instead of the source code zip file. When you install the SDK, you will be given the choice of installation locations. This tutorial will assume you have installed the MogreSDK in default location (C:\MogreSDK).
You will also need vcredist_x86.exe; check it out in the same URL above. Some users reported that applications executed correctly after installation (e.g.: Visual Studio 2005, Team Edition, Version 8.0.50727-42).
Alternatively you can install the SP1 for your IDE (Visual Studio, C# Express, etc.) So you also can use the debug version of DLL files.
Downloading MogreFramework
The series of tutorials which follows this one will use a .Net assembly called the MogreFramework. Before getting started, you will need the file MogreFramework.dll.
Download:
- MogreFramework.dll - precompiled version for Mogre 1.4.8
- Source code - for Mogre 1.4.8; updated by Smiley80 in January 2009
Put the file MogreFramework.dll in both of these directories:
- C:\MogreSDK\bin\debug
- C:\MogreSDK\bin\release
Note:
- For each Mogre version a related MogreFramework file is needed. Maybe you have to recompile it.
- For Mogre 1.6.x look to this forum thread.
Setting Your PATH Variable
Ogre itself includes a large number of DLLs which we will need to include in Windows PATH variable. To do this, go to the Control Panel and open System. Click on "Advanced" tab, then click on the "Environment Variables" button. Under "System Variables", find the PATH Variable and click on it. Now click on the "Edit" button. At the end of the "Variable Value" field, add ";C:\MogreSDK\bin\release;C:\MogreSDK\bin\debug", and then click OK. Exit out of the System Properties and the Control Panel.
Note: You may need to restart your computer before these changes will take effect.
Building Your First Mogre Application
Creating a Project
Open up Visual Studios and create a new project. Be sure to select the "Windows Application" template, give the program a name, then hit OK. Visual C# creates a default form for you, called Form1. Delete that out of the project.
Now that we have a project created, we need to add references to it. Right click on "References" in the project, and select "Add Reference". Click on the "Browse" tab, and change the directory to "C:\MogreSDK\bin\release". Select both Mogre.dll and MogreFramework.dll and click "OK".
Adding Configuration Files.
Testing Your Application
Now that the project is fully setup and ready to be used, open up "program.cs" and replace the code with the following:
using System; using System.Collections.Generic; using System.Windows.Forms; using Mogre; using MogreFramework; namespace Test { static class Program { [STAThread] static void Main() { OgreWindow win = new OgreWindow(); try { win.Go(); } catch (System.Runtime.InteropServices.SEHException) { if (OgreException.IsThrown) MessageBox.Show(OgreException.LastException.FullDescription, "An Ogre exception has occurred!"); else throw; } } } }
Run the application by pressing F5. You should see a splash screen showing you the startup process and then a blank window with a black background. If so, congratulations! You have just successfully created your first Ogre project. We will be doing more with this later.
NOTE: If you get a line 80 or a line 100 exception after build, try to copy your build exe into the appropiate Debug or Release folder in your MogreSDK library (default: C:\MogreSDK\bin\(Debug or Release) and run it.
Troubleshooting
Checklist
If you have problems getting started, check the following things first:
- Did you install the Mogre SDK and NOT the standard OgreSDK? The Mogre SDK can be obtained from the [1]. The Mogre SDK will include Mogre.dll in the C:\OgreSDK\bin\debug and C:\OgreSDK\bin\release directories.
- Did you download and install the MogreFramework? This assembly is NOT required to use Mogre, but it will be used in all Mogre tutorials.
- Is your PATH variable properly set so that Ogre can find them?
- Did you add references to "Mogre.dll" AND "MogreFramework?
- To use the Direct3D9-Renderer you need to install the DirectX Redistributables from November 2007 or newer.
By this point you should be able to create and run an empty Mogre project. All subsequent tutorials will assume you can successfully set up an Mogre project.
Also, a possible way to speed up the creation of new Mogre projects is to create a new Templete. An example templete is available here: BasicMogreSetup. NOTE- this templete is only able to be used with Visual Studios 2008 C#. A tutorial on how to create a templete is available here: How to Create a Templete in VSC# 2008.
- Proceed to Mogre Basic Tutorial 1 The SceneNode, Entity, and SceneManager constructs | http://www.ogre3d.org/wiki/index.php/Mogre_Basic_Tutorial_0 | crawl-002 | refinedweb | 961 | 59.7 |
Write on lisp. Compile to pure javascript without runtime dependencies. Enjoy compiler that can guess your thoughts and generate intentionally missed parts of code.
MetaJS is yet another attempt to create better programming language for modern world. More about MetaJS background, why it was chosen Lisp-syntax and why it's compiled to Javascript, you can find on coect.net/metajs/. Project Coect aims to replace outdated Email and XMPP with modern universal communication protocol.
MetaJS for Coect plays the same role as Emacs Lisp for Emacs. MetaJS is written in MetaJS and can recompile itself. Look at the interactive MetaJS-documentation where you can try MetaJS without leaving your browser.
Knowledge-oriented programming as opposed to object-oriented or functional one gives main priority to semantic models of the program instead of building blocks of the program (objects or functions). Each semantic model (in the form that compiler can understand) is called logos.
You can find more information about semantic code transformations, examples of symbolic and entitative MetaJS to JavaScipt transformations in the metajs_semantic_code_transformations.pdf. Please look also at the high-level MetaJS language overview metajs_lisp.pdf.
MetaJS is compiled to Javascript code without runtime dependencies and don't use
own datastructures (like for example ClojureScript does). MetaJS uses native
Javascript's arrays as lists and so can perform in any Javascript environment
without unnecessary overhead. JSON documents are valid MetaJS documents and so
can be included with usual
include. MetaJS tries to generate beautiful
javascript code that passes JSHint without warnings. The generated code is
compatible with EcmaScript5. For
legacy browsers like IE8 it should be used
es5-shim or other
polyfill.
MetaJS is implemented in MetaJS and you can extend language easily by adding new
macros. For example, to add support of
yield keyword introduced in
Javascript 1.7
just create a macro like:
(defmacro yield (x)`(js "yield %" ~x))
MetaJS supports destructuring across all forms that accept name-value bindings:
(def actors ["Neo" "Trinity" "Morpheus"][neo trinity morpheus] actors)(let digits [1 2 3][one two three] digits(set [one two three] digits))
Forms can be chained with well-known
-> macro. For chaining methods calls often
used in javascript libraries like jQuery or
D3 there is also special syntax based on method hooks. For
example let's look at following code-sample from
D3 homepage:
d3;
and rewrite it in MetaJS using hooks and short anonymous functions:
(d3 .selectAll "circle" .transition.duration 750.delay #(* %2 10).attr "r" #(Math.sqrt (* %1 scale)))
To define a macro you can use standard Lisp syntax-quote, unquote and unquote-splicing:
(defmacro when (x & code)`(if ~x (do ~@code)))
Functions can have optional parameters and parameters with default values. Each parameter can be passed positionally or as keyword. In addition function can accept variable number of parameters that are accessible as list. Shortly syntax for keyword-only function parameters will be finalised.
;; 'a' is required, 'b' is required and associated with an entity 'Thing';; 'c' is optional, 'd' is optional and has default value 2, 'more' holds rest positional parameters(defn demo-fn (a b:Thing c:? d:2 & more)(log a b c d more));; an example of the function call(demo-fn "Just A" "noumenon" c:42)
You can embed variables inside interpolated
strings that are started with
#.
Inside such strings
$symbol is replaced with symbol's value and
$=var
replaced with pair name=value. For escaping
$ itself use
$$.
(= #"Hello, $nickname!" (str "Hello, " nickname "!"))
MetaJS is under active development. In the nearest plans is to finish javascript source maps support and explicit semantic code transformations. Then add namespaces and integrate support of Browserify. You can see full list of planned changes and offer your own.
Firstly, please install Node.js.
If you want to install latest development version of MetaJS:
$ git clone cd ./metajs$ npm install$ npm link .
If you don't plan to rebuild MetaJS and just want to try it:
$ npm install -g metajs
You have just installed MetaJS and become qualified for a MetaJS-developer T-shirt. It's time to dive into MetaJS:
$ metajs -x test/index.mjs # run MetaJS test suite$ metajs --lint test/index.mjs # check unit tests for errors$ metajs --lint --lint-log-level=1 test/index.mjs # show only Lint errors, hide warnings and hints$ metajs # start TEPL (Translate Eval Print Loop)$ metajs src/cli.mjs # compile single file to stdout$ metajs test/def.mjs test/hook.mjs --output ./ # compile 2 files to the working directory$ metajs -e "(+ 2 2)" # advanced calculator$ metajs --help # print help to stdout$ make # rebuild MetaJS compiler and run test suite
If you use Emacs you will enjoy MetaJS-support for flymake mode. The simplest method is to use my fork of flymake, however you can also extend standard flymake with MetaJS support (use this changeset as a hint). With flymake you will receive MetaJS feedback in real-time mode during edithing the code.
Add any bugs or feature requests to the issues page. Follow @meta_js or d0gada on Twitter to receive latest metajs news. Like MetaJS page on Facebook. Join our mailing list. Please visit to find more docs and examples. it in both cases. | https://www.npmjs.com/package/metajs | CC-MAIN-2018-05 | refinedweb | 861 | 57.27 |
Whether you are doing pre or post mortem debugging, whether you are using Visual Studio or WinDBG, one of the most important things you can do ( short of not writing the bug in the first place! ) to ready yourself for a productive debugging session is to establish the use of Symbol and Source servers. I’m going to give you some quick pointers of how to make use of these technologies in your day – to – day development process.
What is it? Essentially, a symbol server is way to expose the symbols ( PDBs ) of your applications to the debugger in a way discoverable by the debugger regardless of where the debugger is run. This same thing is also true for system symbols as well. Not only that, it is a way to handle the versioning of those PDBs so that the debugger understands how to find version one of your symbols, vs. version two, and so on.
That’s all well and good, but why is this a good thing for the developer? Let’s look at what things look like when you *don’t* have a symbol server established.
Here’s some sample code you have undoubtedly seen a zillion times by now:
using System;namespace DebuggingSeries{ class Program { static void Main( string[] args ) { Console.WriteLine( "Hello World" ); } }}
After a moment, you will hit the breakpoint. Now, open up the Modules window ( while in the debugger, select the Debug->Windows->Modules menu item ):
While will open a tool window that looks something like the one below:
The “Modules” tool window shows you all the images ( dlls, etc. ) that are loaded in order to run the executable you are currently debugging. ( NOTE: This is a very useful tool window that many folks don’t know is available in the product, and has many uses which we won’t have a chance to go through today, but more some other time. )
You’ll notice in the image above that there is a Column called “Symbol Status”. Assuming you are running with default debugging settings that Visual Studio 2010 has shipped with, you’ll also notice that almost all the rows in the tool windows except the one I highlighted have the value “Skipped loading symbols.”. The one highlighted is the actual executable itself, which contains the symbols associated with the code you typed in. You’ll also notice that the “User Code” column is “No” for everything except for this last entry as well. More on this later.
Now bring up the “Call Stack” toolwindow ( Debug->Windows->Call Stack ). You should see something like this:
Cool, now let’s see what changes once you start using a Symbol Server, but there is actually one other thing you’ve gotta do before you see the goodness of the Symbol Server. You’ll need to turn off the “Just My Code” feature in Visual Studio.
By default, Visual Studio 2010 has the “Just My Code” option turn on. This on on by default as it tends to reduce the amount of information a new user has to deal with when initially debugging inside Visual Studio. It tries to protect you by not drowning you in information.
I struggle with this option, as the intent of it is quite good, but in practice, I tend to always turn this off. ( I would love to hear your thoughts on whether or not this option should be on or off by default. Please fill the comment section with those thoughts! )
For the purposes of this post on this series, please turn off this option. Here’s how:
Go into “Tools-Options…” dialog, find the “Debugging” option on the left side of the dialog, and notice the “Enable Just My Code” option on the right:
Uncheck that box so that your dialog looks like this:
Now your ready to see the effects of the Symbol Server option.
Go back into the “Tools->Options…” dialog, and expand the “Debugging” option, and select the “Symbols” option:
Go ahead and click the check box next to “Microsoft Symbol Servers”. You should see a dialog box popup that you can safely ignore for now.
If you hit OK at this point, VS will automatically fill in a default directory that it will use for PDBs it pulls down from a public Microsoft site that contains the PDBs tied to the various versions of the framework DLLs.
If you are on a team of developers, it is a good idea to establish a common file share that all members of your team can use to house these symbols so that you don’t have to wait for the download of those images while you debug. The first developer who needs them would feel that delay, but everyone else on the team would simply pull from the common share.
For now, take the defaults and hit F5 again. You should be in the debugger waiting at the breakpoint.
Take a look at your Modules window now:
Notice how everything is loaded ( Symbol Status column reads “Symbols loaded.” ) and the User Code column reads “N/A”, ‘cause we disabled the “Just My Code Feature”
If you had turned on the Symbol Server options as described above but failed to turn off “Just My Code”, you would have seen something like the following in the Modules window, indicating that symbols were available to be loaded, but Visual Studio did not do so in order to abide by the constraints associated with “Just My Code”. Also, your call stack would look exactly the same as it did before.
Now take a look at your call stack window:
Compare this with the image of the call stack with the one I previously showed you above. Notice how much more information is now available to you?
And therein lies the point of all this:
When you are debugging, you need as much information as you can get in order to figure out the task at hand. You never know what little piece of information will be the clue that drives you towards the final solution.
This post is just scratching the surface. Next post in this series, I’ll dig a little further into some more of the benefits of the symbol server, and why making your own symbols available to your team in this manner will benefit you.
Cheers!
Cameron | http://blogs.msdn.com/b/camerons/archive/2011/04/01/debugging-series-symbol-server.aspx | CC-MAIN-2014-52 | refinedweb | 1,062 | 65.96 |
Most of my programming has been hobbyist-theoretical and reading more blogs than is probably healthy. I'm sick of it. I wanna make a game.
I'm going to make a game, using my current game engine.
Presenting SimpleRTS Update 1:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using...
Narf the MouseMember Since 20 Apr 2006
Offline Last Active Jul 30 2013 12:55 AM
Community Stats
- Group Members
- Active Posts 1,008
- Profile Views 5,940
- Submitted Links 0
- Member Title Member
- Age Age Unknown
- Birthday Birthday Unknown
- Gender
Not Telling
318 Prototype
User Tools
Contacts
Narf the Mouse hasn't added any contacts yet. | http://www.gamedev.net/user/100991-narf-the-mouse/?tab=blog | CC-MAIN-2016-40 | refinedweb | 112 | 58.69 |
How to disable auto orientation in Flash Lite 4 of N8?
How to disable auto orientation in Flash Lite 4 of N8?
hi yeggo,
i was not able to give it a try till now in FL4 but maybe this article can help you:
BR
Thank you for your sharing!
And I found this code for Flash Lite 3.1:
fscommand2("DisableKeypadCompatibilityMode");
fscommand2("FullScreen", "true");
Stage.scaleMode = "noScale";
import com.nokia.lib.Device;
var deviceObject:Object = new Device();
deviceObject.DisableAutoRotation(true);
But is there a Flash Lite 4.0 version? Where can I find the NOKIA API for Flash Lite 4.0?
Flash Lite 4.0 supports Actionscript 3.0 and is based on Flash Player 10. There is no separate API specific to the version. You can read more about FL 4 on this link
Regarding the auto-rotation disabling code, what you've mentioned will work fine on the N8 even if you compile your program with FL 3.
fscommand2("fullscreen", "true");
fscommand2("DisableKeypadCompatibilityMode");
Stage.scaleMode = "noScale";
Stage.align = "TL";
import com.nokia.lib.Device;
var deviceObject:Object = new Device();
deviceObject.DisableAutoRotation(true);
Mariam
Mariam Dholkawala
MaD UG -
Thank you for your advice.
However I want to use AS 3, so that I cannot use that disabling code.
I found that the following code works in AS3:
public function Main()
{
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.addEventListener(Event.RESIZE, onResize);
}
private function onResize(e:Event):void
{
if (stage.stageWidth > stage.stageHeight)
{
rotation = -90;
x = -140;
y = 500;
}
else
{
rotation = 0;
x = 0;
y = 0;
}
}
But there is still a blink when I rotate the phone, not a perfect solution.
The blink is inevitable using that method, and it's the only way I'm aware of. From my experience it is not a problem as far as OVI test criteria are concerned. I've seen Flash games with it, because it is the only way for FL below 3.1 version (many S60 5th edition devices come with FL 3.0).
As for:
deviceObject.DisableAutoRotation(true)
I don't know any AS3 equivalent. Shame, it's kind of going backwards, let's hope there'll be a similar lib to do that in the future.
Last edited by RomanAge; 2010-11-11 at 17:20.
Don't know about FL4 on N8 but I set landscape or portrait modes as default and without auto orientation via the WGZ route on applications I write for touch screens.
In the main.html file I set dimensions to 360 by 640 and do the same with the general.css file in the style folder. This seems to force portrait - I have tried the opposite (640 by 360) and it forced the application to run in landscape mode; both times without auto orientation.
Regards
Hi,
Little bit disappointed after reading this thread that we don't even have a lock orientation basic feature in Flash Lite 4 (via AS 3). Hope it will be implemented in future. For now, we can use either rotation (which is not perfect in all cases) or just show a popup showing that please, rotate your device for full screen. Moreover, as Seth Muriithi already discussed that we can use wgz for locking the orientation which is actually done by calling javascript :
How_to_switch_orientations_in_WRT_WidgetHow_to_switch_orientations_in_WRT_Widgetwindow.widget.setDisplayPortrait(); //or
widget.setDisplayLandscape();
Wish u luck
Best Regards,
SajiSoft
Projects: sajisoft.com/projects.html
Blog: sajisoft.wordpress.com
--§ajid Ali Anjum-- | http://developer.nokia.com/community/discussion/showthread.php/213209-How-to-disable-auto-orientation-in-Flash-Lite-4-of-N8?p=797982 | CC-MAIN-2014-15 | refinedweb | 568 | 68.26 |
#include <db.h>
int DB_ENV->set_cachesize(DB_ENV *dbenv, u_int32_t gbytes, u_int32_t bytes, int ncache);
int DB_ENV->get_cachesize(DB_ENV *dbenv, u_int32_t *gbytesp, u_int32_t *bytesp, int *ncachep);
Set.
It is possible to specify caches to Berkeley DB large enough split across ncache separate regions, where the region size is equal to the initial cache size divided by ncache.
The memory pool.Parameters
The DB_ENV->set_cachesize method may fail and return one of the following non-zero errors:
The DB_ENV->get_cachesize method returns the current size and composition of the cache.
The DB_ENV->get_cachesize method may be called at any time during the life of the application.
The DB_ENV->get_cachesize method returns a non-zero error value on failure and 0 on success.Parameters | http://www.oracle.com/technology/documentation/berkeley-db/db/api_c/env_set_cachesize.html | crawl-002 | refinedweb | 121 | 53.21 |
All the code we need will be in one file, main.cpp. Create that file with the code below:
#include <KApplication>
#include <KAboutData>
#include <KCmdLineArgs>
#include <KMessageBox>
#include <KLocale>.
The KAction is built up in a number of steps. The first is including the KAction library and then creating the KAction:
#include <KAction> ... KAction* clearAction = new KAction(this);
This creates a new KAction called clearAction..
You want to use CMake for your build environment. You provide a file CMakeLists.txt, cmake uses this file to generate all Makefiles out of it.
Create a file named CMakeLists.txt in the same directory as main.cpp with this content:.. | http://techbase.kde.org/User:Icwiener/Test | CC-MAIN-2013-20 | refinedweb | 107 | 70.5 |
If you want to integrate barcode scanning directly into your application without relying on having the separate ZXing application installed, then you can do so! It's an open source project and the code is available for free and can be downloaded at are going to add the whole ZXing project core to your app and modify as you wish. This way your app will no longer require ZXing app exist in client device.
ZXing uses phone or tablet camera to scan barcodes, QR codes or multi-format 1D/2D barcodes. So the scan result highly depends on the camera quality and resolution. ZXing has relatively fast processing speed. More importantly, it is an open source projectso you can do whatever changes you like to it!
Example source code for using Zxing barcode scanner from you application using Intent
Source for main.xml screen layout
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns: <TextView android: <Button android: </Button> <Button android: </Button> </LinearLayout>
Source for AndroidScanner.java program for barcode scanning
package com.as400samplecode; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class AndroidScanner extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { Button scanner = (Button)findViewById(R.id.scanner); scanner.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent = new Intent("com.google.zxing.client.android.SCAN"); intent.putExtra("SCAN_MODE", "QR_CODE_MODE"); startActivityForResult(intent, 0); } }); Button scanner2 = (Button)findViewById(R.id.scanner2); scanner2.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent = new Intent("com.google.zxing.client.android.SCAN"); intent.putExtra("SCAN_MODE", "PRODUCT_MODE"); startActivityForResult(intent, 0); } }); } catch (ActivityNotFoundException anfe) { Log.e("onCreate", "Scanner Not Found", anfe); } } public void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == 0) { if (resultCode == RESULT_OK) { String contents = intent.getStringExtra("SCAN_RESULT"); String format = intent.getStringExtra("SCAN_RESULT_FORMAT"); // Handle successful scan Toast toast = Toast.makeText(this, "Content:" + contents + " Format:" + format , Toast.LENGTH_LONG); toast.setGravity(Gravity.TOP, 25, 400); toast.show(); } else if (resultCode == RESULT_CANCELED) { // Handle cancel Toast toast = Toast.makeText(this, "Scan was Cancelled!", Toast.LENGTH_LONG); toast.setGravity(Gravity.TOP, 25, 400); toast.show(); } } } }
TIP: You can make your application check for existence of the Zxing application.
See IntentIntegrator for a possibly easier way to integrate. In particular this will handle the case where Barcode Scanner is not yet installed. Click on the link below for more details
Sample code from IntentIntegrator.java
private static final String PACKAGE = "com.google.zxing.client.android"; catch (ActivityNotFoundException e) { return showDownloadDialog(activity, stringTitle, stringMessage, stringButtonYes, stringButtonNo); } private static AlertDialog showDownloadDialog(final Activity activity, CharSequence stringTitle, CharSequence stringMessage, CharSequence stringButtonYes, CharSequence stringButtonNo) { AlertDialog.Builder downloadDialog = new AlertDialog.Builder(activity); downloadDialog.setTitle(stringTitle); downloadDialog.setMessage(stringMessage); downloadDialog.setPositiveButton(stringButtonYes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int i) { Uri uri = Uri.parse("market://search?q=pname:" + PACKAGE); Intent intent = new Intent(Intent.ACTION_VIEW, uri); try { activity.startActivity(intent); } catch (ActivityNotFoundException anfe) { // Hmm, market is not installed Log.w(TAG, "Android Market is not installed; cannot install Barcode Scanner"); } } }); downloadDialog.setNegativeButton(stringButtonNo, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int i) {} }); return downloadDialog.show(); }
More information on Zxing scanner application
According to
- EAN-8 and EAN-13
-. The values must match the names of
* {@link com.google.zxing.BarcodeFormat}s, e.g. {@link com.google.zxing.BarcodeFormat#EAN_13}.
* Example: "EAN_13,EAN_8,QR_CODE"
*
* This overrides {@link #MODE}.
*/
public static final String FORMATS = "SCAN_FORMATS"; intent.putExtra("SCAN_FORMATS", "CODABAR");
List of barcode formats supported by ZXING
/** QR Code 2D barcode format. */ public static final BarcodeFormat QR_CODE = new BarcodeFormat("QR_CODE"); /** DataMatrix 2D barcode format. */ public static final BarcodeFormat DATA_MATRIX = new BarcodeFormat("DATA_MATRIX"); /** UPC-E 1D format. */ public static final BarcodeFormat UPC_E = new BarcodeFormat("UPC_E"); /** UPC-A 1D format. */ public static final BarcodeFormat UPC_A = new BarcodeFormat("UPC_A"); /** EAN-8 1D format. */ public static final BarcodeFormat EAN_8 = new BarcodeFormat("EAN_8"); /** EAN-13 1D format. */ public static final BarcodeFormat EAN_13 = new BarcodeFormat("EAN_13"); /** UPC/EAN extension format. Not a stand-alone format. */ public static final BarcodeFormat UPC_EAN_EXTENSION = new BarcodeFormat("UPC_EAN_EXTENSION"); /** Code 128 1D format. */ public static final BarcodeFormat CODE_128 = new BarcodeFormat("CODE_128"); /** Code 39 1D format. */ public static final BarcodeFormat CODE_39 = new BarcodeFormat("CODE_39"); /** Code 93 1D format. */ public static final BarcodeFormat CODE_93 = new BarcodeFormat("CODE_93"); /** CODABAR 1D format. */ public static final BarcodeFormat CODABAR = new BarcodeFormat("CODABAR"); /** ITF (Interleaved Two of Five) 1D format. */ public static final BarcodeFormat ITF = new BarcodeFormat("ITF"); /** RSS 14 */ public static final BarcodeFormat RSS14 = new BarcodeFormat("RSS14"); /** PDF417 format. */ public static final BarcodeFormat PDF417 = new BarcodeFormat("PDF417"); /** RSS EXPANDED */ public static final BarcodeFormat RSS_EXPANDED = new BarcodeFormat("RSS_EXPANDED");
Thanks for the example code. It was just what I needed to get started.
I pasted it into my test app and it worked with no issues.
Much appreciated
Hi John,
Can you share your application ( Working project source code).
I am novice on Java & Android. But i really wish to learn from the working project.
Please advise.
Thank you.
Regards,
Mic
Dear John,
I just move from c# programming to Android/Java programming. Could you please share your simple application to use Zxing for studying? I am very new in Java and I start using eclipse too.
Thank you very much,
Thanin
Hi John,
I was trying to run QR Scanner application by using above sample code, but its automatically exit the application.
I have added also core jar (Zing) file to application.
Could you send your whole application to gsp.437@gmail.com
pls i need help, i copied the codes above and pasted into a new project in my ADK, but it was realling giving me errors.
the truth is i am a noob in both android and java development, and i really need a software that will scan a qrcode, it is a fragment of a system i am working on as an academic project, pls help me
hi john can u pls help me regarding this code????????????????
Hello, even I am developing a barcode scanner, so do I need to add a camera code into it..? And what about the scanning result? I want the output to be the price of the product. How do I integrate the sqlite code and all... Please help me asap
No you needn't to add camera code into it. Scanning result can be retrieved in onActivityResult method. you may store the price in your sqlite database.
you can see result in (onactivityresult();) method if u hav ua own product and wanna to give ua own price den u can save in database and can get it..but u can also check the result by internet also ...
You can use the scanner as shown in the example above. It needs the zxing barcode app to be already installed on the device. Or you can code your app to check if the barcode app is installed or not, and if not installed then guide the user to the market for download.
Another approach will be to download the source code for the zxing project and put it in your project so you will not have to depend on the other app and it will get deployed with yours.
Now to get prices you must take the barcode and fetch the price from SQLite database or a HTTP request. There are examples available in this blog to help you.
Would like codabar format support, but otherwise it's great.
There is support for codabar format in zxing. I have added a section above to explain.
Thanks a lot. Okay, I've got yet another query in my mind.. What if I want to construct my own database for products alongwith their prices? I googled a lot but dint find any article on sqlite that wud suffice my needs...
You can look at this for SQLite query from your database of items and prices...
Android SQLITE query selection example
Sheetal,
Sounds like we are working towards completing the same type of project. I had decided to create a barcode scanning app from my Tech Capstone project...this has been a nightmare! Maybe by collaborating of what we have accomplished, we can help each other out. Like they say 2 heads are better than one! You can email me also jblack0526@yahoo.com.
I hope to hear back from you.
Hi, I am scanning the barcode using zxing. everything is fine but i am facing problem i.e., while scanning i found some extra icons i.e., topleft, right top and bottom right icons. instead of that icons i need 2 put my own button i.e., close button. how can i achieve this?? this is my mail id s.seshu143attherategmaildotcom.
thanks in advance. i need asap..
Satya,
I guess if you calling the zxing barcode app then you have no control over the screen. May be you need to download the source code and put that in your project and modify it.
Hello,
I am developing barcode scanning application by integrating ZXing into my app,I can launch it and scan flawlessly but I want to store scanned barcode values onto mobile,am totally stuck here,So could anyone help me doing this
Need more detail on what you are trying to do.
Anyway after you get the scanned barcode value you can store it in a SQLite database or make Web Request to store it on a server database.
Lot of people seem to be looking for a solution to this problem. Let me explain:
I am developing a mobile app which needs barcode scanning. However after the scan, I want to handle the results myself.
So in essence, I want to launch barcode scanner and once it scans a barcode, I want it to return it back to my app so I can manipulate it. Currently I am facing these issues:
1. When I launch barcode scanner, it takes user to the app and user has to press "open" button to launch it. Is there a way to avoid this?
2. After barcode scanner scans a code, the only options are to act on it (open in browser etc.), instead I want it to automatically (or after pressing close) return the data back to my app, so I can use it.
3. I am currently using phonegap + other abstract frameworks. This means I cannot use the source code of barcode scanner directly in my app.
It should be very easy to add support to barcode scanner where, if a parameter "returndata" is passed, after scanning it simply returns the data to calling app?
hey can you please tell me the barcode scanner application in android.
i read the zxing application i want to convert number to qrcode in android.
can u please tell me how can i convert?
if possible try to send the links or source code to my mail\
shankarraopilli@gmail.com
hi,
I'm having a problem with some samples above. Do I have to use the zxing to your example? BTW, I'm new for androids. You can send me back here. >> error22.mekhef@ymail.com
tnx a lot . .
Yes you need the Zxing app in your phone or tablet for this demo app to work. To avoid that you have to get the source from the zxing website and put that in your project. There are instructions about that in the site itself. I haven't tried that yet!
Can You explain me please how to integrate Zxing library into our project?
how to use?:"Sample code from IntentIntegrator.java"
the app fc when the barcode scanner is absent..
i did not implemtn the sample code yet,because i don't know..pls help
phoenix_dragon21@yahoo.com
thank you so much for this tutorial.
I have a questions about no which is provided by scanner.
how to get complete information form given number.
i m waiting for your +ve response.
thanks and regards
rakesh
This application just scans the Barcode and provides you with the scanned value. After that you can take the value and make a HTTP request to your Web service and get all the information about the Product from your ERP backend system.
Hi all, I would really appreciate if someone can upload a working android project with code to help me get started
Nice one thanks for sharing...!!
i want to convert my app from version 14 to version 12, plz help me.
Here is an Android barcode encoder which works nice!
The above code works flawlessly when I used QR code.But when I try to scan product barcode using Scan BAR code ,it doesnt seem to work.I try to click camera button but nothing happens..Has anyone got that part working or guide me in resolving the issue
also product barcode is working now but is slow as compared to the qr reader
The qrcode will always scan faster than the barcode.
Nice post.Give it up. Thanks for share this article. For more visit:android development
How to add library for this application and where to place IntentIntegrator.java file.Is there any requirement to add library or not?If yes then from where to download it and wehere place it?Plrase give reply asap
You can send me solution on pooja_patel_aaa@yahoo.com
Thanks for that
Nice post.Give it up. Thanks for share this article. For more visit:android development
can you send me the source please?
clbr@sapo.pt
thanks
Nice post.Give it up. Thanks for share this article. For more visit:android development
Hi, am started the bar code scanner but it seems to be not worked in my app, could u explain me how to add library for this application and where to place IntentIntegrator.java file, could tell me how to place library file then from where to download it and wehere place it..
or else can u send me on mail
bosekarthiks@gmail.com
Above code is working very well for QR CODE but it is not working for Bar Code scanning . So what is going wrong with me. Any help really Appreci
Hello, your application code and are great! Thank you for your work! I would like to use your code, it is sufficient to only scan the EAN me and send the URL, what should I do when editing code? Thank you for your time.
Hi
With the above code it works after we instal the barcode scanner application.
If I don't have that application, it will ask to install the application or it uses Google's default camera page opens (where we can see Google logo) to capture the image.
But my requirement is, it should neither open Google camera capturing images nor bar code scanner (zxing application) application. My should should take care opening the camera itself (off course it can use zxling library internally) and capture without dependent on any other app which is installed or not-installed.
Can QR code detect or trace "who ,when and from where qr scan".
can Qr code scan every Student individual id from single qr code.
Please send me base code. Please advice me.
Superb, its work fine without any issue... very much appreciated...
This was not that easy to manage, due to the limitation of Android library I was require to pull everything from Androidmanifest.xml.Chances are there you will overcome to runtime exception error which I did received.
I want to open the camera in the middle of the screen with the 4 square corner. Please Help me to do that.
how to use barcode scanner to check data in database?
it is working fo QR code but not working for any bar code like -
UPC_A
CODABAR
is any way to scan barcode (not QR code)
HI..I want to know How can I scan bar code without using camera...Plz explain me...Its Urgent..
Thanks..
I implement this scanner in my application. Intially it work file while i m trying it in my android mobile phone.. but after some time it showing "unfortunately has stopped" while pressing scan qrcode button.. Plz any body help to fix this issue
Agen Poker Online Indonesia Terpercaya
Hi.
Could you send me the code, please?
Thanks
hi john can u pls send me the whole app pls my email id is jainshilpi3@gmail.com
Works, great !!!!!
Great to apply to my next android pet project!
Hi.
Could you send me the code, please?
Thanks
This comment has been removed by the author.
Thanks for sharing this.
Exit Popup
Hey Cn u send me code on ruturaj.scriptoss@gmail.com please..
Thanx in advance..
public void buttonClick(View v) {
int id=v.getId();
switch(id) {
case R.id.scanner:
Intent();
break;
case R.id.scanner2:
Intent1();
break;
}
}
use above instead of button.setlistener.
For more details :nxo_1@yahoo.com
Hey Can you please send me code on devresources@yahoo.com
Thanks in advance.
Please send complete source code on akashgarg1000@gmail.com .
That code is creating unfortunatelly shut down .and after that application is closed.
Hello, Please somebody can send mi, please? byakuyana@gmail.com A lot of thanks!
i want to discuss about the augmented reality, can any body help me?
Thank u for sharing such nice information. Now I realize the importance of promoting android apps. The ways suggested are quite efficient for promoting android apps.
Total Recall Recording App
one problem in this app..if i am not installed "barcode scanner" in my device then its not working .and i don't want to depend on another app.so please give proper solution .and you also send proper solution on sumiraj.singh.rs@gmail.com
thank for you totourial. but it can do saved data of qr code in private database what act and what android code to it and php. please help me and thanks for all
Need someone to work on a QR project. Contact me if interested at 4pbohara@gmail.com
Thanks
Great and Useful Article.
Online Java Training
Online Java Training from India
Online Java Training
Online Java Training From India
Java Training Institutes in Chennai
Java Training in Chennai
Java Interview Questions
Java Tutorials
Please send complete source code on nassaus@yahoo.com
Fantastic articles is post by you in this blog
Bulk SMS Software | Bulk SMS Gateway | Voice Broadcasting
Informative post you have shared. Thanks for sharing.
Transactional SMS Service in Chennai
Hi,
How to use barcode scanner according to the instructions below?
First my class and after the instructions.
I've installed the scanner app and Can access it. But I cannot reach onactivityresult method.
Thanks for your attention.
package com.mycompany.my2app;
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.content.*;
import com.google.zxing.integration.android.*;
import android.bluetooth.le.*;
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onScanButtonClick(View view)
{
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.initiateScan();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
// handle scan result
String conteudoScan = scanResult.getContents();
Toast.makeText(this, conteudoScan, Toast.LENGTH_LONG);
}
// else continue with any other code you need in the method
}
/*
*
* To integrate, create an instance of {@code IntentIntegrator} and call {@link #initiateScan()} and wait
* for the result in your app.
*
* It does require that the Barcode Scanner (or work-alike) application is installed. The
* {@link #initiateScan()} method will prompt the user to download the application, if needed.
*
* There are a few steps to using this integration. First, your {@link Activity} must implement
* the method {@link Activity#onActivityResult(int, int, Intent)} and include a line of code like this:
*
* {@code
* public void onActivityResult(int requestCode, int resultCode, Intent intent) {
* IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
* if (scanResult != null) {
* // handle scan result
* }
* // else continue with any other code you need in the method
* ...
* }
* }
*
* This is where you will handle a scan result.
*
* Second, just call this in response to a user action somewhere to begin the scan process:
*
* {@code
* IntentIntegrator integrator = new IntentIntegrator(yourActivity);
* integrator.initiateScan();
* }
*
* Note that {@link #initiateScan()} returns an {@link AlertDialog} which is non-null if the
* user was prompted to download the application. This lets the calling app potentially manage the dialog.
* In particular, ideally, the app dismisses the dialog if it's still active in its {@link Activity#onPause()}
* method.
*
* You can use {@link #setTitle(String)} to customize the title of this download prompt dialog (or, use
* {@link #setTitleByID(int)} to set the title by string resource ID.) Likewise, the prompt message, and
* yes/no button labels can be changed.
*
* Finally, you can use {@link #addExtra(String, Object)} to add more parameters to the Intent used
* to invoke the scanner. This can be used to set additional options not directly exposed by this
* simplified API.
*/
}
Using this works for me well for this. It's great
I am getting no activity found to handle intent exception, even though its inside the try catch block.the "startActivityForResult(intent, 0);" gives error for "com.google.zxing.client.android.SCAN"
i used this library to read boarding pass .However it only scans if the code is in the centre of the screen.Is this the limitation of the library | http://www.mysamplecode.com/2011/09/android-barcode-scanner-using-zxing.html | CC-MAIN-2016-36 | refinedweb | 3,579 | 59.9 |
I want to execute a program as normal user unsharing the network namespace.
What misconceptions are you thinking?
I was puzzled about somebody who knew enough about namespaces to have a use case for them didn't know about how to run a program as another user. Ropid provided a solution.]]>
Check this out (if "ezzetabi" is your username):
sudo unshare -n sudo -u ezzetabi bash -c 'echo Hello, my name is $USER; echo My home is $HOME; echo; echo Here is the output of "id":; id; echo; echo I can see these networks:; ip a'
I want to execute a program as normal user unsharing the network namespace.
What misconceptions are you thinking?
Please provide more details about what you want to do with noshare, maybe we can get misconceptions out of the way.]]>
From what I saw unshare needs to be executed as root...
% sudo unshare -n -- id uid=0(root) gid=0(root) groups=0(root) ... % unshare -n -- id unshare: unshare failed: Operation not permitted
However, I would like to start an application as normal user because otherwise it saves all its files in the /root directory. Is there a way?]]> | https://bbs.archlinux.org/extern.php?action=feed&tid=205240&type=atom | CC-MAIN-2020-10 | refinedweb | 194 | 71.14 |
13.4. Simulating a stochastic differential
Stoch numerical method called the Euler-Maruyama method. It is a simple generalization to SDEs of the Euler method for ODEs.
How to do it...
1. Let's import NumPy and matplotlib:
import numpy as np import matplotlib.pyplot as plt %matplotlib inline
2. We define a few parameters for our model:
sigma = 1. # Standard deviation. mu = 10. # Mean. tau = .05 # Time constant.
3. Let's define a few simulation parameters:
dt = .001 # Time step. T = 1. # Total time. n = int(T / dt) # Number of time steps. t = np.linspace(0., T, n) # Vector of times.
4. We also define renormalized variables (to avoid recomputing these constants at every time step):
sigma_bis = sigma * np.sqrt(2. / tau) sqrtdt = np.sqrt(dt)
5. We create a vector that will contain all successive values of our process during the simulation:
x = np.zeros(n)
6. Now, let's simulate the process with the Euler-Maruyama method. It is really like the standard Euler method for ODEs, but with an extra stochastic term (which is just a scaled normal random variable). We will give the equation of the process along with the details of this method in the How it works... section:
for i in range(n - 1): x[i + 1] = x[i] + dt * (-(x[i] - mu) / tau) + \ sigma_bis * sqrtdt * np.random.randn()
7. Let's display the evolution of the process:
fig, ax = plt.subplots(1, 1, figsize=(8, 4)) ax.plot(t, x, lw=2)
8. Now, we are going to take a look at the time evolution of the distribution of the process. To do this, we will simulate many independent realizations of the same process in a vectorized way. We define a vector
X that will contain all realizations of the process at a given time (that is, we do not keep all realizations at all times in memory). This vector will be overwritten at every time step. We will show the estimated distribution (histograms) at several points in time:
ntrials = 10000 X = np.zeros(ntrials)
# We create bins for the histograms. bins = np.linspace(-2., 14., 100) fig, ax = plt.subplots(1, 1, figsize=(8, 4)) for i in range(n): # We update the process independently for # all trials X += dt * (-(X - mu) / tau) + \ sigma_bis * sqrtdt * np.random.randn(ntrials) # We display the histogram for a few points in # time if i in (5, 50, 900): hist, _ = np.histogram(X, bins=bins) ax.plot((bins[1:] + bins[:-1]) / 2, hist, {5: '-', 50: '.', 900: '-.', }[i], label=f"t={i * dt:.2f}") ax.legend()
The distribution of the process tends to a Gaussian distribution with mean \(\mu = 10\) and standard deviation \(\sigma = 1\). The process would be stationary if the initial distribution was also a Gaussian with the adequate parameters.
How it works.... Also, \(W\) is a Brownian motion (or the Wiener process) that underlies our SDE.
The first term on the right-hand side is the deterministic term (in \(dt\)), while the second term is the stochastic term. Without that last term, the equation would be a regular deterministic ODE.
The infinitesimal step of a Brownian motion is a Gaussian random variable. Specifically, the derivative (in a certain sense) of a Brownian motion is a white noise, a sequence of independent Gaussian random variables.
The Euler-Maruyama method involves discretizing time and adding infinitesimal steps to the process at every time step. This method involves a deterministic term (like in the standard Euler method for ODEs) and a stochastic term (random Gaussian variable). Specifically, for an equation:
The numerical scheme is (with \(t=n * dt\)):
Here, \(\xi\) is a random Gaussian variable with variance 1 (independent at each time step). The normalization factor \(\sqrt{dt}\) comes from the fact that the infinitesimal step for a Brownian motion has the standard deviation \(\sqrt{dt}\) .
There's more...
The mathematics of SDEs comprises the theory of stochastic calculus, Itō calculus, martingales, and other topics. Although these theories are quite involved, simulating stochastic processes numerically can be relatively straightforward, as we have seen in this recipe.
The error of the Euler-Maruyama method is of order \(\sqrt{dt}\). The Milstein method is a more precise numerical scheme, of order \(dt\).
Here are a few references on these topics:
- Stochastic differential equations on Wikipedia, available at
- White noise, described at
- The Langevin equation on Wikipedia, available at
- The Ornstein-Uhlenbeck process described at
- Itō calculus, described at
- The Euler-Maruyama method, explained at
- The Milstein method on Wikipedia, available at
See also
- Simulating a Brownian motion | https://ipython-books.github.io/134-simulating-a-stochastic-differential-equation/ | CC-MAIN-2019-09 | refinedweb | 760 | 57.27 |
Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
10 months, 1 week ago.
Including c++ standard libraries
I'm trying to compile an existing firmware (originally written for NUCLEO-F767 using visual studio / VisualGDB) to a GD32F307VG-mbed -board. The code has following lines:
#include <list> #include <unordered_map>
compiling stops at the second line with error "no such file or directory". The first line goes through well.
This seems like a very basic thing. The library should be available, no?
Thanks and BR!
1 Answer
10 months, 1 week ago.
unordered_map was only added in c++11. <map> should be available for all platforms but unordered_map will depend on the compiler and settings used. | https://os.mbed.com/questions/86850/Including-c-standard-libraries/ | CC-MAIN-2020-29 | refinedweb | 134 | 69.07 |
Advertisement
Today we are going to look at how you can remove the background from an image or video frame. The method is known as background subtraction in OpenCV Python.
Let’s Code it!
Background Subtraction OpenCV Python Algorithm
Import Packages
import cv2 as cv
Computer Vision and NumPy packages are very important for working in OpenCV Python.
import numpy as np
If you feel uncomfortable in OpenCV Python basics have a look at OpenCV Basic Operations and Image Manipulation in OpenCV.
Capture Video for Background Subtraction OpenCV
cap = cv.VideoCapture(‘./img/vtest.avi’)
VideoCapture() is an OpenCV function in Python, It takes one parameter i.e the source of the video. 0 for Front Camera, 1 for Rear Camera, and for recorded video provide the Absolute or Relative Path.
MOG2 Background Subtraction OpenCV Python
There are two functions in OpenCV for subtraction namely MOG2 and KNN.
fgbg = cv.createBackgroundSubtractorMOG2(detectShadows=False)
If you do not want to detect shadows and remove them from the image, pass the argument detectShadows as False.
KNN Background Subtraction OpenCV Python
fgbg = cv.createBackgroundSubtractorKNN(detectShadows=False)
This is another algorithm for background subtraction, known as KNN. It also takes detect shadows argument as True or False. This OpenCV function will initialize background subtraction.
Reading Frames
ret, frame = cap.read()
Now read every frame from the video source. If retention is True it means the function successfully reads the frame from the video source.
Applying Background Subtraction in OpenCV Python
fgmask = fgbg.apply(frame)
In MOG2 and KNN background subtraction methods/steps we had created an instance of the background subtraction and the instance was named fgbg.
Now, we will use apply() function in every frame of the video to remove the background. The apply() function takes one parameter as an argument, i.e The source image/frame from which the background has to be removed.
Showing Frames on window
The background removed image “fgmask” is then shown using the cv.imshow() function.
The Subtracted frames are shown using a while loop that is true when the program is able to read the video. So we need some logic to end the program otherwise the program will be stuck in an infinite loop.
One way to end the infinite loop is to bind the Keyboard key to the program that will break the loop.
In this case, we are binding the Keyboard key ‘q’s to end the loop, and after that, all the created windows will be destroyed and the memory occupied will be released.
Note: Release the captured video that is read in the beginning, otherwise the machine’s memory will be full and the process will not work properly.
Background Subtraction OpenCV Python Code
This is the full code of the background subtraction function created in OpenCV Python.
def bs(): cap = cv.VideoCapture('./img/vtest.avi') # fgbg = cv.createBackgroundSubtractorMOG2(detectShadows=False) fgbg = cv.createBackgroundSubtractorKNN(detectShadows=False) while cap.isOpened(): ret, frame = cap.read() if frame is None: break fgmask = fgbg.apply(frame) cv.imshow('Frame', frame) cv.imshow('FG Mask', fgmask) if cv.waitKey(30) & 0xFF == ord('q'): break cap.release() cv.destroyAllWindows()
Background Subtraction GitHub
Get the Full Source Code at GitHub.
OpenCV Documentation
Look at the OpenCV Documentation for more knowledge of the functions. | https://hackthedeveloper.com/background-subtraction-opencv-python/ | CC-MAIN-2021-39 | refinedweb | 544 | 59.09 |
This is a long one. If you want to ease yourself into it, go and read the other ones for today which are much shorter and then come back to this one. Seriously - it’s a doozy. Pointers, one of the toughest part of C, is what we’ll be tackling today.
So you’ve had the past week to wrestle with pointers on your own, and no doubt you’ve all become something of self-made experts on the subject. So let’s have a rather simple warm-up puzzle. So what’s the output of this file?
#include <stdio.h> int main() { int a = 5, b = 15; int *p1, *p2; p1 = &a; p2 = &b; *p1 = 10; *p2 = *p1; p1 = p2; *p1 = 20; printf("a: %d ", a); printf("b: %d\n", b); printf("p1: %p p2: %p\n", p1, p2); return 0; }
Did you get it?
a: 10 b: 20 p1: 0x7fff58bbd754 p2: 0x7fff58bbd754
Of course, the particular pointer locations are irrelevant except in that
p1 and
p2 should be the same value; since the operating system is what allocates memory, these values should most likely be different each time you run the program. But in case you didn’t quite get the right answer, let’s break it down.
What’s a pointer? A pointer is just a variable that represents a location in memory. So after initializing
a and
b to
5 and
15 respectively, we create two addresses
p1 and
p2. How do we assign the two pointers to the addresses in which
a and
b are stored? We create a reference with the
& operator. The error most novices make is that the reference operator can never be on the left side of the assignment operator. This makes logical sense - you can’t change the address in which something is stored. All you can do is instead copy the same information held at that address to a new location, and then later
free whatever was held in the original location. Okay, so far so good.
The
* operator is known as dereferencing a pointer. It means we’re accessing not the address represented by the pointer, but the value in memory represented by that address. Unlike the reference operator, the dereference operator can be present on either side of the assignment operator. So
*p1 accesses the value that
a stores; in this case, we’re functionally resetting
a to be
10, and similarly we set
b to the same value.
Here is the part that may have confused some of you. We set
p1 to point to the same address to which
p2 points, so they are both manipulating the area of memory in which
b is stored. Then, we set that value to be
20, thus altering
b. And that’s it!
So now that we’ve had this quick three-minute review of pointers, we’re ready for some better puzzles.
This puzzle tests disambiguation of pointers. Fundamentally, we’re going to explore an array of
type versus pointer to
type. Here’s
pointer_test.c. What’s the output?
#include <stdio.h> int main(int argc, const char *argv[]) { int a[5] = { 1, 2, 3, 4, 5 }; int *ptr = (int *)(&a + 1); printf("%d %d\n", *(a + 1), *(ptr - 1)); return 0; }
You may remember from the lecture that the variable that represents an array is actually a pointer referencing the zero-eth element in that array. So in this example,
a is actually a pointer referencing
a[0] - in this case,
1. By that logic,
a + 1 merely references the next integer -
a[1]; thus, the first integer printed is
2. That’s the easy part.
The next one is a little tougher. If you treated
*ptr as a simple pointer to an integer – like you treated
a – you’d be tempted to give the following incorrect explanation:
Since
ptr points to the location of
a,
a + 1 merely points to the location of
a[1]; thus,
ptr - 1 goes back to referencing
a[0]. So the second number printed must be
1.
Nope! The trick here is that
ptr is not a pointer to an integer. It is a pointer to an array – which is entirely different. Pointer arithmetic on these two variables works entirely differently. A pointer to an integer, when incremented, will simply move up in memory by the number of bytes an integer represents. A pointer to an array, however, will move up in memory by the length of the array when incremented. Thus, when incremented, it moves up by five elements - to the slot in memory right after
5 in the array
a. When decremented, however,
printf is treating the output as a pointer to an integer, and not a pointer to an array. So when we subtract
1 inside the
printf statement,
ptr references
a[4] instead of
a[5], and dereferencing that gives us
5.
So the output is
2 5. Phew!
This puzzle is testing a concept known as pointer disambiguation, where the same pointer can be treated differently depending on the context. Let’s warm up our disambiguation skills with a little puzzle: What are the differences between the following three declarations.
int* arr1[8]; int (*arr2)[8]; int *(arr3[8]);
The first is an array of integer pointers - specifically, an array of length eight. The second is a pointer to an array of integers. And the third is the same as the first! So how the heck do we start evaluating these things? The difference here is critical. Operator precedence can be a rather esoteric subject – especially when function pointers get involved, as you’ll see next time – but there are a couple simple rules that can help you learn rather quickly how this works.
As the C Bible (K&R, as you all should know well by now) suggests using cdecl for any very complicated situations. It is wonderful, and you should definitely consider it.
Order of operations seems fairly obvious, and in general we encounter fairly trivial examples. But what about when you get something like the following:
char *(*(**foo[][8])())[];
[ ]) and “function returning” (
( )) have higher precedence than “pointer to” (
*).
foo is...
foo is... int
Let’s go through some examples.
long **foo[7];
As we go through the example, I’ll strikeout whatever we’ve delt with. We start with the variable, and end with the type.
foo is ... long. Okay, simple enough. Now let’s fill in the middle.
long ** foo[7];
“Array of” has the highest precedence, so we can and must go right. This gives us the sentence
foo is array of 7 long.
long ** foo[7]
Now, we’ve gone as far to the right as possible. This means we have no choice but to go left.
foo is array of 7 pointer to long takes care of the first “pointer to”, but we have on last pointer. Here is the final result:
foo is array of 7 pointer to pointer to long.
Think you’ve got the hang of it? Let’s try some really hairy examples to really get it down.
char * ( * ( * *foo [][8])())[];
We start as usual, with the variable and the simple type:
foo is ... char. Sweet, let’s see what we have left.
char * ( * ( * * foo [][8])())[]
Since
foo touches both “pointer to” and “array of”, we go right as much as we can. This gives us:
foo is array of array of 8 ... char
char * ( * ( * * foo [][8])())[]
Okay, now we have no choice but to go left. It has two “pointer to” phrases to add:
foo is array of array of 8 pointer to pointer to ... char
Leaving this:
char * ( * ( * *foo [][8])())[]
What do we do now!? There seems to be an empty set of parentheses? It must be a function call! This involves pointers to functions. Remember, we try and go right when we can. On the right is a function call, and on the left is a “pointer to”. Remember our rule – “function returning” has higher precedence. So here is our new sentence:
foo is array of array of 8 pointer to pointer to function returning ... char
This leaves us with the following:
char * ( * ( * *foo [][8]) () )[]
We would like to go right, but we have a set of parentheses that block our way. As you know, parens have a much higher precedence than anything else, so we must oblige and go left. This gives us the following:
foo is array of array of 8 pointer to pointer to function returning pointer to ... char
Which gives us this left over:
char * ( * ( * * foo [][8])() ) []
So all that’s left is an “array of” and a “pointer to”; as you well know, we can go right and then left, finishing off our sentence. That gives us the final result – the following mouthful:
foo is array of array of 8 pointer to pointer to function returning pointer to array of pointer to char
Wow!
Thought we were done? We’re just getting started. What we say in the more complicated example there was a function pointer – a pointer to a function. These nasty beasts are unique to C; in higher languages like C++, you should use polymorphism and virtual functions; thus, function pointers have been exclusive to C. Lucky you.
Why do we have pointers to functions? There are lots of cases where it’s more useful to design a function to be general purpose; this way, the function you’re writing can accept any function as a parameter and simply call that function. The most common example is sorting. Your sort function can take a compare function as a parameter – this way, you can write seven small compare functions and just a single sorting function, rather than seven long sorting functions. This follows good coding design of factoring out code as well.
Let’s start with a simple example.
void (*foo)(int);
Here,
foo is a pointer to a function that takes a single argument, an
int, and returns
void. The tip to make it easier is that you’re just writing out the function declaration but surrounding the function name by a set of parens. So
foo would be declared like this:
void foo(int a);
Pretty simple! What about this?
void *(*foo)(int *);
Again, re-writing the function header helps.
void *foo (int * a);
One interesting thing about function pointers is that the reference operator (
&) becomes optional, as does the dereference (
*). Because why not. Pointers were too simple anyways.
void foo(int a) { return a; } int main() { void (*func)(int); func = foo; func = &foo; func(5); (*func)(5); return 0; }
Both ways of assigning
func are legal, and both ways of calling
func are also legal. Here are some guidelines to keep in mind when talking about pointers and specifically function pointers:
void *foo; // legal void foo(); // legal void foo; // not legal void foo[]; // not legal
char foo[1][2][3][4][5] // legal char foo[] // legal char foo[][5] // legal char foo[5][] // not legal
Functions cannot return arrays; they can return pointers, and they can return pointers to arrays, but they cannot return arrays.
Functions cannot return functions. (We need to go deeper.)
Cannot have an array of functions.
But with function pointers, come abstract declarators. These wonderful little creatures are used in two places: casts, and arguments for
sizeof. They look something like this:
int ( * ( * ) ( ) ) ( )
This is another wonderful moment of sublime
.
It seems unfair, certainly. I told you to always start at the variable name, which led to the logical conclusion of giving you an example without a variable name. Put away your inhaler and calm down. There are four rules that govern where a variable can be:
There’s actually only two places in the given example that a variable can be using those syntax rules.
int ( * ( * x ) x ( ) ) ( )
The two
x’s represent the two possible locations of a variable. A quick look back at the fourth rule above tells us that there’s only one location, so we can read the abstract declarator as the following:
int (*(*foo)())()
which translates to:
foo is a pointer to function returning pointer to function returning int
So, after all this advice, when you’re reading some truly advanced C code, you won’t freak out when you see this:
BOOL (__stdcall *foo)(...);
You’ll think - hey! This is simple –
foo is a pointer to a __stdcall function returning BOOL . Piece of cake. I highly recommend you read this guide - it’s wonderful.
Multidimensional pointers aren’t too difficult. Let’s have a three dimensional array
buffer, where each of the dimensions are
10. We could directly index into it:
char buffer[3][4][5];
Or we could use pointers
*( *( *( buffer + 3) + 4) + 5);
Here,
buffer is a triple pointer; adding
3 moves it over to the third triple pointer. Dereferencing that gives us a double pointer, and adding four to that gives us the fourth double pointer. Dereferencing that gives us just a regular pointer, and adding five gives us the fifth pointer. Finally, one last dereference gives us just a regular
char.
That’s pretty much it! Here’s one puzzle just to make sure you really understood the concept.
int main() { char arr[5][7][6]; char (*p)[5][7][6] = &arr; printf("%d\n", (&arr + 1) - &arr); printf("%d\n", (char *)(&arr + 1) - (char *)&arr); printf("%d\n", (unsigned)(arr + 1) - (unsigned)arr); printf("%d\n", (unsigned)(p + 1) - (unsigned)p); return 0; }
The output should be
1 210 42 210
Why does this program give an error?
#include <stdio.h> void foo(const char **p) { } int main(int argc, char **argv) { foo(argv); return 0; }
This program uses a const pointer. This simply means that while the pointer itself can be changed, the memory it touches cannot change in value. In other words, it’s not the pointer that’s a const, but rather what it points to. This is why the
const appears before the
*. If you put the
const after the
* (like
int * const p_int = &x;) then you get a regular old pointer to an int, but this time the value of
p_int cannot change. Thus, it’s the pointer that’s a const.
Here is a hint to the for the code example above.
char const c = 'a'; char* p = 0; char const** pp = &p; // not allowed in C *pp = &c; // p now points to c. *p = 'b'; // changing a const value!
The first code snippet would work perfectly fine, without any warning, if
p were a single pointer instead of a double pointer. So why does this break with double pointers? This is known as const correctness in C. Although it is possible to cast from
char * to
const char * without warning, C will prohibit
char ** to
const char ** casting.
So why would this be prohibited? Imagine
p is a
char * – if so, logically, it could be used to modify whatever it’s pointing at. Imagine you have another pointer,
pp that points to
p. You could use
pp to assign to
p the address of a const char - you could even use
p to modify the const char, which might even be in read-only memory!
So why use
const? One misconception is that this can be utilized to make further optimizations. However, this is rarely the case. Usually, this is generally for conceptual clarity and readability.
Here is some further explanations of this issue in C. Oh, of course Alex Alain has another great tutorial.
Here are some awesome resources about pointer arithmetic and an awesome video series by Stanford University. | https://cs50.notablog.xyz/puzzle/Puzzle4.html | CC-MAIN-2018-43 | refinedweb | 2,604 | 72.66 |
Method takes exactly 2 arguments...but it doesn't...
I have a script that works great when run from within Pythonista. It calls another script by passing three arguments to it:
final = kraken(response['kraked_url'], path, name)
And this is what kraken() looks like:
def kraken(image_link,path,name):
However, when I run it as an iOS extension (which is what I really want to do), it ends up giving me this error:
TypeError: kraken() takes exactly 2 arguments (3 given)
What can I do to fix this?
What you have here looks like it should work. Could you please provide a minimal example that we can run that will throw this error?? | https://forum.omz-software.com/topic/3795/method-takes-exactly-2-arguments-but-it-doesn-t | CC-MAIN-2021-21 | refinedweb | 113 | 70.43 |
Tutorials > C++ > For Loop
Another effective looping method is the for loop. This is probably
the most frequently used of all the looping methods.
The for loop takes the form :
for ( initialization; logical expression; loop action ) { statements }
A description of each of the 3 sections inside parenthesis are shown below :
Contents of main.cpp :
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
int main()
{
string data;
In the code segment below, nothing is entered into the 3 sections of the
for loop. This basically causes no actions to be
taken before the loop or after each iteration. It also specifies that there
is no terminating condition. This will cause the for
loop to continue running forever, resulting in an infinite loop.
How do we get out of the for loop. You may remember
the break keyword from the switch statement tutorial.
This keyword allows you to break out of any loop or case statement. We can therefore
use it below to exit the loop when the user enters q.
for (;;)
{
cout << "Enter Data : ";
cin >> data;
if (data == "q")
break;
}
cout << endl;
The code segment below shows how a typical for loop
is used.
Before the loop starts, an integer i is created and assigned the value of 0.
The loop will continue running as long as i is less than 10.
No action is taken at the end of each iteration.
The code will therefore print out all values from 0 to 9. 10 is not printed out
as i is increased to 10 before the i < 10
is checked.
for (int i = 0; i < 10; )
cout << i++ << " ";
cout << endl;
The code below now shows how you can simplify the code above by utilizing the
3rd section of the for loop. An action can be
specified to occur at the end of each loop iteration. Our action is the incrementing (increasing)
of the i variable.
The code below will therefore print out exactly the same values as it did before, but the
code will be easier to read and maintain.
10 is not printed out as the action is run before the check at the beginning of the loop.
for (int i = 0; i < 10; i++)
cout << i << " ";
cout << endl;
You may find it necessary to stop running a particular iteration of a loop and
to start the loop again. The continue keyword can be useful
here. It basically moves execution to the end of the loop skipping all statements between
itself and the end of the loop.
In the code below, the printing out of the variable i
will be skipped if the value is even. Any value % 2 is always 0 if it is a multiple of 2 ie. even.
This could also be accomplished by using a simple if statement
but you may find a situation where the continue keyword is the only
option.
for (int i = 0; i < 10; i++)
{
if ((i % 2) == 0)
continue;
cout << i << " ";
}
cout << endl;
system("pause");
return 0;
}
You should now understand how to use probably the most widely used loop of them
all. In every useful program, you will find a number of for loops.
Please let me know of any comments you may have : Contact Me
Back to Top
Read the Disclaimer | http://www.zeuscmd.com/tutorials/cplusplus/17-ForLoop.php | CC-MAIN-2016-50 | refinedweb | 545 | 71.24 |
In this post we chart the shores of the undiscovered country, and show that drawing maps, such as the one shown in Figure 1, is not so difficult. We will make use of R’s powerful functions that allow plotting of maps, locations on those maps, and connecting lines that illustrate links between points of interest.
We will also make use of Python, as I have found it far easier to use the Python bindings for the GoogleMaps API. Our approach consists of three steps:
- Work out what you want to plot: the region, the nodes (ie, the locations), and the edges (ie, the connections between nodes).
- Get the coordinates of the nodes.
- Read and plot the data in R.
Step 1: What do you want to plot?
As a proud Australian, I am trying to increase the profile of my tiny country. All too often, the maps that I see on R bloggers are of the United States. Granted, the US has 300 million people and, despite the inexorable rise of China, remains the economic super-power of the world. Kudos to Uncle Sam. But Australia can boast a similar landmass, a bucket-load of natural resources, and more species of poisonous snakes and man-eating reptiles than any other country on the planet (a point that we have down-played since the unsuccessful tourism slogan “come to Australia and you might get eaten”). No, this article is going to be printed next to a map of the Land Downunder dammit!
To illustrate how one can plot points, label them, and connect them with lines, we will plot each of Australia’s state capitals, and connect selected pairs with lines. These lines will be based on the geodesic between the two points that uses the geosphere package (see here). To complete this task, there are three pieces of input data that you will require: a shape-file, a list of nodes, and an edge-list.
Shapefile
I have used a shape-file located here:. This website also contains shape files for other countries and is definitely worth a look.
List of nodes
The nodes could be anything from airports to electricity transmission hubs. In my case, the nodes are just the capital cities of each of the states and territories. The list, which I have stored in the CSV file “CapitalCities.csv“, consists of two columns: the name and the state/territory of each city.
Edge-list
The edge-list contains two columns: the ‘from’ column and the ‘to’ column. Each entry represents a connection between two nodes. In this instance, the two columns are interchangeable as the network is not directed, however, it would be easy to incorporate this feature. The edge-list that I have used can be accessed here.
Step 2: Get the coordinates of the nodes
Getting coordinates of a specific location is a simple affair thanks to the wonders of Google Maps and Google Earth. The problem is not how to get the data, but instead how to get it programmatically. For ten nodes, you can just as easily do this manually. For 1000 nodes, you can either find some intern to sit in front of Google Earth for the next week, or accept that there must be a better way.
I am sure that there are solutions to this problem that use R, but I have not yet found anything that is as quick and easy as the Python wrappers for the Google Maps API. (If you are unfamiliar with Python, then I advise you to take the time to learn the basics – your time will not have been wasted.) The module can be downloaded at or via easy_install. An API key is needed to interface with the GoogleMaps API, but this is easy enough to obtain – just search for ‘Google Maps API key’ and follow the instructions.
The following script retrieves the latitude and longitude of each city in the file ‘CapitalCities.csv’, and copies them into a new file ‘CapCoordinates.csv‘.
from googlemaps import GoogleMaps
import csv
ifile=csv.reader(open('CapitalCities.csv','rb'),delimiter=',')
ofile=open('CapCoordinates.csv','wb')
w=csv.writer(ofile,delimiter=',')
w.writerow(['Name','State','Latitude','Longitude'])
gmaps=GoogleMaps(API_KEY)
count=0
for row in ifile:
if count!=0:
address=str(row[0])+" "+str(row[1])
lat, lng = gmaps.address_to_latlng(address)
w.writerow([str(row[0]),str(row[1]),str(lat),str(lng)])
print row[0],lat,lng
count+=1
ofile.close()
Step 3: Plotting the map in R
At last we arrive at the R portion of this article. We will need to load four packages: the maps, sp, maptools, and geosphere libraries. Below is the complete code.
# Load necessary packages
library(maps)
library(sp)
library(maptools)
library(geosphere)
# Function that returns coordinates of a given location
getCoords<-function(location,df){
return(df[match(x=location,df[,"Name"]),][,c(4,3)])
}
# Plot a great circle from 'from' to 'to' names.
plotLine<-function(from,to,df){
inter<-gcIntermediate(p1=getCoords(from,df),
p2=getCoords(to,df),
n=50,addStartEnd=TRUE)
lines(inter, col="green",cex=2,lwd=2)
}
# Read in the Australia Shapefile
ozDATA<-readShapeSpatial("AUS_adm1")
# Read CSV file containing coordinates and edges
nodes<-read.csv(file="CapCoordinates.csv",sep=",",header=TRUE)
edges<-read.csv(file="EdgeListCapCities.csv",sep=",",header=TRUE)
# Plot the graph itself
plot(ozDATA,lwd=0.01,bg="#242424",col="#0000CD",ylim=c(-46,-10),xlim=c(125,145))
# Plot the nodes on the graph
points(nodes$Longitude,nodes$Latitude,pch=16,cex=1.5)
# Label the nodes
text(nodes$Longitude,nodes$Latitude,nodes$Name,cex=1,adj=0,pos=2,col="#C2C2C2")
# Plot each of the edges between nodes
for (j in 1:nrow(edges)){
plotLine(edges[j,]$From,edges[j,]$To,nodes)
}
Line-by-line walkthrough
We start by reading in the Australia shape-file using the readShapeSpatial function from the sp package.
ozDATA<-readShapeSpatial("AUS_adm1")
Then we read in our list of nodes and freshly obtained coordinates, as well as the edge list.
nodes<-read.csv(file="CapCoordinates.csv",sep=",",header=TRUE)
edges<-read.csv(file="EdgeListCapCities.csv",sep=",",header=TRUE)
Having loaded all the necessary data, we can start plotting.
plot(ozDATA,lwd=0.01,bg="#242424",col="#0000CD",ylim=c(-46,-10),xlim=c(125,145))
We plot the shape-file using the plot function with the following arguments:
- lwd – the line width;
- bg – the background colour;
- col – the colour of the regions (usually landmasses);
- ylim – a 2-tuple containing the latitude boundaries for the plot; and
- xlim – a 2-tuple containing the longitude boundaries for the plot.
Now we want to plot the cities (ie, the nodes) on this map. To do this we simply pass the coordinates to the points function. The parameters pch and cex set the type and size of the marker, respectively.
points(nodes$Longitude,nodes$Latitude,pch=16,cex=1.5)
Next we want to add labels to each of the nodes.
text(nodes$Longitude,nodes$Latitude,nodes$Name,cex=1,adj=0,pos=2,col="#C2C2C2")
The text function is used in almost identical fashion to the points function, but with an additional argument that contains the names of the nodes. We also add two additional arguments: adj and pos. The adj parameter adjusts the location of the labels. In this instance we have set it to zero, as it will be overwritten by our specification of pos. The pos parameter takes a value between 1 and 4 that specifies whether the label will be below, to the left, above, or to the right of the specified coordinates. (In this instance we have chosen to have labels to the left of the nodes.)
All that remains is to plot the lines between the respective cities. We loop through each of the edges and call the plotLine function.
for (j in 1:nrow(edges)){
plotLine(edges[j,]$From,edges[j,]$To,nodes)
}
getCoords<-function(location,df){
return(df[match(x=location,df[,"Name"]),][,c(4,3)])
}
plotLine<-function(from,to,df){
inter<-gcIntermediate(p1=getCoords(from,df),
p2=getCoords(to,df),
n=50,addStartEnd=TRUE)
lines(inter, col="green",cex=2,lwd=2)
}
plotLine simply takes each pair of nodes in the edge-list, and uses the gcIntermediate function (as defined in the geosphere package) to join the two nodes with the shortest edge that lies upon a great circle (ie, the geodesic between the two nodes). To simplify this function, I have defined an additional function, getCoords, that takes as arguments a string (the node name) and a data frame (the nodes and their coordinates) and returns the coordinates of that particular node. After the for loop is completed, we arrive at the graph shown in Figure 1.
Conclusion
Nothing here was particularly complicated. We decided what we wanted to plot, collected the data, and used R to handle the data and produce the image. However, the applications for the tools that we have used are practically endless. To that end, I would be keen to hear from people who have been exploiting R’s mapping functions across different applications. Ideally, I would like to showcase a range of applications in my next posting. Feel free to leave comments and links to your websites.
Until next time, enjoy being one of the few analysts who has visited the undiscovered country and can make maps in R with... | http://www.r-bloggers.com/the-undiscovered-country-a-tutorial-on-plotting-maps-in-r/ | CC-MAIN-2016-22 | refinedweb | 1,565 | 53.51 |
Decentralized DevOps: Master-less Puppet and supply_drop
Decentralized DevOps: Master-less Puppet and supply_drop
Join the DZone community and get the full member experience.Join For Free
Discover how you can reduce your Kubernetes installation from 22 steps to 1.
Here at Braintree, we are big fans of Puppet for system administration. In our ever-changing infrastructure, Puppet allows us to quickly provision and re-provision servers in multiple environments. We are also big fans of keeping our infrastructure lean and simple. Each piece of infrastructure that we must maintain comes with a cost. We have taken advantage of an under-appreciated feature of Puppet that allows us to manage our servers in a completely decentralized manner.
Benefits of going master-less
- Fine-grained control We pride ourselves on our ability to keep our site up. By using Puppet without a master, we have tight control over how configuration is applied to a server.
- Parallelization With a centralized Puppet server, the server maintains a single canonical version of the Puppet configuration. This causes contention when multiple people are attempting to make changes at the same time. Without a master, the source control repository maintains the canonical version, so people can easily work in parallel as long as they are not trying to Puppet the same server.
- No single point of failure Running a Puppet master is yet another service to maintain and make highly available. Having one less service to apply our typical HA rigor is a big win.
The nuts and bolts
In order to facilitate our master-less setup, we wrote a small gem called supply_drop. It's a set of capsitrano tasks that let you provision servers with Puppet. It tries to be small, simple, and stay out of your way. There are two tasks that do the bulk of the work. cap puppet:noop and cap puppet:apply. The noop will show you the set of changes that are about to be applied. As you could guess, the apply task makes those changes on the box. supply_drop uses rsync to push the current Puppet configuration from your box out to the server making it very fast.
We use a setup similar to cap multistage to manage the scope of what boxes we apply changes to. We dynamically create tasks for each server and environment that we have. Here is an example of what that looks like
def tasks_for_datacenter(datacenter, servers) task datacenter do role :server, *servers end servers.each do |server| task server do role :server, server end end end tasks_for_datacenter :sandbox, %w(app1.sand db.sand) tasks_for_datacenter :production, %w(app1.prod app2.prod db.prod)
These tasks allow us to apply changes to a single server or the entire datacenter. We can also use shell expansions to easily make changes to a subset of the servers in a given environment. Some examples:
- cap app1.prod puppet:noop shows the changes on app1
- cap sandbox puppet:apply applies the current changes to all of Sandbox
- cap app{1,2}.prod puppet:apply applies the changes to app1.prod and app2.prod
The workflow
We are always looking for ways to improve our workflow, but are generally happy with the one we have now. Our goals are:
- Easily allow multiple people to make changes to an environment
- Have explicit promotion from QA to Sandbox to Production
- Store every change in source control without making the logs overly noisy
We use a separate git branch for each environment (QA -> master, Sandbox -> sandbox, Production -> production). This allows us to promote changes by merging branches. Furthermore, if we need to do a quick fix in Production, we can use that branch and not affect Sandbox or QA until we merge. I'll walk through our workflow by adding a new Nagios alert for Apache as an example.
Write the Nagios script and push it out to a web server in QA. Repeat until you are happy with it.
cap web01.qa puppet:noop cap web01.qa puppet:apply
Push the script out to all the web servers in the datacenter
cap web0{1..n}.qa puppet:noop cap web0{1..n}.qa puppet:apply
Change the central Nagios server's configuration to know about the new alert
cap monitor.qa puppet:noop <span class="c"># Some scary changes</span>
Oh snap. There is a diff we don't know about. Someone else is adding a Nagios alert. No worries, they've already checked in. We grab their changes and try again.
git stash git pull origin master git stash pop cap monitor.qa puppet:noop cap monitor.qa puppet:apply
The alert works. Now we noop the entire environment for changes, and commit our change. If our noop shows that we are going to be removing some other changes in addition to our own, we talk to those devs and let them know what we did and that they will need to pull from git.
git commit -am "new nagios check"
Now we want to push the change to Sandbox. Since we are using git we can either merge all the changes from master or cherry-pick our single commit if there is other stuff that is not ready.
git checkout sandbox git merge master
Then apply the changes to Sandbox. We can do this on a server-by-server basis or in one fell swoop.
cap sandbox puppet:noop cap sandbox puppet:apply
Repeat for Production. Declare victory.
In conclusion
supply_drop and Puppet allow us fine grained control of how we apply changes to any server in any one of our datacenters. Pairing it with git and a decent workflow gives you auditable and repeatable configuration management.
Source: }} | https://dzone.com/articles/decentralized-devops-master | CC-MAIN-2018-47 | refinedweb | 949 | 65.12 |
Have you ever wondered how sites like Google, Facebook and Twitter work? How they can constantly change their content, while your humble HTML files dont do the same?
This is because while an HTML file is static, these companies are using a dynamic language to pre-compute their pages. There are many different languages out there, such as PHP, ASP, ColdFusion, JSP... The list goes on. And I am sure some of you want to create a simple web page without having the hassle of learning a new language. Well guess what, you can make your own dynamic web pages with AutoIt!
Do not get your hopes up - it will never be as powerful or fast as a fully blown web language such as PHP - simply because it is AutoIt. But your learning in AutoIt can be used in other langauges - such as C++! You can also create pages in C++ as long as output is pretty much the same, and no-one will know the difference, however that is a different story.
To start off, you will need a web server.
Head over to apachefriends.org and download a copy of XAMPP for windows. Install.
The great thing about XAMPP is that it is made for a development environment and requires near no configuration, trust me - that is a good thing.
Once you have installed XAMPP, use the control panel provided to start the Apache server. You are now running a web server on your computer, accessible via! Navigation to this page will automatically re-direct you to play with XAMPP settings. We are not covering that.
Once you have started Apache, open SCITE, or your favourite text editor - even Notepad will do.
We are going to create a simple two line program.
Observe:
ConsoleWrite("Content-type: text/plain" & @CRLF & @CRLF) ; This is a crucial element. This tells the web server what type of page we are sending. This says that the following will be in raw text. ; ==IMPORTANT POINT== The Content-type: xxx line MUST be followed by exactly two or more empty lines before output. Output continues after two lines and any lines after are output. ConsoleWrite("Hello AutoIt world!") ; We are now outputting Hello AutoIt World!
That is it! Now we must compile it.
Compile it as a CUI (NOT GUI.EXE) program without UPX. Preferably as an x86 program however this is simply in case you wish to move it between different architectures. Feel free to compile it as x64. Lastly, it MUST be compiled as an .exe file.
Once that is done, you must rename it (yes rename, trust me) from x.exe to x.cgi (yes, simply change the .exe to .cgi it will work if you have done it correctly) and place it in the XAMPP root /cgi-bin folder. For most this should be c:\xampp\cgi-bin\
Then, access it via localhost/cgi-bin/x.cgi in your browser of choice, where x is the appropriate file name.
Congrats! You just created a 'dynamic' web page! At the moment, this is not really dynamic as the content served will always say 'Hello AutoIt world!'. You can change that...
On the line where you write 'Hello AutoIt world!' to the console, change the text to send out a random number, then compile it and upload it to the server. You should be presented with a new number each time. If you are not, and the previous script DID work, you may have a caching issue, clear your browsers cache and re-try. However I do not expect this to happen.
The reason this works is because you are using the 'ConsoleWrite' function to send the data. ConsoleWrite outputs data to the STDOUT stream, which is that required for CGI scripts to work.
Now just to show you the equivalent in C++...
#include <iostream> using namespace std; int main() { cout << "Content-type: text/plain" << endl << endl; cout << "Hello AutoIt World!"; return 0; }
Aren't you glad you know AutoIt? (I do not expect most of you to understand it - isn't it way more complex than AutoIt?)
After a while, it will become more practical, as you require Line feeds and horizontal tabs - but that is a completely different story.
For those wishing to create full on HTML web pages, the above is not enough. The above will be sent as plain text. If you wish to create HTML pages, it must be sent as HTML text rather than plain text. How do we achieve this?
Change Content-type to text/html. Output the HTML like you would with the plain text, with ConsoleWrite.
ConsoleWrite("Content-type:text/html" & @CRLF & @CRLF) ; Output to STDOUT - required stream to output to CGI ConsoleWrite("<html>" & @CRLF & @TAB & "<head>" & @CRLF & @TAB & @TAB & "<title>Hello AutoIt world!</title>" & @CRLF) ; Begin HTML output ConsoleWrite(@TAB & "</head>" & @CRLF & @TAB & "<body>" & @CRLF & @TAB & @TAB & "Hello AutoIt world!" & @CRLF & @TAB) ; Continue HTML output ConsoleWrite("</body>" & @CRLF & "</html>") ; This will be the end of our page
As you can see, there is extensive use of @CRLF and @TAB, this is one of the areas in which C++ is easier. C++ would use \n and \t respectively, and it would actually be part of the text rather than having to break and concatonate. ie:
@TAB & "Hello World" & @CRLF
is the same as
"\tHello World\n";
Anyway, that wraps up the tutorial, I hope you all enjoyed it! To have a quick look at an already compiled cgi program + source code, download here: cgi_autoit.zip.
For anyone who really takes to web design, I suggest you learn a proper web language, however this will get the fundamentals going for really intensive web programming with C/C++, Python, Perl and other languages I am yet to find out about...
I hope you enjoyed the tutorial, I may do another depending on how this goes and as long as I am not told off for it!
Shane Thompson
PS:
I hope I dont get told off for this... it is AutoIt after all
A callout to Donald8282: I promised you I would do the tutorial
Edited by shanet, 19 August 2011 - 12:03 PM. | http://www.autoitscript.com/forum/topic/132067-dynamic-autoit-web-pages/ | CC-MAIN-2014-41 | refinedweb | 1,028 | 74.29 |
For Oscar Peterson, who died today. We will miss you.
When making a request for an HTTP resource, the trailing slash is significant in a URI and makes a difference in how the webserver processes the request.
For example, if you have the URI, you can expect the server to look in the userstuff subdirectory and return the default document (provided directory browsing is turned off). But without the trailing slash, the server will look for a file called "userstuff" in the site's root folder - not what you want. If no such file is present, most webservers will return a 301 Permanent Redirect response, suggesting that the client try again with the trailing slash. A .NET WebClient or WebRequest will respond just like a browser would - by re-requesting the resource with the trailing slash appended.
What this means is that when you leave out a trailing slash when it should have been included, your request will still work, but you'll have created an extra round trip to the server.
If you do not have a proxy in use, you should set the Proxy property on all your WebClient and WebRequest objects to null. If you do not do this, you run the risk of having the Framework attempt to "autodetect" proxy settings, which can add up to an additional 30 seconds to your requests. As an alternative to having to set the Proxy property on every request, you can set global defaults like so:
WebRequest.DefaultWebProxy =null;
The above will apply for the lifetime of the application domain.
WebClient is simply a wrapper over the WebRequest and WebResponse classes which can save a lot of extra lines of code. WebClient allows you to deal with your requests and responses with strings, byte arrays, files, or streams. Unfortunately, you can't use WebClient all the time; some features such as cookies are only available with WebRequest and WebResponse. You can't use the same instance of WebClient to perform repeated requests in sequence. For example if you are using a ThreadPool to handle multiple requests, you need to create a separate WebClient object in each thread.
The following are the steps to use WebClient:
1. Instantiate a WebClient instance
2. Assign the Proxy property
3. Assign the Credentials property if authentication is required.
4. Call one of the DownloadXXX or UploadXXX methods with the correct URI.
Each method of WebClient is overloaded to accept a Uri instance instead of a string address. The Upload methods are similar and each returns the response from the server:
UploadValues is used with the POST verb to upload a NameValueCollection just like a Form Post. The Content-Type header must not be null , you must set it to "application/x-www-form-urlencoded".
null
The Download methods are similar:
Since the asynchronous methods are new in .NET Framework 2.0, here is a short example of a Windows Form with a textbox for the url, a button and a multiline textbox for display, using DownloadStringAsync:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
namespace WebClientTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
WebClient wc = new WebClient();
wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
wc.DownloadStringAsync(new Uri(textBox2.Text),textBox2.Text);
while(wc.IsBusy)
System.Threading.Thread.Sleep(0);
wc.Dispose();
}
void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
textBox1.Text += "Result: " + e.Result + " State:" + e.UserState.ToString() + "\r\n";
}
void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
textBox1.Text += e.BytesReceived.ToString() + " bytes of " + e.TotalBytesToReceive.ToString() + " total\r\n";
}
}
}
You can provide a username / password combination to an HTTP or FTP site by creating the NetworkCredential object and assigning it to the Credentials property of your WebClient instance:
using (WebClient wc = new WebClient() ){wc.Proxy=null;wc.BaseAddress = "";
string userName="me@mysite.com";string password = "dorkusMcDweeb";wc.Credentials = new NetworkCredential(userName, password);wc.DownloadFile("mydocument.doc", "mydocument.doc");wc.UploadFile("userlist.txt", "userlist.txt");}
The above works with Basic and Digest authentication, and you can extend it via the AuthenticationManager class. You can also use NTLM and Kerberos if you supply the domain name before the userName. However this does not work with FormsAuthentication as it requires the Forms cookie ticket which WebClient does not support. For that, you must use WebRequest / WebResponse.
WebClient (as does WebRequest) allows you to add custom HTTP headers as well as to enumerate the headers in a response. Headers are just key-value pairs. You add a header like this:
wc.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
If your request contains a query, you'll need to add a user-agent header.
WebClient has a Dispose method which should be called as soon as your code has obtained the return data or any headers that are to be examined. Or, you can employ the using ( ... ) { } construct as shown above. Find out more about the WebClient class, its methods, properties and events. | http://www.nullskull.com/a/848/webclient-class-gotchas-and-basics.aspx | CC-MAIN-2013-48 | refinedweb | 858 | 50.63 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.