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 |
|---|---|---|---|---|---|
Hey. I wanted to say something about video. There are a lot of very bad things with it, but people ignores it
For example, colors
RGB pallete is 0-255, now we works with LCD screens, before this we watched on CRT screen
Some people knows that CRT has better colors, but actually its possible on LCD displays. The first problem is levels
0-0-0 and 255-255-255 is completely different on CRT and LCD. With another words, you can not met lcd 0-0-0 and 255-255-255 in real life. Black is too black, white is too white
Video works with limited color range as i know 16-236, but players force them to 0-255
Its possible to fix this with shaders, actually
MPC has levels shader, but its broken, the formula is not correct. I fix it and created 2 shaders
Black:
WhiteWhiteCode:// Levels=ps_2_0 // Code from MPC fixed by Danila Zabiaka sampler s0 : register(s0); #define black 16.0 float4 main(float2 tex : TEXCOORD0) : COLOR { // original pixel float4 c0 = tex2D(s0,tex); return c0 + black/255.0 - c0*black/255.0 ; }
Then, comression artefacts. Compression is very bad for gradients, it gives blocks and banding. Its debanding shaderThen, comression artefacts. Compression is very bad for gradients, it gives blocks and banding. Its debanding shaderCode:sampler s0 : register(s0); #define white 236.0 float4 main(float2 tex : TEXCOORD0) : COLOR { // original pixel float4 c0 = tex2D(s0, tex); return c0 * white/255.0; }
Surfaces in real life has texture, but video compression removes noiseSurfaces in real life has texture, but video compression removes noiseCode://From Dreamject . History: MaverickTse(AviUtl)->SAPikachu(Avisynth)->haasn(GLSL)->JPulowski(Reshade HLSL)->mbah.primbon(HLSL) /* --- Settings --- */ #define Threshold 70.0 //[0.0:4096.0] //-The debanding filter's cut-off threshold. Higher numbers increase the debanding strength dramatically but progressively diminish image details. (Default 64) #define Range 16.0 //[1.0:64.0] //-The debanding filter's initial radius. The radius increases linearly for each iteration. A higher radius will find more gradients, but a lower radius will smooth more aggressively. (Default 16) #define Iterations 1 //[1:16] //-The number of debanding steps to perform per sample. Each step reduces a bit more banding, but takes time to compute. Note that the strength of each step falls off very quickly, so high numbers (>4) are practically useless. (Default 1) #define Grain 0.0 //[0.0:4096.0] //-Add some extra noise to the image. This significantly helps cover up remaining quantization artifacts. Higher numbers add more noise. (Default 48) /* --- Defining Constants --- */ #define myTex2D(s,p) tex2D(s,p) #ifndef s0 sampler s0 : register(s0); #define s1 s0 //sampler s1 : register(s1); float4 p0 : register(c0); float4 p1 : register(c1); // #define width (p0[0]) // #define height (p0[1]) // #define counter (p0[2]) #define clock (p0[3]) // #define px (p1[0]) //one_over_width // #define py (p1[1]) //one_over_height #define px (p1.x) //one_over_width #define py (p1.y) //one_over_height #define screen_size float2(p0.x,p0.y) #define pixel float2(px,py) //#define pxy float2(p1.xy) //#define PI acos(-1) #endif /* --- Main code --- */ /*-----------------------------------------------------------. / Deband Filter / '-----------------------------------------------------------*/ float permute(float x) { return ((34.0 * x + 1.0) * x) % 289.0; } float rand(float x) { return frac(x * 0.024390243); } float3 average(sampler2D tex, float2 pos, float range, inout float h) { // Compute a random rangle and distance float dist = rand(h) * range; h = permute(h); float dir = rand(h) * 6.2831853; h = permute(h); float2 pt = dist * pixel; float2 o = float2(cos(dir), sin(dir)); // Sample at quarter-turn intervals around the source pixel float3 ref[4]; ref[0] = tex2D(tex, pos + pt * float2( o.x, o.y)).rgb; ref[1] = tex2D(tex, pos + pt * float2(-o.y, o.x)).rgb; ref[2] = tex2D(tex, pos + pt * float2(-o.x, -o.y)).rgb; ref[3] = tex2D(tex, pos + pt * float2( o.y, -o.x)).rgb; // Return the (normalized) average return (ref[0] + ref[1] + ref[2] + ref[3]) * 0.25; } /* --- Main --- */ float4 main(float2 texcoord : TEXCOORD0) : COLOR { float h; // Initialize the PRNG by hashing the position + a random uniform float3 m = float3(texcoord, clock * 0.0002) + 1.0; h = permute(permute(permute(m.x) + m.y) + m.z); // Sample the source pixel float3 col = tex2D(s0, texcoord).rgb; float3 avg; float3 diff; #if (Iterations == 1) [unroll] #endif for (int i = 1; i <= Iterations; i++) { // Sample the average pixel and use it instead of the original if the difference is below the given threshold avg = average(s0, texcoord, i * Range, h); diff = abs(col - avg); col = lerp(avg, col, diff > Threshold * 0.00006103515625 * i); } if (Grain > 0.0) { // Add some random noise to smooth out residual differences float3 noise; noise.x = rand(h); h = permute(h); noise.y = rand(h); h = permute(h); noise.z = rand(h); h = permute(h); col += (Grain * 0.000122070313) * (noise - 0.5); } return float4(col, 1.0); }
It's noise shader, i prefer 2-5
Then, cantThen, cantHTML Code:sampler s0 : register(s0); float4 p0 : register(c0); float4 p1 : register(c1); #define amplificationFactor 5 #define offset -15.0 #define dx (p1[0]) #define dy (p1[1]) #define counter (p0[2]) #define clock (p0[3]) float randCust(in float2 uv) { float noiseX = (frac(sin(dot(uv, float2(12.9898,78.233) )) * 43758.5453)); float noiseY = (frac(sin(dot(uv, float2(12.9898,78.233) * 2.0)) * 43758.5453)); return noiseX * noiseY; } float4 main(float2 tex : TEXCOORD0) : COLOR { float4 orig; orig = tex2D(s0, tex); float noise = randCust(tex*(counter/500)) + offset/100; return orig+ (noise*amplificationFactor/100); }
Hm...
+ Reply to Thread
Results 1 to 2 of 2
Thread
About colors, if some coder read me. There are some software to control colors on screen like f.lux
Actually if you wanna make your display better, you need change black and white point boths.
Its not enought to just make colors warmer how f.lux suggests
It will be great, if you can tune levels. You can limit white a little in dccw from windows
But there are no correct tools to change black point. May be some programmer can change redshift sources to make this possible and make simple GUI
Actually for calibration for your taste you dont need to change color temp, you can move RGB sliders, like dccw does, but they works only for max values
May be somebody can change redshift a little for this gui
Similar Threads
TMPGenc Video Mastering Works 6 Deinterlacing settingsBy magnu in forum RestorationReplies: 25Last Post: 8th Aug 2017, 11:43
Is 1080p fake?By draig-llofrudd in forum Newbie / General discussionsReplies: 2Last Post: 7th Dec 2016, 14:40
RedFox really makes me angryBy kevinharold in forum Newbie / General discussionsReplies: 6Last Post: 13th Apr 2016, 12:56
TMPGEnc Video Mastering Works 5By kalemvar1 in forum Video ConversionReplies: 5Last Post: 5th Sep 2015, 22:37
Genuine of Fake?By newpball in forum Camcorders (DV/HDV/AVCHD/HD)Replies: 6Last Post: 18th Jul 2015, 00:20 | https://forum.videohelp.com/threads/397016-This-video-playing-is-just-a-fake-%2Aangry-%28%2A-btw-how-recklock-works?s=7f8cda5d0408d96ff58c1f4954287c08 | CC-MAIN-2020-40 | refinedweb | 1,156 | 65.73 |
How to use sensitive information in your code
As a developer one of the major mistakes I used to do was writing secure information (like passwords, API tokens, keys etc.) inside the code repository. Now the problem with this approach is leakage of secured information. A Lot of times when we push the code to the online repository (ex. GitHub or BitBucket) we push the secured information along with the code. And users who can access your repository can easily get the access of your secured information. Now there are several ways to avoid this. Here I am explaining you one of the simplest ways you can follow. And the method is storing this sensitive information inside your OS environment variables. This way only you will be able to access them and other users who will access your code, if they need they can set the environment variables inside their systems. In this way, you will be able to keep sensitive information safe. Following are the methods to create environment variables inside your operating system.
Mac / Linux -
For the operating systems like Mac or Linux you can follow the following steps-
1. Open the terminal
2. Navigate to the home directory
3. Open the bash profile in text editor. you can use any editor like vi, vim or nano whatever you like. bash_profile is the file where you can store your environment variables. if you don’t have the file, create one.
$ nano ~/.bash_profile
or
$ vi ~/.bash_profile
4. Now declare the environment variable at the top of the file.
export ENV_VAR_NAME=”value”
5. Save the file and exit.
6. Now to verify whether environment variable is properly set, run the following command.
echo $ENV_VAR_NAME
It will display the value of the variable.
7. If you are not getting any value, restart the terminal and run the following command.
$ source ~/.bash_profile
8. Now if you again use the command mentioned in step number 6 you will definitely get the value.
Windows -
- From start menu, open the control Panel
- Open the System and Security section
- Navigate to System
- Click on the Advanced system settings link displayed in the left panel
- Click on Environment Variables button present at the bottom
- Now for this purpose, you can set User variables (System variables need not be updated. In this way you won’t need the admin access as well)
- Click on New in User Variable section
- Give the environment variable name in the Variable name section and the value in the Variable value section
- Click on OK. Now your environment variable is set. You may need to restart your system if you are unable to fetch the variable
Accessing environment variables inside your code -
Python -
import os
os.environ.get(“ENV_VAR_NAME”)
Java -
System.getenv(“ENV_VAR_NAME”)
JavaScript -
process.env.ENV_VAR_NAME | https://sensoumya94.medium.com/how-to-use-sensitive-information-in-your-code-9c8534ce3fc0?source=user_profile---------3------------------------------- | CC-MAIN-2022-05 | refinedweb | 464 | 65.93 |
There are some situations with iOSApple’s mobile operating system. More info
See in Glossary where your game can work perfectly in the Unity editor but then doesn’t work or maybe doesn’t even start on the actual device. The problems are often related to code or content quality. This section describes the most common scenarios.
There are a number of reasons why this may happen. Typical causes include:
This message typically appears on iOS devices when your application receives a NullReferenceException. There are two ways to figure out where the fault happened:
Unity includes software-based handling of the NullReferenceException. The AOT compiler includes quick checks for null references each time a method or variable is accessed on an object. This feature affects script performance, which is why it is enabled only for development buildsA development build includes debug symbols and enables the Profiler. More info
See in Glossary (enable the script debugging option in Build Settings dialog). If everything was done right and the fault actually is occurring in .NET code then you won’t see EXC_BAD_ACCESS anymore. Instead, the .NET exception text will be printed in the Xcode console (or else your code will just handle it in a “catch” statement). Typical output might be:
Unhandled Exception: System.NullReferenceException: A null value was found where an object instance was required. at DayController+$handleTimeOfDay$121+$.MoveNext () [0x0035a] in DayController.js:122
This indicates that the fault happened in the handleTimeOfDay method of the DayController class, which works as a coroutine. Also, if it is script code then you will generally be told the exact line number (e.g. “DayController.js:122”). The offending line might be something like the following:
Instantiate(_img);
This might happen if, say, the script accesses an asset bundle without first checking that it was downloaded correctly.
Native stack traces are a much more powerful tool for fault investigation but using them requires some expertise. Also, you generally can’t continue after these native (hardware memory access) faults happen. To get a native stack trace, type bt all into the Xcode Debugger Console. Carefully inspect the printed stack traces; they may contain hints about where the error occurred. You might see something like:
... Thread 1 (thread 11523): 1. 0 0x006267d0 in m_OptionsMenu_Start () 1. 1 0x002e4160 in wrapper_runtime_invoke_object_runtime_invoke_void__this___object_intptr_intptr_intptr () 1. 2 0x00a1dd64 in mono_jit_runtime_invoke (method=0x18b63bc, obj=0x5d10cb0, params=0x0, exc=0x2fffdd34) at /Users/mantasp/work/unity/unity-mono/External/Mono/mono/mono/mini/mini.c:4487 1. 3 0x0088481c in MonoBehaviour::InvokeMethodOrCoroutineChecked () ...
Firstly, you should find the stack trace for “Thread 1”, which is the main thread. The very first lines of the stack trace will point to the place where the error occurred. In this example, the trace indicates that the NullReferenceException happened inside the OptionsMenu script’s Start method. Looking carefully at this method implementation would reveal the cause of the problem. Typically, NullReferenceExceptions happen inside the Start method when incorrect assumptions are made about initialization order. In some cases only a partial stack trace is seen on the Debugger Console:
Thread 1 (thread 11523): 1. 0 0x0062564c in start ()
This indicates that native symbols were stripped during the Release build of the application. The full stack trace can be obtained with the following procedure:
This usually happens when an external library is compiled with the ARM Thumb instruction set. Currently, such libraries are not compatible with Unity. The problem can be solved easily by recompiling the library without Thumb instructions. You can do this for the library’s Xcode project with the following steps:
If the library source is not available you should ask the supplier for a non-thumb version of the library.
Sometimes, you might see a message like Program received signal: “0”. This warning message is often not fatal and merely indicates that iOS is low on memory and is asking applications to free up some memory. Typically, background processes like Mail will free some memory and your application can continue to run. However, if your application continues to use memory or ask for more, the OS will eventually start killing applications and yours could be one of them. Apple does not document what memory usage is safe, but empirical observations show that applications using less than 50% of all device RAM do not have major memory usage problems. The main metric you should rely on is how much RAM your application uses. Your application memory usage consists of three major components:
Note: The internal profiler shows only the heap allocated by .NET scriptsA piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info
See in Glossary. Total memory usage can be determined via Xcode Instruments as shown above. This figure includes parts of the application binary, some standard framework buffers, Unity engine internal state buffers, the .NET runtime heap (number printed by internal profiler), GLES driver heap and some other miscellaneous stuff.
The other tool displays all allocations made by your application and includes both native heap and managed heap statistics. The important statistic is the Net bytes value.
To keep memory usage low:
Querying the OS about the amount of free memory may seem like a good idea to evaluate how well your application is performing. However, the free memory statistic is likely to be unreliable since the OS uses a lot of dynamic buffers and caches. The only reliable approach is to keep track of memory consumption for your application and use that as the main metric. Pay attention to how the graphs from the tools described above change over time, especially after loading new levels.
There could be several reasons for this. You need to inspect the device logs to get more details. Connect the device to your Mac, launch Xcode and select Window > Devices and Simulators from the menu. Select your device in the window’s left toolbar, then click on the Show the device console button and review the latest messages carefully. Additionally, you may need to investigate crash reports. You can find out how to obtain crash reports here:.
There is a poorly-documented time limit for an iOS application to render its first frames and process input. If your application exceeds this limit, it will be killed by SpringBoard. This may happen in an application with a first sceneA Scene contains the environments and menus of your game. Think of each unique Scene file as a unique level. In each Scene, you place your environments, obstacles, and decorations, essentially designing and building your game in pieces. More info
See in Glossary which is too large, for example. To avoid this problem, it is advisable to create a small initial scene which just displays a splash screen, waits a frame or two with yield and then starts loading the real scene. This can be done with code as simple as the following:
IEnumerator Start() { yield return new WaitForEndOfFrame(); // Do not forget using UnityEngine.SceneManagement directive SceneManager.LoadScene("Test"); }
Currently Type.GetProperty() and Type.GetValue() are supported only for the .NET 2.0 Subset profile. You can select the .NET API compatibility level in the Player settings.
Note: Type.GetProperty() and Type.GetValue() might be incompatible with managed code stripping and might need to be excluded (you can supply a custom non-strippable type list during the stripping process to accomplish this). For further details, see the iOS player size optimization guide.
The Mono .NET implementation for iOS is based on AOT (ahead of time compilation to native code) technology, which has its limitations. It compiles only those generic type methods (where a value type is used as a generic parameter) which are explicitly used by other code. When such methods are used only via reflection or from native code (i.e. the serialization system) then they get skipped during AOT compilationAhead of Time (AOT) compilation is an iOS optimization method for optimizing the size of the built iOS player More info
See in Glossary. The AOT compiler can be hinted to include code by adding a dummy method somewhere in the script code. This can refer to the missing methods and so get them compiled ahead of time.
void _unusedMethod() { var tmp = new SomeType<SomeValueType>(); }
Note: Value types are basic types, enums and structs.
.NET Cryptography services rely heavily on reflection and so are not compatible with managed code stripping since this involves static code analysis. Sometimes the easiest solution to the crashes is to exclude the whole System.Security.Crypography namespace from the stripping process.
The stripping process can be customized by adding a custom link.xml file to the Assets folder of your Unity project. This specifies which types and namespaces should be excluded from stripping. Further details can be found in the iOS player size optimization guide.
<linker> <assembly fullname="mscorlib"> <namespace fullname="System.Security.Cryptography" preserve="all"/> </assembly> </linker>
You should consider the above advice or try working around this problem by adding extra references to specific classes to your script code:
object obj = new MD5CryptoServiceProvider();
This error usually happens if you use lots of recursive generics. You can hint to the AOT compiler to allocate more trampolines of type 0, type 1 or type 2. Additional AOT compiler command line options can be specified in the Other Settings section of the Player settings. For for type 0 trampolines specify
ntrampolines=ABCD, where ABCD is the number of new trampolines required (i.e. 4096). For type 1 trampolines specify
nrgctx-trampolines=ABCD and for type 2 trampolines specify
nimt-trampolines=ABCD.
With some latest Xcode releases there were changes introduced in PNG compression and optimization tool. These changes might cause false positives in Unity iOS runtime checks for splash screen modifications. If you encounter such problems try upgrading Unity to the latest publicly available version. If this does not help, you might consider the following workaround:
If this still does not help try disabling PNG re-compression in Xcode:
The most common mistake is to assume that WWW downloads are always happening on a separate thread. On some platforms this might be true, but you should not take it for granted. Best way to track WWW status is either to use the yield statement or check status in Update method. You should not use busy while loops for that.
Some operations with the UI(User Interface) Allows a user to interact with your application. More info
See in Glossary will result in iOS redrawing the window immediately (the most common example is adding a UIView with a UIViewController to the main UIWindow). If you call a native function from a script, it will happen inside Unity’s PlayerLoop, resulting in PlayerLoop being called recursively. In such cases, you should consider using the performSelectorOnMainThread method with waitUntilDone set to false. It will inform iOS to schedule the operation to run between Unity’s PlayerLoop calls.
If your application runs ok in editor but you get errors in your iOS project this may be caused by missing DLLs (e.g. I18N.dll, I19N.West.dll). In this case, try copying those dlls from within the Unity.app to your project’s Assets\Plugins folder. The location of the DLLs within the unity app is: Unity.app\Contents\Frameworks\Mono\lib\mono\unity You should then also check the stripping level of your project to ensure the classes in the DLLs aren’t being removed when the build is optimised. Refer to the iOS Optimisation Page for more information on iOS Stripping Levels.
Typically, such a message is received when the managed function delegate is passed to the native function, but the required wrapper code wasn’t generated when the application was built. You can help AOT compiler by hinting which methods will be passed as delegates to the native code. This can be done by adding the MonoPInvokeCallbackAttribute custom attribute. Currently, only static methods can be passed as delegates to the native code.
Sample code:
using UnityEngine; using System.Collections; using System; using System.Runtime.InteropServices; using AOT; public class NewBehaviourScript : MonoBehaviour { [DllImport ("__Internal")] private static extern void DoSomething (NoParamDelegate del1, StringParamDelegate del2); delegate void NoParamDelegate (); delegate void StringParamDelegate (string str); [MonoPInvokeCallback(typeof(NoParamDelegate))] public static void NoParamCallback() { Debug.Log ("Hello from NoParamCallback"); } [MonoPInvokeCallback(typeof(StringParamDelegate))] public static void StringParamCallback(string str) { Debug.Log(string.Format("Hello from StringParamCallback {0}", str)); } // Use this for initialization void Start() { DoSomething(NoParamCallback, StringParamCallback); } }
This error usually means there is just too much code in single module. Typically, it is caused by having lots of script code or having big external .NET assemblies included into build. And enabling script debugging might make things worse, because it adds quite few additional instructions to each function, so it is easier to hit that limit.
Enabling managed code stripping in Player settings might help with this problem, especially if big external .NET assemblies are involved. But if the issue persists then the best solution is to split user script code into multiple assemblies. The easiest way to this is move some code to Plugins folder. Code at this location is put to a different assembly. Also, check the information about how special folder names affect script compilation.
Did you find this page useful? Please give it a rating: | https://docs.unity3d.com/Manual/TroubleShootingIPhone.html | CC-MAIN-2019-30 | refinedweb | 2,223 | 56.05 |
While thinking David's suggestion through, about adding an FOND driver, I found out that's still not possible without modifications elsewhere in FT2. This is because I need to create a special new stream from information that can't be reached from the (stdio) stream created by FT_Open_Face(). (The reason that I can't get at the information is due to the nature of Mac files in general, and the nature of Mac font suitcase files in particular.) I see two solutions: 1) the *driver* should be responsible for creating the stream -- but this seems inefficient for the general case, since most often various drivers can check whether they can handle the resource by looking at the default stream. 2) I supply a Mac-specific FT_New_Stream(). The second solution sounds best to me, but I'm worried about the implications. For one, I still need the stdio stream implementation (as in config/ansi/ftsystem.c) for non-Mac fonts, and I'd hate to duplicate that code just to add one test: if ( is_mac_suitcase(file) ) return FT_New_Stream_From_Mac_Suitcase(args); ...continue, create stdio stream... Secondly, I really, *really* dislike to duplicate that code. More on that in my upcoming reply to Werner's post. So, is it negotiable to add a compiler switch to ft_new_input_stream()? Something like this: /* do we have an 8-bit pathname? */ else if ( args->pathname ) #ifndef macintosh error = FT_New_Stream( args->pathname, stream ); #else error = FT_New_Stream_Mac( args->pathname, stream ); #endif FT_New_Stream_Mac() would look roughly like this: FT_New_Stream_Mac(path, stream) { if ( is_mac_suitcase(path) ) return FT_New_Stream_From_Mac_Suitcase(path, stream); else: return FT_New_Stream(path, stream); } The advantage is that I don't even *need* to write a driver (at least for TT), since I can just create a memory stream containing pure sfnt data. For T1 I'm not so sure yet (although I can easily create a PFA stream): I still need a way to attach the kerning from the FOND to the face object. But first things first. Just | https://lists.gnu.org/archive/html/freetype-devel/2000-02/msg00089.html | CC-MAIN-2019-35 | refinedweb | 329 | 60.55 |
Section 4.6
More on Program Design
Understanding how programs work is one thing. Designing a program to perform some particular task is another thing altogether. In Section 3.2, I discussed how pseudocode and.
4.6.1 Preconditions and Postconditions
When working with subroutines as building blocks, it is important to be clear about how a subroutine interacts with the rest of the program. This interaction is specified by the contract of the subroutine, as discussed in Section 4.1. A convenient way to express the contract of a subroutine is in terms of preconditions and postconditions.
The precondition of a subroutine is something that must be true when the subroutine is called, if the subroutine is to work correctly. For example, for the built-in function Math.sqrt(x), a precondition is that the parameter, x, is greater than or equal to zero, since it is not possible to take the square root of a negative number. In terms of a contract, a precondition represents an obligation of the caller of the subroutine. If you call a subroutine without meeting its precondition, then there is no reason to expect it to work properly. The program might crash or give incorrect results, but you can only blame yourself, not the subroutine.
A postcondition of a subroutine represents the other side of the contract. It is something that will be true after the subroutine has run (assuming that its preconditions were met -- and that there are no bugs in the subroutine). The postcondition of the function Math.sqrt() is that the square of the value that is returned by this function is equal to the parameter that is provided when the subroutine is called. Of course, this will only be true if the preconditiion -- that the parameter is greater than or equal to zero -- is met. A postcondition of the built-in subroutine System.out.print() is that the value of the parameter has been displayed on the screen.
Preconditions most often give restrictions on the acceptable values of parameters, as in the example of Math.sqrt(x). However, they can also refer to global variables that are used in the subroutine. The postcondition of a subroutine specifies the task that it performs. For a function, the postcondition should specify the value that the function returns.
Subroutines are often described by comments that explicitly specify their preconditions and postconditions. When you are given a pre-written subroutine, a statement of its preconditions and postconditions tells you how to use it and what it does. When you are assigned to write a subroutine, the preconditions and postconditions give you an exact specification of what the subroutine is expected to do. I will use this approach in the example that constitutes the rest of this section. The comments are given in the form of Javadoc comments, but I will explicitly label the preconditions and postconditions. (Many computer scientists think that new doc tags @precondition and @postcondition should be added to the Javadoc system for explicit labeling of preconditions and postconditions, but that has not yet been done.)
4.6.2 A Design Example
Let's work through an example of program design using subroutines. In this example, we will use prewritten subroutines as building blocks and we will also design new subroutines that we need to complete the. In fact, the class defines a toolbox or API that can be used for working with such windows. Here are some of the available routines in the API, with Javadoc-style comments:
/** * Opens a "mosaic" window on the screen. * * Precondition: The parameters rows, cols, w, and h are positive integers. * Postcondition: A window is open on the screen that can display rows and * columns of colored rectangles. Each rectangle is w pixels * wide and h pixels high. The number of rows is given by * the first parameter and the number of columns by the * second. Initially, all rectangles are black. * Note: The rows are numbered from 0 to rows - 1, and the columns are * numbered from 0 to cols - 1. */ public static void open(int rows, int cols, int w, int h) /** * Sets the color of one of the rectangles in the window. * * Precondition: row and col are in the valid range of row and column numbers, * and r, g, and b are in the range 0 to 255, inclusive. * Postcondition: The color of the rectangle in row number row and column * number col has been set to the color specified by r, g, * and b. r gives the amount of red in the color with 0 * representing no red and 255 representing the maximum * possible amount of red. The larger the value of r, the * more red in the color. g and b work similarly for the * green and blue color components. */ public static void setColor(int row, int col, int r, int g, int b) /** * Gets the red component of the color of one of the rectangles. * * Precondition: row and col are in the valid range of row and column numbers. * Postcondition: The red component of the color of the specified rectangle is * returned as an integer in the range 0 to 255 inclusive. */ public static int getRed(int row, int col) /** * Like getRed, but returns the green component of the color. */ public static int getGreen(int row, int col) /** * Like getRed, but returns the blue component of the color. */ public static int getBlue(int row, int col) /** * Tests whether the mosaic window is currently open. * * Precondition: None. * Postcondition: The return value is true if the window is open when this * function is called, and it is false if the window is * closed. */ public static boolean isOpen() /** * Inserts a delay in the program (to regulate the speed at which the colors * are changed, for example). * * Precondition: milliseconds is a positive integer. * Postcondition: The program has paused for at least the specified number * of milliseconds, where one second is equal to 1000 * milliseconds. */ public static void delay(int milliseconds)
Remember that these subroutines are members of the Mosaic class, so when they are called from outside Mosaic, the name of the class must be included as part of the name of the routine. For example, we'll have to use the name Mosaic.isOpen() rather than simply isOpen().
Open a Mosaic window Fill window with random colors; Move around, changing squares at random.
Filling the window with random colors seems like a nice coherent task that I can work on separately, so let's decide to the square at the current position; Move current position up, down, left, or right, at random;
I need to represent the current position in some way. That can be done with two int variables named currentRow and currentColumn that hold the row number and the column number of the square where the disturbance is currently located.. The fillWithRandomColors() routine is defined by the postcondition that "each of the rectangles in the mosaic has been changed to a random color." Pseudocode for an algorithm to accomplish this task can be given as:
For each row: For each column: set the in the Mosaic class, Mosaic.setColor(), that can be used to change the color of a square. If we want a random color, we just have to choose random values for r, g, and b. According to the precondition of the Mosaic.setColor() subroutine, these random values must be integers in the range from 0 to 255. A formula for randomly; directionNum = ; }
4.6.3 The Program
Putting this all together, we get the following complete program. Note that I've added Javadoc-style comments for the class itself and for each of the subroutines..
/** * This program opens a window full of randomly colored squares. A "disturbance" * moves randomly around in the window, randomly changing the color of each * square that it visits. The program runs until the user closes the window. */ public class RandomMosaicWalk { static int currentRow; // Row currently containing the disturbance. static int currentColumn; // Column currently containing disturbance. /** * The main program creates the window, fills it with random colors, * and then moves the disturbances in a random walk around the window * as long as the window is open. */ public static void main(String[] args) { Mosaic.open(10,20,10,10); fillWithRandomColors(); currentRow = 5; // start at center of window currentColumn = 10; while (Mosaic.isOpen()) { changeToRandomColor(currentRow, currentColumn); randomMove(); Mosaic.delay(20); } } // end main /** * Fills the window with randomly colored squares. * Precondition: The mosaic window is open. * Postcondition: Each square has been set to a random color. */ static void fillWithRandomColors() { for (int row=0; row < 10; row++) { for (int column=0; column < 20; column++) { changeToRandomColor(row, column); } } } // end fillWithRandomColors /** * Changes one square to a new randomly selected color. * Precondition: The specified rowNum and colNum are in the valid range * of row and column numbers. * Postcondition: The square in the specified row and column has * been set to a random color. * @param rowNum the row number of the square, counting rows down * from 0 at the top * @param colNum the column number of the square, counting columns over * from 0 at the left */ static void changeToRandomColor(int rowNum, int colNum) { int red = (int)(256*Math.random()); // Choose random levels in range int green = (int)(256*Math.random()); // 0 to 255 for red, green, int blue = (int)(256*Math.random()); // and blue color components. Mosaic.setColor(rowNum,colNum,red,green,blue); } // end of changeToRandomColor() /** *: // move left currentColumn--; if (currentColumn < 0) currentColumn = 19; break; } } // end randomMove } // end class RandomMosaicWalk | http://www-h.eng.cam.ac.uk/help/importedHTML/languages/java/javanotes5.0.2/c4/s6.html | CC-MAIN-2018-09 | refinedweb | 1,578 | 54.63 |
On Tue, 18 Sep 2001 11:52:17 -0500 Nathan E Norman <nnorman@micromuse.com> wrote: > On Tue, Sep 18, 2001 at 11:36:17AM +0300, Alexander Poslavsky wrote: > > Hi, > > does anybody know how to find my ide-scsi devices? They seem to be lost. > > But (root@wt1:root)# cat /proc/scsi/scsi gives this: > ide-scsi simply aliases ide devices into scsi namespace. You need > "SCSI CD-ROM Support" to use the drives as CD drives, and "SCSI > generic support" to use the writer. > > device names will be /dev/scd0 or /dev/sr0 for the cd devices, and > /dev/sg0 for the generic devices (obviously the 0 might be some other > integer in your case). yep, I forgot to compile "SCSI CD-ROM Support" in the kernel (duh) , now it all works. Thanks all. -- Sleep: A completely inadequate substitute for caffeine. | https://lists.debian.org/debian-user/2001/09/msg02712.html | CC-MAIN-2016-40 | refinedweb | 142 | 72.56 |
an introduction/tutorial on writing a multi-threaded Berkeley DB XML application in Haskell. It is intended for Haskell programmers who are new to Berkeley DB XML.
I hope you will consider the advantages of using an XML database instead of the traditional SQL database in your application..5 databases. Also when DB_INIT_LOG is enabled, you cannot move your database files example.
Because your transaction can be re-started, you should not do any normal I/O inside your transaction. It would be even better if (like in Software Transactional Memory) the transactional code runs in a monad of its own that prevents normal access to the IO monad.
All the important topics are covered in "Getting Started with Berkeley DB XML" guide that comes with the Berkeley DB XML distribution, so I will only cover more Haskell-specific things here.
Berkeley DBXML returns its document contents as text. You need to use an XML library of some kind to handle these. The Haskell binding leaves you free to choose your own XML library.
Please take a look at the source code of the adventure example included with the DB XML binding distribution. Here are some examples from it:
3.1 Example 1: Querying documents
Here is an example that covers a lot of ground: The "query" function from the adventure game:
collectM :: Monad m => m (Maybe a) -> m [a] collectM valueM = do value <- valueM case value of Just item -> do rest <- collectM valueM return (item:rest) Nothing -> do return [] fromByteString :: B.ByteString -> String fromByteString = map (chr . fromIntegral) . B.unpack query_ :: XmlPickler p => (XmlManager, XmlContainer, XmlTransaction) -> PU p -> String -> [(String, XmlValue)] -> [DbXmlFlag] -> IO [(XmlDocument, p)] query_ (mgr, cont, trans) pickler queryText params flags = do qctx <- xmlManager_createQueryContext mgr LiveValues Eager let collection = xmlContainer_getName cont xmlQueryContext_setDefaultCollection qctx collection forM params $ \(name, value) -> do xmlQueryContext_setVariableValue qctx name value res <- xmlManager_query mgr (Just trans) queryText qctx flags docs <- collectM (xmlResults_next res) records <- liftM (concat) $ forM docs $ \doc -> do text <- liftM fromByteString $ xmlDocument_getContent doc ps <- runX ( readString [ (a_validate, v_0),(a_remove_whitespace, v_1)] text >>> xunpickleVal pickler) return$ map (\p -> (doc, p)) ps return records query :: XmlPickler p => (XmlManager, XmlContainer, XmlTransaction) -> PU p -> String -> [(String, XmlValue)] -> IO [p] query ctx pickler queryText params = liftM (map snd)$ query_ ctx pickler queryText params []
The 'query' function is a helper that calls 'query_' and returns the results as Haskell data structures only, discarding the XmlDocument objects. (XmlDocuments are useful as a reference to a document for updating or deleting.)
Now look at 'query_'. First, we create a query context. This holds the variable assignments used in the XQuery. For example, if we call 'query' like this...
items <- query db xpItem "collection()/item[@location=$loc]" [("loc", xmlString loc)]
...then we push "loc" and its value into the query context, so the XQuery parser can resolve the variable $loc. This query says "give me all documents with a top-level tag of <item> containing a 'location' attribute matching $loc".
xmlQueryContext_setDefaultCollection allows the XQuery to refer our document container as just "collection()" rather than having to name it explicitly in the XQuery string.
Then we run the query, and use a helper called 'collectM' to extract the results from the XmlResults object and return them as a list of XmlDocument objects.
The last step is iterate over the returned documents, using HXT's unpickle functionality to translate the XML document into Haskell data structures.
3.2 Example 2: Updating a document
-- | Query with write lock. Returned document allows the document to be updated -- without having to specify its document name. queryUpdate :: XmlPickler p => (XmlManager, XmlContainer, XmlTransaction) -> PU p -> String -> [(String, XmlValue)] -> IO [(XmlDocument, p)] queryUpdate ctx pickler queryText params = query_ ctx pickler queryText params [DB_FLAG DB_RMW] toByteString :: String -> B.ByteString toByteString = B.pack . map (fromIntegral . ord) update :: XmlPickler p => (XmlManager, XmlContainer, XmlTransaction) -> XmlDocument -> p -> IO () update (mgr, cont, trans) doc p = do text <- toXML p xmlDocument_setContent doc (toByteString text) uctx <- xmlManager_createUpdateContext mgr xmlContainer_updateDocument cont (Just trans) doc uctx
'queryUpdate' works like 'query' in the previous example, except that it sets the DB_RMW flag, which means you get a write (exclusive) lock instead of the default read (non-exclusive) lock. Using a write lock makes no difference to the semantics of the transaction: It is just as atomic if you use a read lock. But, write locks can reduce the probability of transaction re-starts due to deadlocks, and so they improve efficiency when updating.
A caller would pass the XmlDocument returned by queryUpdate to 'update', along with a modified version of the Haskell data structure p.
'update' then converts p to a String containing XML using 'toXML'- a small helper (see the adventure game source code). It proceeds to stuff this XML string into the XmlDocument that queryUpdate gave us, and then issues the update.
3.3 10:28, 1 October 2008 (UTC) | http://www.haskell.org/haskellwiki/index.php?title=BerkeleyDBXML&oldid=24701 | CC-MAIN-2014-23 | refinedweb | 799 | 50.16 |
Service Discovery
Your Amazon ECS service can optionally be configured to use Amazon ECS Service Discovery. Service discovery uses AWS Cloud Map API actions to manage HTTP and DNS namespaces for your Amazon ECS services. For more information, see What Is AWS Cloud Map? in the AWS Cloud Map Developer Guide.
Topics
Service Discovery Concepts
Service discovery consists of the following components:
Service discovery namespace: A logical group of service discovery services that share the same domain name, such as
example.com.
Service discovery service: Exists within the service discovery namespace and consists of the service name and DNS configuration for the namespace. It provides the following core component:
Service registry: Allows you to look up a service via DNS or AWS Cloud Map API actions and get back one or more available endpoints that can be used to connect to the service.
Service discovery instance: Exists within the service discovery service and consists of the attributes associated with each Amazon ECS service in the service directory.
Instance attributes: The following metadata is added as custom attributes for each Amazon ECS service that is configured to use service discovery:
AWS_INSTANCE_IPV4– For an
Arecord, the IPv4 address that Route 53 returns in response to DNS queries and AWS Cloud Map returns when discovering instance details, for example,
192.0.2.44.
AWS_INSTANCE_PORT– The port value associated with the service discovery service.
AVAILABILITY_ZONE– The Availability Zone into which the task was launched. For tasks using the EC2 launch type, this is the Availability Zone in which the container instance exists. For tasks using the Fargate launch type, this is the Availability Zone in which the elastic network interface exists.
REGION– The Region in which the task exists.
ECS_SERVICE_NAME– The name of the Amazon ECS service to which the task belongs.
ECS_CLUSTER_NAME– The name of the Amazon ECS cluster to which the task belongs.
EC2_INSTANCE_ID– The ID of the container instance the task was placed on. This custom attribute is not added if the task is using the Fargate launch type.
ECS_TASK_DEFINITION_FAMILY– The task definition family that the task is using.
ECS_TASK_SET_EXTERNAL_ID– If a task set is created for an external deployment and is associated with a service discovery registry, then the
ECS_TASK_SET_EXTERNAL_IDattribute will contain the external ID of the task set.
Amazon ECS health checks: Amazon ECS performs periodic container-level health checks. If an endpoint does not pass the health check, it is removed from DNS routing and marked as unhealthy.
Service Discovery Considerations
The following should be considered when using service discovery:
Service discovery is supported for tasks using the Fargate launch type if they are using platform version v1.1.0 or later. For more information, see AWS Fargate Platform Versions.
The Create Service workflow in the Amazon ECS console only supports registering services into private DNS namespaces. When a AWS Cloud Map private DNS namespace is created, a Route 53 private hosted zone will be created automatically.
Amazon ECS does not support registering services into public DNS namespaces.
The DNS records created for a service discovery service always register with the private IP address for the task, rather than the public IP address, even when public namespaces are used.
Service discovery requires that tasks specify either the
awsvpc,
bridge, or
hostnetwork mode (
noneis not supported).
If the task definition your service task specifies uses the
awsvpcnetwork mode, you can create any combination of A or SRV records for each service task. If you use SRV records, a port is required.
If the task definition that your service task specifies uses the
bridgeor
hostnetwork mode, an SRV record is the only supported DNS record type. Create an SRV record for each service task. The SRV record must specify a container name and container port combination from the task definition.
DNS records for a service discovery service can be queried within your VPC. They use the following format:
<service discovery service name>.<service discovery namespace>. For more information, see Step 3: Verify Service Discovery.
When doing a DNS query on the service name, A records return a set of IP addresses that correspond to your tasks. SRV records return a set of IP addresses and ports per task.
If you have eight or fewer healthy records, Route 53 responds to all DNS queries with all of the healthy records.
When all records are unhealthy, Route 53 responds to DNS queries with up to eight unhealthy records.
You can configure service discovery for an ECS service that is behind a load balancer, but service discovery traffic is always routed to the task and not the load balancer.
Service discovery does not support the use of Classic Load Balancers.
It is recommended to use container-level health checks managed by Amazon ECS for your service discovery service.
HealthCheckCustomConfig—Amazon ECS manages health checks on your behalf. Amazon ECS uses information from container and health checks, as well as your task state, to update the health with AWS Cloud Map. This is specified using the
--health-check-custom-configparameter when creating your service discovery service. For more information, see HealthCheckCustomConfig in the AWS Cloud Map API Reference.
If you are using the Amazon ECS console, the workflow creates one service discovery service per ECS service. It maps all of the task IP addresses as A records, or task IP addresses and port as SRV records.
Service discovery can only be configured when first creating a service. Updating existing services to configure service discovery for the first time or change the current configuration is not supported.
The AWS Cloud Map resources created when service discovery is used must be cleaned up manually. For more information, see Step 4: Clean Up in the Tutorial: Creating a Service Using Service Discovery topic.
Amazon ECS Console Experience
The service create and service update workflows in the Amazon ECS console supports service discovery.
To create a new Amazon ECS service that uses service discovery, see Creating a Service.
Service Discovery Pricing
Customers using Amazon ECS service discovery are charged for Route 53 resources and AWS Cloud Map discovery API operations. This involves costs for creating the Route 53 hosted zones and queries to the service registry. For more information, see AWS Cloud Map Pricing in the AWS Cloud Map Developer Guide.
Amazon ECS performs container level health checks and exposes them to AWS Cloud Map custom health check API operations. This is currently made available to customers at no extra cost. If you configure additional network health checks for publicly exposed tasks, you are charged for those health checks. | https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-discovery.html | CC-MAIN-2019-26 | refinedweb | 1,091 | 54.42 |
Here, we will see how to stop python application or program gracefully ? We will be using system signals to stop python program gracefully.
Generally, We use system signals to stop program gracefully. Why is this needed? Sometimes we need to collect log or useful information before abnormally existing the program or application. This can also be helpful in cleaning up resources before existing the program.
Now, we will look about signals to be used for gracefully terminating the program.
Here, we will be using two signals:
- SIGINT: This signal is used to interrupts a process immediately. The default action of this signal is to terminate a process gracefully. This signal is generated when a user presses ctrl+c.
- SIGTERM: This signal terminates a process immediately. This is also used for graceful termination of a process. The only difference is that, It is generated by shell command kill by default.
Program to demonstrate given above behaviour:
import signal import sys import time class App(object): def __init__(self): self.shutdown = False # Registering the signals signal.signal(signal.SIGINT, self.exit_graceful) signal.signal(signal.SIGTERM, self.exit_graceful) def exit_graceful(self, signum, frame): print('Received:', signum, ": ", frame) self.shutdown = True def run(self): time.sleep(1) print("running App: ") def stop(self): # clean up the resources print("stop the app") if __name__ == "__main__": app = App() while not app.shutdown: app.run() app.stop() sys.exit(0)
Output:
python sample.py running App: running App: running App: ^CReceived: 2 : ===>> Press ctrl + c running App: stop the app
To learn more about golang, Please refer given below link:
References: | https://www.techieindoor.com/python-how-to-stop-python-application-or-program-gracefully/ | CC-MAIN-2022-40 | refinedweb | 264 | 50.94 |
From Script-Behind to Code-Behind
Any elements that appear in a XAML document can be scripted by the companion code that comes with the XAML resource. In Silverlight 1.0, XAML elements can only be scripted using JavaScript functions and their events can be handled exclusively through JavaScript handlers. A common naming convention entails that you name the JavaScript file that contains this code after the page that hosts the plug-in. For example, a page named default.aspx that incorporates Silverlight will be served by a script file named default.aspx.js. This is only a convention, however, and is sometimes referred to as "script-behind".
You typically create XAML documents using the new facilities in Visual Studio 2008 or Expression Studio tools. You then empower these documents using C# or Visual Basic code saved to a classic code-behind file, such as default.aspx.cs. Any code-behind class attached to a XAML document will be downloaded to the client and executed within the local machine. Here's how a XAML document links to a managed class:
<UserControl x: 7lt;Grid> : </Grid> </UserControl>
The x:Class attribute on the UserControl XAML tag instructs the plug-in about the class to instantiate to start up the application. UserControl is generally the root tag of a Silverlight 2.0 page. Where does class Samples.MyPage come from? It is defined in the code-behind file of the XAML document and inherits from UserControl, as in the code snippet below:
namespace Samples { public partial class MyPage : UserControl { public MyPage() { InitializeComponent(); } // Event handlers and helpers go here : } }
The x:Class attribute is the discriminating factor that enables the CoreCLR to run managed code. An XAML document that lacks the attribute can only use JavaScript to handle internal events and provide glue code.
If you use Visual Studio to develop your Silverlight 2.0 application, XAML markup and any related code are compiled into a standard .NET assembly and then packaged in a XAP file along with any required auxiliary resources such as images or perhaps script files. Additional assemblies, if necessary, are added to the XAP bundle as well. What would be the typical size of these packages? A XAP file made of a code-behind class with no external dependencies will hardly exceed 10 KB and often it is around the base size of a .NET assembly, which is 4 KB. If your code depends on external assemblies, all of them are added to the XAP. The overall size, in this case, grows up. Code reuse through assemblies is always a good practice; in Silverlight programming, though, you might want to keep an eye also on the size of the assemblies and thus organize your reusable code in relatively small and simple classes rather than compiled assemblies so that you can reuse just the pieces you need.
Is JavaScript Required to Run Silverlight 2.0 Applications?
Any Silverlight applications require a host page, be it a static HTML page or any flavors of server-side generated page. The host page includes the plug-in as an <object> tag. At least in Silverlight 1.0, it is common to rely on some boilerplate JavaScript code to create the <object> tag on-the-fly and configure it properly. As you can see, this creates a clear dependency: the browser must have JavaScript support enabled in order to run Silverlight applications. This dependency may sound reasonable in Silverlight 1.0 where JavaScript is anyway the only supported language, but is just out of place in the fully .NET-based version of Silverlight 2.0. So is JavaScript required? No, you can host and run a Silverlight application also without JavaScript. All that you have to do is adding manually an <object> tag into the page and make it point to a server-side XAP resource. The plug-in will then automatically download the XAP content, instantiate the related class, and generate any user interface in the browser.
The XAP file is a sort of zipped archive. In fact, it uses the standard ZIP compression algorithm to reduce the size of the files and minimize the client download.
The Silverlight plug-in enables .NET development across a variety of platforms including Windows, Mac and Linux and it brilliantly solves the issue of interoperability that held back the adoption of ActiveX 10 years ago. But what about security? Is it really safe to download and run compiled code over the Internet? | http://www.drdobbs.com/security/the-silverlight-20-security-model/206902613?pgno=2 | CC-MAIN-2014-52 | refinedweb | 746 | 63.9 |
This is the mail archive of the cygwin mailing list for the Cygwin project.
On 1/20/2018 6:49 PM, Ken Brown wrote: > On 1/20/2018 7:23 AM, Ken Brown wrote: >> On 1/19/2018 10:27 PM, Ken Brown wrote: >>> On 1/18/2018 6:28 PM, Ken Brown wrote: >>>> On 1/18/2018 4:30 PM, Yaakov Selkowitz wrote: >>>>> On 2018-01-18 08:35, Ken Brown wrote: >>>>>> On 1/17/2018 5:29 PM, Ken Brown wrote: >>>>>>> Do we need a new gcc release to go along with the recent ssp >>>>>>> changes? >>>>>> >>>>>> The following commit message seems to answer my question: >>>>>> >>>>>> Note that this does require building gcc with >>>>>> --disable-libssp and >>>>>> gcc_cv_libc_provides_ssp=yes. >>>>> >>>>> Correct. >>>>> >>>>>> Are there plans to coordinate the release of Cygwin 2.10.0 with a new >>>>>> gcc release? In the meantime, I guess package maintainers have to >>>>>> build >>>>>> with -U_FORTIFY_SOURCE in order to test building with Cygwin >>>>>> 2.10.0. Or >>>>>> am I missing something? >>>>> >>>>> -D_FORTIFY_SOURCE is not the default, so simply omitting it is >>>>> sufficient. >>>> >>>> I was talking about building projects in which _FORTIFY_SOURCE is >>>> defined by default. That happens, for instance, in the gnulib >>>> subdirectory of the emacs tree, so it may affect other projects that >>>> use gnulib also. >>>> >>>>> You could also just delete >>>>> /usr/lib/gcc/*-pc-cygwin/6.4.0/include/ssp, since we won't need it >>>>> anymore and it wasn't even being used properly in the first place. >>>> >>>> That's a simpler workaround than what I was doing. Thanks. >>> >>> Here's another issue that's come up with _FORTIFY_SOURCE. One of the >>> emacs source files, fileio.c, makes use of a pointer to readlinkat. >>> [More precisely, the file uses an external function foo() with a >>> parameter 'bar' that's a pointer to a function; foo is called in >>> fileio.c with bar = readlinkat.] >>> >>> When _FORTIFY_SOURCE > 0, this leads to an "undefined reference to >>> `__ssp_protected_readlinkat'" linking error. Does this sound like >>> something that will be fixed with the new gcc release? >>> >>> I realize I haven't given you full details, but it might be a few >>> days until I have a chance to extract an STC for this issue, so I >>> thought I'd give it a shot. >>> >>> If you can't answer the question based on the information above, I'll >>> make an STC as soon as I can. >> >> I got to this sooner than expected: >> >> $ cat ssp_test.c >> #define _FORTIFY_SOURCE 1 >> #include <unistd.h> >> void foo (ssize_t (*preadlinkat) (int, char const *, char *, size_t)); >> >> void baz () >> { >> foo (readlinkat); >> } >> >> $ gcc -c -O1 ssp_test.c >> >> $ objdump -x ssp_test.o | grep readlinkat >> 6 .rdata$.refptr.__ssp_protected_readlinkat 00000010 >> 0000000000000000 0000000000000000 00000180 2**4 >> [...] The following patch seems to fix the problem: --- ssp.h~ 2018-01-22 09:18:18.000000000 -0500 +++ ssp.h 2018-01-24 13:44:55.856635800 -0500 @@ -41,7 +41,7 @@ #endif #define __ssp_real(fun) __ssp_real_(fun) -#define __ssp_inline extern __inline__ __attribute__((__always_inline__, __gnu_inline__)) +#define __ssp_inline extern __inline__ __attribute__((__always_inline__)) #define __ssp_bos(ptr) __builtin_object_size(ptr, __SSP_FORTIFY_LEVEL > 1) #define __ssp_bos0(ptr) __builtin_object_size(ptr, 0) I arrived at this by comparing Cygwin's ssp.h with NetBSD's, on which Cygwin's was based, and I noticed that NetBSD didn't use __gnu_inline__. Yaakov, is there a reason that Cygwin needs __gnu_inline__? It apparently prevents fortified functions from being used as function pointers. Using my test case again, here's what happens with and without __gnu_inline__: With: $ gcc -O1 -c ssp_test.c && objdump -x ssp_test.o | grep readlinkat 6 .rdata$.refptr.__ssp_protected_readlinkat 00000010 0000000000000000 0000000000000000 00000180 2**4 CONTENTS, ALLOC, LOAD, RELOC, READONLY, DATA, LINK_ONCE_DISCARD (COMDAT .refptr.__ssp_protected_readlinkat 18) [ 4](sec 7)(fl 0x00)(ty 0)(scl 3) (nx 1) 0x0000000000000000 .rdata$.refptr.__ssp_protected_readlinkat [ 18](sec 7)(fl 0x00)(ty 0)(scl 2) (nx 0) 0x0000000000000000 .refptr.__ssp_protected_readlinkat [ 19](sec 0)(fl 0x00)(ty 0)(scl 2) (nx 0) 0x0000000000000000 __ssp_protected_readlinkat 0000000000000007 R_X86_64_PC32 __ssp_protected_readlinkat RELOCATION RECORDS FOR [.rdata$.refptr.__ssp_protected_readlinkat]: 0000000000000000 R_X86_64_64 __ssp_protected_readlinkat Without: $ gcc -O1 -c ssp_test.c && objdump -x ssp_test.o | grep readlinkat [ 2](sec 1)(fl 0x00)(ty 20)(scl 2) (nx 1) 0x0000000000000000 __ssp_protected_readlinkat [ 27](sec 0)(fl 0x00)(ty 0)(scl 2) (nx 0) 0x0000000000000000 readlinkat 0000000000000005 R_X86_64_PC32 readlinkat Ken -- Problem reports: FAQ: Documentation: Unsubscribe info: | http://cygwin.com/ml/cygwin/2018-01/msg00245.html | CC-MAIN-2018-09 | refinedweb | 706 | 66.94 |
pex — python executables
PythonEXecutables are awesome, they bring everything you need to run your code with them. Just like
virtualenv used to do but without the need of having to initialize a environment or doing that
pip path import hack I recently started using more often (as I didn't want to have to distribute an entire environment)
In a nutshell, you install all your requirements with
pip install -t .pip -r requirements.txt
All modules will be installed into
.pip which you can then use when you add the path to your
PYTHONPATH. You can do that inside your app/script by doing the following
#!/usr/bin/env python
import sys
import os
sys.path.append(sys.path.append(os.path.abspath('.pip')))
import your.modules.from.requirements.txt
So, above isn’t too bad, and you can relatively easy distribute the
.pip directory without needing an entire environment and you also won't need to install any requirements onto the destination machine or container (or environment).
Doing the above isn’t bad, but we can do better! Here is where PEX comes in, a python executable that one builds either by using
pants (python ant) or by using the
pex module. In this example, we'll be using the
pex module.
Install
pex
$ (sudo) pip install pex
Yep, that’s all you have to do to install pex ;)
Building a .pex file
So, unlike virtualenv and the .pip hack, you cannot easily just add a python script and execute it as part of the .pex file as you (or I) may have expected.
To build a .pex file that functions just like virtualenv or .pip with all our requirements installed, you can do the following short steps, ensure you have installed pex (see above) first.
$ pex module1 module2 module3 -o myenv.pex
To use this
myenv.pex (which now has all your required modules available), simply run
$ ./myenv.pex
By default, this will just spin up python itself, then you can import the modules you’ve added to the .pex file or, to run a script, do a simple
$ ./myenv.pex script.py
Using a
requirements.txt file may be easier to create your environment though
$ pex -r requirements.txt -o myenv.pex
Running your script inside the .pex, not as a script
So, it turns out you can run your script inside the .pex file, it’s just simply a tiny bit more work than one would like. Isn’t that great!? Think of a
go static binary, but it's
python.
So, let’s assume you’re wanting to run a script that prints
Hello! when executed, obviously that wouldn't need its own environment, etc. but it's just an exercise.
__init__.py,
hello.py &
setup.py
First, we need to create the necessary directory structure and files to make this a installable python module/package. For this, we will need the following
./hello/__init__.py ./hello/setup.py ./hello/hello.py
__init__.py can just be empty - yay!
setup.py does need some two lines of boilerplate
from distutils.core import setup
setup( name='hello', version='0.0.1', py_modules=['hello'] )
hello.py will just do what we ask it to - print hello
def hello():
print "hello!"
Yep, that’s all we need — great isn’t it?
Build the .pex file
From outside the “hello” module/package/path, run pex to create the pex
$ pex hello -e hello:hello -o hello.pex
This will install the “hello” module that we created into the .pex file, the
-e hello:hello declares an entrypoint which will load the module "hello" and execute the function "hello" when the .pex is being run.
Final result
Output
vagrant@local:/vagrant$ pex hello -e hello:hello -o hello.pex
vagrant@local:/vagrant$ ls
hello
hello.pex
vagrant@local:/vagrant$ ./hello.pex
hello!
File / Dir size comparison
- .pex file with ansible installed : 3 MB
- .pip dir with ansible installed : 17 MB
- virtualenv with ansible installed : 28 MB | https://medium.com/ovni/pex-python-executables-c0ea39cee7f1 | CC-MAIN-2020-10 | refinedweb | 666 | 68.57 |
One of the things I get asked about semi-regularly is when Azure Mobile Apps is going to support .NET Core. It’s a logical progression for most people and many ASP.NET developers are planning future web sites to run on ASP.NET Core. Also, the ASP.NET Core programming model makes a lot more sense (at least to me) than the older ASP.NET applications. Finally, we have an issue open on the subject. So, what is holding us back? Well, there are a bunch of things. Some have been solved already and some need a lot of work. In the coming weeks, I’m going to be writing about the various pieces that need to be in place before we can say “Azure Mobile Apps is there”.
Of course, if you want a mobile backend, you can always hop over to Visual Studio Mobile Center. This provides a mobile backend for you without having to write any code. (Full disclosure: I’m now a program manager on that team, so I may be slightly biased). However, if you are thinking ASP.NET Core, then you likely want to write the code.
Let’s get started with something that does exist. How does one run ASP.NET Core applications on Azure App Service? Well, there are two methods. The first involves uploading your application to Azure App Service via the Visual Studio Publish… dialog or via Continuous Integration from GitHub, Visual Studio Team Services or even Dropbox. It’s a relatively easy method and one I would recommend. There is a gotcha, which I’ll discuss below.
The second method uses a Docker container to house the code that is then deployed onto a Linux App Service. This is still in preview (as of writing), so I can’t recommend this for production workloads.
Create a New ASP.NET Core Application
Let’s say you opened up Visual Studio 2017 (RC right now) and created a brand new ASP.NET Core MVC application – the basis for my research here.
- Open up Visual Studio 2017 RC.
- Select File > New > Project…
- Select the ASP.NET Core Web Application (.NET Core).
- Fill in an appropriate name for the solution and project, just as normal.
- Click OK to create the project.
- Select ASP.NET Core 1.1 from the framework drop-down (it will say ASP.NET Core 1.0 initially)
- Select Web Application in the ASP.NET Core 1.1 Templates selection.
- Click OK.
I called my solution netcore-server and the project ExampleServer. At this point, Visual Studio will go off and create a project for you. You can see what it creates easily enough, but I’ve checked it into my GitHub repository at tag p0.
I’m not going to cover ASP.NET Core programming too much in this series. You can read the definitive guide on their documentation site, and I would recommend you start by understanding ASP.NET Core programming before getting into the changes here.
Go ahead and run the service (either as a Kestrel service or an IIS Express service – it works with both). This is just to make sure that you have a working site.
Add Logging to your App
Logging is one of those central things that is needed in any application. There are so many things you can’t do (including diagnose issues) if you don’t have appropriate logging. Fortunately, ASP.NET Core has logging built-in. Let’s add some to the
Controllers\HomeController.cs file:
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace ExampleServer.Controllers { public class HomeController : Controller { private ILogger logger; public HomeController(ILoggerFactory loggerFactory) { logger = loggerFactory.CreateLogger(this.GetType().FullName); } public IActionResult Index() { logger.LogInformation("In Index of the HomeController", null); return View(); } // Rest of the file here
I’ve added the logger factory via dependency injection, then logged a message whenever the Index file is served in the home controller. If you run this version of the code (available on the GitHub respository at tag p1), you will see the following in your Visual Studio output window:
It’s swamped by the Application Insights data, but you can clearly see the informational message there.
Deploy your App to Azure App Service
Publishing to Azure App Service is relatively simple – right-click on the project and select Publish… to kick off the process. The layout of the windows has changed from Visual Studio 2015, but it’s the same process. You can create a new App Service or use an existing one. Once you have answered all the questions, your site will be published. Eventually, your site will be displayed in your web browser.
Turn on Diagnostic Logging
- Click View > Server Explorer to add the server explorer to your work space.
- Expand the Azure node, the App Service node, and finally your resource group node.
- Right-click the app service and select View Settings
- Turn on logging and set the logging level to verbose:
- Click Save to save the settings (the site will restart).
- Right-click the app service in the server explorer again and this time select View Streaming Logs
- Wait until you see that you are connected to the log streaming service (in the Output window)
Now refresh your browser so that it reloads the index page again. Note how you see the access logs (which files have been requested) but the log message we put into the code is not there.
The Problem and Solution
The problem is, hopefully, obvious. ASP.NET Core does not by default feed logs to Azure App Service. We need to enable that feature in the .NET Core host. We do this in the
Program.cs file:
using System.IO; using Microsoft.AspNetCore.Hosting; namespace ExampleServer { public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .UseApplicationInsights() .UseAzureAppServices() .Build(); host.Run(); } } }
You will also need to add the Microsoft.AspNetCore.AzureAppServicesIntegration package from NuGet for this to work. Once you have done this change, you can deploy this and watch the logs again:
If you have followed the instructions, you will need to switch the Output window back to the Azure logs. The output window will have been switched to Build during the publish process.
Adjusting the WebHostBuilder for the environment
It’s likely that you won’t want Application Insights and Azure App Services logging except when you are running on Azure App Service. There are a number of environment variables that Azure App Service uses and you can leverage these as well. My favorites are
REGION_NAME (which indicates which Azure region your service is running in) and
WEBSITE_OWNER_NAME (which is a combination of a bunch of things). You can test for these and adjust the pipeline accordingly:
using Microsoft.AspNetCore.Hosting; using System; using System.IO; namespace ExampleServer { public class Program { public static void Main(string[] args) { var hostBuilder = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .UseApplicationInsights(); var regionName = Environment.GetEnvironmentVariable("REGION_NAME"); if (regionName != null) { hostBuilder.UseAzureAppServices(); } var host = hostBuilder.Build(); host.Run(); } } }
You can download this code at my GitHub repository at tag p2.
One thought on “Running ASP.NET Core applications in Azure App Service”
[…] Running ASP.NET Core applications in Azure App Service by Adrian Hall […] | https://shellmonger.com/2017/02/16/running-asp-net-core-applications-in-azure-app-service/ | CC-MAIN-2017-13 | refinedweb | 1,216 | 59.09 |
Head over to
/admin/article and log in as an admin user:
admin1@thespacebar.com password
engage. Use this unchecked admin power to go to
/admin/article and click to create a new article.
I love the new "secrets" feature... but what I'm about to show you might be my second favorite new thing. It actually comes from Symfony 4.3 but was improved in 4.4. It's called: validation auto-mapping... and it's one more step towards robots doing my programming for me.
Start by going into
templates/article_admin/_form.html.twig:
This is the form that renders the article admin page. To help us play with validation, on the button, add a
formnovalidate attribute:
Thanks to that, after you refresh, HTML5 validation is disabled and we can submit the entire form blank to see... our server-side validation errors. These come from the annotations on the
Article class, like
@Assert\NotBlank above
$title:
So it's no surprise that if we remove the
@Assert\NotBlank annotation... I'll move it as a comment below the property:
That's as good as deleting it. And then re-submit the blank form... the validation error is gone from that field.
Ready for the magic? Go back to
Article and, on top of the class, add
@Assert\EnableAutoMapping():
As soon as we do that, we can refresh to see... Kidding! We refresh to see... the validation error is back for the
title field!
This value should not be null
Yep! A
@NotNull constraint was automatically added to the property! How the heck did that work? The system - validation auto-mapping - automatically adds sensible validation constraints based off of your Doctrine metadata. The Doctrine
Column annotation has a
nullable option and its default value is
nullable=false:
In other words, the
title column is required in the database! And so, a constraint is added to make it required on the form.
Auto-mapping can also add constraints based solely on how your code is written... I'll show you an example of that in a few minutes. Oh, and by the way, to get the most out of this feature, make sure you have the
symfony/property-info component installed.
composer show symfony/property-info
If that package doesn't come up, install it to allow the feature to get as much info as possible.
Let's play with this a bit more, like change this to
nullable=true:
This means that the column should now be optional in the database. What happens when we submit the form now? The validation error is gone: the
NotNull constraint was not added.
Oh, but it gets even cooler than this. Remove the
@ORM\Column entirely - we'll pretend like this property isn't even being saved to the database. I also need to remove this
@Gedmo\Slug annotation to avoid an error:
What do you think will happen now? Well think about it: the auto-mapping system won't be able to ask Doctrine if this property is required or not... so my guess is that it won't add any constraints. Try it! Refresh!
Duh, duh, duh! The
NotNull validation constraint is back! Whaaaaat? The Doctrine metadata is just one source of info for auto-mapping: it can also look directly at your code. In this case, Symfony looks for a setter method. Search for
setTitle():
Ah yes, the
$title argument is type-hinted with
string. And because that type-hint does not allow null, it assumes that
$title must be required and adds the validation constraint.
Watch this: add a
? before
string to make
null an allowed value:
Refresh now and... the error is gone.
Let's put everything back to where it was in the beginning. What I love about this feature is that... it's just so smart! It accuarely reflects what your code is already communicating.
And even if I add back my
@Assert\NotBlank annotation:
And refresh... check it out. We don't get 2 errors! The auto-mapping system is smart enough to realize that, because I added a
NotBlank annotation constraint to this property, it should not also add the
NotNull constraint: that would basically be duplication and the user would see two errors. Like I said, it's smart.
And it's not all about the
NotNull constraint. The length of this column in the database is 255 - that's the default for a
string type. Let's type a super-creative title over and over and over and over again... until we know that we're above that limit. Submit and... awesome:
This value is too long. It should have 255 characters or less.
Behind-the-scenes, auto-mapping also added an
@Length annotation to limit this field to the column size. Say goodbye to accidentally allowing large input... that then gets truncated in the database.
As cool as this feature is, automatic functionality will never work in all cases. And that's fine for two reasons. First, it's your choice to opt-into this feature by adding the
@EnableAutoMapping annotation:
And second, you can disable it on a field-by-field basis.
A great example of when this feature can be a problem is in the
User class. Imagine we added
@EnableAutoMapping here and created a registration form bound to this class. Well... that's going to be a problem because it will add a
NotNull constraint to the
$password field! And we don't want that!
In a typical registration form - like the one that the
make:registration-form command creates - the
$password property is set to its hashed value only after the form is submitted & validated. Basically, this is not a field the user sets directly and having the
NotNull constraint causes a validation error on submit.
How do you solve this? You could disable auto-mapping for the whole class. Or, you could disable it for the
$password property only by adding
@Assert\DisableAutoMapping:
// src/Entity/User.php class User implements UserInterface { // ... /** * @ORM\Column(type="string", length=255) * @Assert\DisableAutomapping() */ private $password; // ... }
This is the one ugly case for this feature, but it's easy to fix.
Oh, and one more thing! You can control the feature a bit in
config/packages/validator.yaml. By default, you need to enable auto-mapping on a class-by-class basis by adding the
@Assert\EnableAutoMapping annotation:
But, you can also automatically enable it for specific namespaces:
If we uncommented this
App\Entity line, every entity would get auto-mapped validation without needing the extra annotation. I like being a bit more explicit - but it's your call.
Next, ready to talk about something super geeky? No, not Star Trek, but that would awesome. This is probably even better: let's chat about password hashing algorithms. Trust me, it's actually pretty neat stuff. Specifically, I want to talk about safely upgrading hashed passwords in your database to stay up-to-date with security best-practices.
// } } | https://symfonycasts.com/screencast/symfony5-upgrade/auto-mapping | CC-MAIN-2020-45 | refinedweb | 1,167 | 67.86 |
.
@echo off xps2pdf.exe C:\in\*.xps C:\out\*.pdf for /f "delims=?" %%f in ('dir C:\out\*.pdf /b') do ( AcroRd32.exe /t "%%f" "\\servername\printername" del %%f )
@echo off for /f "delims=?" %%f in ('dir *.xps /b') do ( xpsrchvw "%%f" -p )
@echo off :: create kix script for print dialog :: download from >"%temp%\xpsprt.kix" echo sleep 1 >>"%temp%\xpsprt.kix" echo if setfocus( "print" ) = 0 >>"%temp%\xpsprt.kix" echo $rc = sendkeys( "{enter}" ) >>"%temp%\xpsprt.kix" echo endif :: print each xps file :: requires xps viewer for /f "delims=?" %%f in ('dir *.xps /b') do ( call cmd /c start %%f -p kix32 "%temp%\xpsprt.kix" )
If you are experiencing a similar issue, please ask a related question
Join the community of 500,000 technology professionals and ask your questions. | https://www.experts-exchange.com/questions/26401994/Print-XPS-documents-from-command-line.html | CC-MAIN-2017-22 | refinedweb | 129 | 63.56 |
importCommands
The
import statement does not have the same functionality in MATLAB® as in Python®.
Python code uses the
import statement to load and make
code accessible. MATLAB automatically loads Python when you type
py. in front of the
module name and function name. This code shows how to call a function
wrap in Python module
textwrap.
Caution
In MATLAB, do not type:
import pythonmodule
Never call:
import py.*
If you do, then MATLAB calls the Python function instead of the MATLAB function of the same name. This can cause unexpected behavior. If you type this
import command, then you must call the MATLAB command:
clear import
The Python
from...import statement lets you reference a module without using
the fully qualified name. In MATLAB, use the
import function. This code shows
how to reference function
wrap in Python module
textwrap. Since
wrap is
not a MATLAB function, you can shorten the calling syntax using the
import function. After calling this command, you do not need
to type the package (
py) and module (
textwrap)
names.
For a complete description of Python functionality, consult outside resources, in particular,. There are different versions of the Python documentation, so be sure to refer to the version corresponding to the version on your system. Many examples in the MATLAB documentation refer to functions in the Python standard library.
To use functions in a third-party or user-defined Python module, refer to your vendor product documentation for information about how to install the module and for details about its functionality.
The MATLAB
py.help command displays the Python help found at. Help for packages and classes can be extensive and might not be useful when displayed in the MATLAB command window.
Package
py.help('textwrap')
Class
py.help('textwrap.TextWrapper')
Method of a class
py.help('textwrap.TextWrapper.wrap')
Function
py.help('textwrap.fill')
If MATLAB displays an error message beginning with
Python Error:, refer to your Python documentation for more information.
Note
Tab completion does not display available Python functionality.
You cannot use the interactive Python help — calling
py.help without input arguments — in MATLAB.
If a Python method name is the name of a sealed method of a MATLAB base class or reserved function, then MATLAB renames the method. The new name starts with the letter
x and changes the first letter of the original name to uppercase.
For example, MATLAB renames the Python method
cat to
xCat. For a list of
reserved methods, see Methods That Modify Default Behavior.
If a method name is a MATLAB keyword, then MATLAB calls
matlab.lang.makeValidName to rename the
method. For a list of keywords, see
iskeyword.
If a generated name is a duplicate name, then MATLAB renames the method using
matlab.lang.makeUniqueStrings.
evalFunction
This example shows how to evaluate the expression
x+y using the
Python
eval command. Read the help for
eval.
py.help('eval')
Help on built-in function eval in module __builtin__:.
To evaluate an expression, pass a Python
dict value for the
globals namespace
parameter.
Create a Python
dict variable for the
x and
y
values.
workspace = py.dict(pyargs('x',1,'y',6))
workspace = Python dict with no properties. {'y': 6.0, 'x': 1.0}
Evaluate the expression.
res = py.eval('x+y',workspace)
res = 7
Alternatively, to add two numbers without assigning variables, pass an empty
dict value for the
globals parameter.
res = py.eval('1+6',py.dict)
res = 7
To execute a callable Python object, use the
feval function. For example, if instance
obj of a Python class is callable, replace the Python syntax
obj(x1, ..., xn) with one of the following MATLAB statements:
feval(obj,x1, ..., xn)
obj(x1, ..., xn)
MATLAB supports the following overloaded operators.
The following Python operators are not supported. | https://kr.mathworks.com/help/matlab/matlab_external/differences-between-matlab-python.html | CC-MAIN-2020-45 | refinedweb | 630 | 59.6 |
Random Search and Appropriate Search-Space Scaling
Grid search isn’t always our best approach for figuring out our best hyperparameters.
In the example of Deep Learning and Adam Optimization, there are several different hyperparameters to consider. Some, like the
alpha constant, need tuning. On the other hand, constants like
epsilon are basically taken as granted and don’t affect the model.
from IPython.display import Image Image('images/feature_grid.PNG')
By grid searching over any feature space that includes
epsilon, we’re putting five times the computation on our system for less-than-negligible performance gain.
Instead, Andrew Ng suggests doing a random search over the feature space to arrive at your coefficients. If instead, we did half the number of searches in a random fashion (below), we’d still get the learnings from tuning
alpha, without over-searching in the
epsilon space.
Image('images/feature_grid_random.png')
But this presents a new, interesting problem.
Whereas something like Number of Layers or Number of Hidden units might make sense to sample from on a linear scale, not all coefficients behave this way.
For instance, adjusting our
alpha constant between
0.05 and
0.06 likely has a bigger performance impact than adjusting between
0.5 and
0.6, as it’s often a low-valued number.
And so by sampling randomly on a linear scale between
0.0001 and and
1, we spend as much compute resources investigating the upper-range values as the incremental, lower ones where the real optimization occurs.
Image('images/uniform_alpha.PNG')
Scaling
Thus, determining the correct scaling mechanism for your hyperparameters is crucial. You want to scale, based on the class of the coefficient, which may include the following:
Linear
This one’s easy. We just want to do a uniform search between two values.
import numpy as np min_val, max_val = 0, 1 np.random.uniform(min_val, max_val)
0.9358677626967968
Discrete
For whole-numbered values between two values, we’ll use
randint()
np.random.randint(0, 10)
2
Log Scale
For coefficients, like
alpha above, where we want to select between a very small value and
1, it’s helpful to consider how to write it out as an exponent. For instance:
$0.0001 = 10^{-4}$
similarly
$1 = 10^{0}$
So this is actually just the same exercise as the Linear Scale, but between some negative number and
0, then piped as an exponent!
min_exp, max_exp = -4, 0 val = np.random.uniform(min_exp, max_exp) 10 ** val
0.00305918793992655
Exponentially Weighted
This would likely be better-named as “Reverse Log Scale,” describing hyperparameters where your search space is most effective between, say,
0.9 and
0.999, on a Log-ish scale.
Following the same approach as above, we just want to do a uniform search over the correct range of values, plus some other steps– in this case, establishing a log log scale for
0.9 to
0.999 involves establishing a log scale for
0.0001 to
0.1 and subtracting that from
1
min_exp, max_exp = -3, -1 val = np.random.uniform(min_exp, max_exp) 1 - (10 ** val)
0.9908195535776579 | https://napsterinblue.github.io/notes/machine_learning/model_selection/random_search/ | CC-MAIN-2021-04 | refinedweb | 515 | 58.89 |
Opened 6 years ago
Closed 3 years ago
#12836 closed Bug (fixed)
Model.get_absolute_url lose method attributes
Description
class MyModel(models.Mode): @models.permalink @set_attr('x', 10) # set some attribute to MyModel.get_absolute_url method def get_absolute_url(self): return ('some', (self.attr, )) >>>print MyModel().get_absolute_url.x AttributeError: 'function' object has no attribute 'x'
Attachments (2)
Change History (13)
Changed 6 years ago by minmax
comment:1 follow-up: ↓ 2 Changed 6 years ago by russellm
- Has patch set
- Needs documentation unset
- Needs tests set
- Patch needs improvement unset
- Triage Stage changed from Unreviewed to Accepted
comment:2 in reply to: ↑ 1 Changed 6 years ago by minmax
Changed 6 years ago by minmax
comment:3 Changed 6 years ago by minmax
- Resolution set to duplicate
- Status changed from new to closed
comment:4 Changed 6 years ago by carljm
- Resolution duplicate deleted
- Status changed from closed to reopened
comment:5 Changed 5 years ago by lukeplant
- Type set to Bug
comment:6 Changed 5 years ago by lukeplant
- caleb.smithnc@…
- Needs tests unset
I added a pull request that adds the test here:
The fix.diff at the top was already applied, but the doc test in test.diff isn't. I simply rewrote it as a unit test.
comment:10 Changed 3 years ago by Caleb Smith <csmith@…>
comment:11 Changed 3 years ago by melinath
- Resolution set to fixed
- Status changed from reopened to closed
So apparently this was fixed as a side effect of fixing #15604. (See). And the commit referenced by Caleb above adds tests for the specific use case mentioned here.
I am prompted to ask "why?", but using wraps on is good practice in general, so I'll accept. | https://code.djangoproject.com/ticket/12836 | CC-MAIN-2015-48 | refinedweb | 284 | 59.64 |
Apache Spark is a very powerful analytic engine for big data processing, and has become more and more popular in different areas of big data industry very recently. Spark includes built-in modules for streaming, SQL, machine learning and graph processing. It provides high-level APIs in Java, Scala, Python and R.
The package PySpark is a Python API for Spark. It is great for performing exploratory data analysis at scale, building machine learning pipelines, creating ETL pipelines for data platforms, and many more. …
Timing a function is one way to evaluate its performance. This post demonstrates how to use decorator to time a function.
It is very straightforward, if we want to time a function directly. The code snippet below demonstrate how to do it.
import time
start = time.time()
result = function_to_be_timed()
end = time.time()
print(f'function_to_be_timed() takes {end-start} seconds.'
With decorator, the code for timing can be reused. Below is an example implementation of a timer decorator.
def timed(fnc): from functools import wraps import time @wraps(fnc) def wrapper(*args, **kwargs): start = time.time() result = fnc(*args, **kwargs) end = time.time() arg_str = ','.join([str(arg)…
In some practical cases, how often a specific function can be invoked may need to be controlled. This post demonstrates how this can be done in python by using Decorator.
Assume we don’t want the function to be called more than some certain number of times within a given duration. In the closure the decorator returns, we define a list for storing the time at which the function is called. For the convenience of description, we call the time at which the function is called the invocation time. When the number of invocation times exceeds the maximum we wanted to…
Jan. 18. 2016
QtCreator is a very convenient IDE for developing Qt GUI programs. Under Ubuntu Linux 14.04, this note demonstrates an alternative way to develop Qt GUI programs without using QtCreator in an example.
First, use any text editor, say gedit, nodepad++, etc, to edit your source code. Here for simplicity, we write everything in a single .cpp file as follows.
// main.cpp
#include <QApplication>
#include <QTreeView>
#include <QStandardItemModel>using namespace std;int main(int argc, char* argv[])
{
QApplication a(argc, argv);
QTreeView *tree = new QTreeView;
QStandardItemModel model(3, 3); for (int i = 0; i < 3; i++)…
Jan. 21. 2016
Roughly speadking, build in software development is the process of “translating” source code files into executable binary code files[1]; and a build system is a collection of software tools that is used to facilitate the build process[2]. Despite the fact that different build systems have been “invented” and used for over three decades, the core algorithms used in most of them are not changed much since the first introduction of the directed acyclic graph ( DAG) by Make[3]. Popular build systems nowadays include the classical GNU Make, CMake, QMake, Ninja, Ant, Scons, and many others. …
Dec. 30. 2015
Factory method is a very important design pattern in object oriented designs[1]. The main goal of this pattern is to allow the client to create objects without having to specify the details of the objects to create. It returns one of several possible classes that share a common super class. This post is not going to discuss factory pattern in C++ or any other OOP language. Instead, a similar implementation of the pattern in the programming language C will be discussed.
Function factory has two slightly different prototypes:
return_type (*function_factory_name(fac_type1 fac_param1, fac_type2 fac_param2, …))(fun_type1 fun_param1, fun_type2 fun_param2…
Nov. 30. 2015
A function with variable number of arguments is called a variadic function, and also known as variable argument function [1]. Due to its flexibility in size of the list of input arguments, it is very useful especially in system programming. Its usual use cases include summing of numbers, concatenating strings, and so on. Typical examples include the printf in C programming language, execl and execlp in Unix, _execl and _execlp in Windows, and many others. This post introduces how to declare/define and use such functions.
Declaration of a variadic function is almost same as an “ordinary” function…
Nov. 23. 2015
In this post, after introducing two preliminary concepts, I explain what virtual inheritance is, and how it is implemented, then introduce two applications of virtual inheritance. One involves multiple inheritance, and the other involves implementation of non-inheritability. For each case, one example demonstrating how virtual inheritance works is presented.
Before discussing virtual inheritance, it is necessary to explain two very important concepts in OOP (Object Oriented Programming) concepts, static and dynamic binding.
Roughly speaking, static binding occurs at compile time, and dynamic binding occurs at run time. In C++, the two kinds of polymorphism (see Appendix for…
Senior Software/Data Engineer | https://chuan-zhang.medium.com/?source=post_internal_links---------5---------------------------- | CC-MAIN-2021-17 | refinedweb | 798 | 55.95 |
Dimensions of an object in perspective view
On 15/01/2013 at 04:36, xxxxxxxx wrote:
A camera should automatically change its distance to an object in that way, that the object is completely in the viewcone of the camera.
The calculations are simple as long as the camera is on the coordinatesystem axis. Its getting complicated when the camera is in a solid angle to the object. For example the length between the extreme points of a cube is larger as if the camera is on the coordinate system axis.
Does Cinema 4D grants the possibilty to get the twodimensional coordinates of an object? So to say the coordinates of the object what the camera sees, whats shown in the render window.
If not I have to use projection matrices, what I really don't like to do. Is there any other possibility left?
I hope I made myself understandable enough. Thank you!
On 25/01/2013 at 03:00, xxxxxxxx wrote:
Hi,
You can retrieve the current BaseDraw and call the methods to convert a point from world space to screen space (BaseView.WS()), screen space to camera space (BaseView.SC()) etc.
EDIT:
Here's how we can use BaseView methods (WS(), GetSafeFrame()) to test if the active object will be completely rendered:
import c4d def TestPointInFrame(pt, frame) : return pt.x > frame['cl'] and pt.x < frame['cr'] and \n pt.y > frame['ct'] and pt.y < frame['cb'] def main() : if op is None: return # Get the current BaseDraw bd = doc.GetActiveBaseDraw() # Get the active object bouding box center and radius rd = op.GetRad() mp = op.GetMp() # Build the active object bouding box box = [c4d.Vector() for x in xrange(8)] box[0] = c4d.Vector() box[0].x = mp.x - rd.x box[0].y = mp.y - rd.y box[0].z = mp.z - rd.z box[0] *= op.GetMgn() box[1] = c4d.Vector() box[1].x = mp.x + rd.x box[1].y = mp.y - rd.y box[1].z = mp.y - rd.z box[1] *= op.GetMgn() box[2] = c4d.Vector() box[2].x = mp.x - rd.x box[2].y = mp.y + rd.y box[2].z = mp.y - rd.z box[2] *= op.GetMgn() box[3] = c4d.Vector() box[3].x = mp.x - rd.x box[3].y = mp.y - rd.y box[3].z = mp.y + rd.z box[3] *= op.GetMgn() box[4] = c4d.Vector() box[4].x = mp.x + rd.x box[4].y = mp.y + rd.y box[4].z = mp.z - rd.z box[4] *= op.GetMgn() box[5] = c4d.Vector() box[5].x = mp.x - rd.x box[5].y = mp.y + rd.y box[5].z = mp.y + rd.z box[5] *= op.GetMgn() box[6] = c4d.Vector() box[6].x = mp.x - rd.x box[6].y = mp.y - rd.y box[6].z = mp.y + rd.z box[6] *= op.GetMgn() box[7] = c4d.Vector() box[7].x = mp.x + rd.x box[7].y = mp.y + rd.y box[7].z = mp.y + rd.z box[7] *= op.GetMgn() # Calculate bouding box coordinates in screen space points = [c4d.Vector() for x in xrange(8)] for i in xrange(len(box)) : points[i] = bd.WS(box[i]) # Test if the current object is completely visible in the rendered safe frame safeFrame = bd.GetSafeFrame() for i in xrange(len(points)) : visible = TestPointInFrame(points[i], safeFrame) if not visible: break print "Active Object Completely Visible:", visible if __name__=='__main__': main()
On 28/01/2013 at 01:21, xxxxxxxx wrote:
Thank you very much! This is exactly what I was looking for. Couldn't find anything in the documentation... | https://plugincafe.maxon.net/topic/6864/7679_dimensions-of-an-object-in-perspective-view/3 | CC-MAIN-2019-30 | refinedweb | 613 | 68.97 |
Opened 6 years ago
Closed 6 years ago
#4005 closed enhancement (fixed)
GDALPolygonize should also be able to read raster values into a 32bit float buffer
Description
And even a 64bit double if possible.
This is necessary for PostGIS raster to be able to polygonize many elevation or temperature rasters.
Change History (10)
comment:1 Changed 6 years ago by
comment:2 Changed 6 years ago by
comment:3 Changed 6 years ago by
Jorge,
you might want to revise the doxygen comment for the new function. The below paragraph, taken from GDALPolygonize(), seems to no longer apply.
* Note that currently the source pixel band values are read into a * signed 32bit integer buffer (Int32), so floating point or complex * bands will be implicitly truncated before processing.
It might also be good to add a link in the doxygen comment of GDALPolygonize() to point to GDALFPolygonize(), and vice versa.
I've some doubts about the implementation of the equals() function. "int aInt = *(int*)&A", A being a float seems risky because it will violate strict aliasing. With some compilers and some optimization options, it might generate a no-op and aInt could be filled with garbage, a float* being not a valid alias for a int*. Here's what g++ -O2 gives :
fpolygonize.cpp: In function ‘GBool equals(float, float)’: fpolygonize.cpp:58: warning: dereferencing type-punned pointer will break strict-aliasing rules fpolygonize.cpp:63: warning: dereferencing type-punned pointer will break strict-aliasing rules
I've been bitten by this in the past: see
I'd encourage you doing a memcpy(&aInt, &A, 4) instead.
I'm also wondering how portable this function is for a big-endian CPU ... It might need some byte-swapping but I'm not 100% sure
Might also be good to add a static keyword before the declaration of the equals() method, to avoid namespace collisions with other code...
comment:4 Changed 6 years ago by
comment:5 Changed 6 years ago by
Thanks for your comments Even. I'll commit the needed changes ASAP.
comment:6 Changed 6 years ago by
Quick question about Doxygen comments. If I want to reference another function in a different file, should I use @see and/or @file?
comment:7 Changed 6 years ago by
Apparently, just putting the function name, e.g. "GDALPolygonize()", is sufficient for doxygen to figure out it is a function and create the hyperlink.
comment:8 Changed 6 years ago by
- The "equals" name has been replaced by "GDALEqualsFloat". The function is not static because is used in 2 sources. I think the name change will avoid collisions. Anyway, it probably needs to be reviewed for portability
- Doxygen comments added in GDALPolygonize and GDALFPolygonize.
- Memcpy used. I forgot to mention in the commit message. Sorry for that.
An alternative GDALPolygonize2 function may be a good idea, to avoid side effects. | http://trac.osgeo.org/gdal/ticket/4005 | CC-MAIN-2017-26 | refinedweb | 479 | 63.7 |
Chapter 16 from Microsoft Windows 2000 TCP/IP Protocols and Services Technical Reference, published by Microsoft Press
For the Windows Server 2003 version of this book, see Microsoft® Windows® Server 2003 TCP/IP Protocols and Services Technical Reference.
Every host that runs TCP/IP must have a unique IP address that's used when communicating with other computers in a network. Computers operate easily with IP addresses, but people don't; users would rather identify systems by a name. To facilitate effective and efficient communication, users need to be able to refer to computers by name, and still have their computer use IP addresses transparently.
In the early days of the ARPANET, the forerunner to today's Internet, there were only a small number of computers attached to the network. The Network Information Center (NIC), located at Stanford Research Institute (SRI), was responsible for compiling a single file, HOSTS.TXT, which contained the names and addresses of every computer. Administrators would email SRI, which would then update the HOSTS.TXT file. Next, ARPANET users would download the new version of HOSTS.TXT using File Transfer Protocol (FTP).
As the ARPANET grew, it became obvious that this approach wouldn't scale, for the following three key reasons:
The bandwidth consumed in transmitting updated versions of an ARPANET-wide host file was proportional to the square of the number of hosts in the ARPANET. With the number of hosts growing at an exponential rate, the long-term impact was likely to be a load that no one host was going to be able to sustain.
The static flat host file also meant that no two computers on the ARPANET could have the same name. As the number of hosts grew, the risk of adding a duplicate name grew, as did the difficulty of trying to control this centrally.
The nature of the underlying network was changing—the large, timesharing computers that had once made up the ARPANET were being superseded by networks of workstation—seach of which needed to have a unique host name. This would be difficult, if not impossible, to control centrally.
As the ARPANET continued to grow, it became clear that ARPANET needed a better solution. Several proposals were generated based on the concept of a distributed naming service, which was based on a hierarchical name space. RFCs 882 and 883 emerged, which described the design for a domain name system, based on a distributed database containing generalized resource information. This design evolved, and RFCs 1034 and 1035 were issued to describe the Domain Name System (DNS) service used in today's Internet. This design continues to evolve, and a number of proposed updates and refinements are being discussed as this chapter is being written.
Chapter Contents
Overview to DNS in Microsoft Windows 2000
How DNS Works
DNS Resource Records
DNS Messages
Summary
This chapter describes Microsoft Windows 2000's implementation of the DNS protocol. Additionally, there are Network Monitor traces on the companion CD-ROM that demonstrate the DNS protocol in operation.
This chapter contains the following sections:
Overview to DNS in Windows 2000 A description of the DNS protocol as implemented in Windows 2000
How DNS Works A description of how DNS works, illustrated by various Network Monitor traces
DNS Messages Describes the format of the messages sent between DNS clients and DNS servers, and the functions provided
Server-Server DNS Messages Describes the format of messages sent between DNS servers
This chapter doesn't discuss the administration of a DNS system, however. The care and feeding of a DNS service could, and does, fill complete books, and we won't duplicate that effort here. See the bibliography for details of recommended books covering DNS administration considerations.
To facilitate communications between computers, computers can be given names within a name space. The specific name space defines the rules for naming a computer, and for how names are resolved into IP addresses. When one computer communicates with other computers, it must resolve, or convert, a computer name into an IP address based on the rules of the name space being used. This resolution will be done by a name-resolution service.
There are two main name spaces, and name-resolution methods, used within Windows 2000: NetBIOS, implemented by Windows Internet Naming Service (WINS) (described in Chapter 17), and the DNS, described in this chapter. Windows 2000 also provides support for other name spaces, such as Novell Netware and Banyan Vines, although discussion of these is outside the scope of this book.
In this section, we'll describe DNS and the protocol used to provide name resolution.
The DNS is an IETF-standard name service. The DNS service enables client computers on your network to register and resolve DNS domain names. These names are used to find and access resources offered by other computers on your network or other networks, such as the Internet..
This section describes the key components of the DNS and defines key DNS terms.
Domain Name Space
The domain name space is a hierarchical, tree-structured name space, starting at an unnamed root used for all DNS operations. In the DNS name space, each node and leaf in the domain name space tree represents a named domain. Each domain can have additional child domains. Figure 16-1 illustrates the structure of Internet domain name space.
Domain Names
Each node in the DNS tree, as Figure 16-1 illustrates, has a separate name, referred to in RFC 1034 as a label. Each DNS label can be from 1 through 63 characters in length, with the root domain having a length of zero characters.
A specific node's domain name is the list of the labels in the path from the node being named to the DNS Tree root. DNS convention is that the labels that compose a domain name are read left to right—from the most specific to the root (for example,). This full name is also known as the fully qualified domain name (FQDN).
Domain names can be stored as upper case or lower case, but all domain comparisons and domain functions are defined, by RFC 1034, to be case insensitive. Thus, is identical to for domain naming operations.
Top-Level Domains
A top-level domain is a DNS domain directly below the root. As Figure 16-1 illustrates, a number of top-level domains have been defined. Additional names (at least for the Internet) are difficult to create. The following are the three categories of top-level domains:
"ARPA" This is a special domain—used today for reverse-name lookups.
3-letter domains There are six 3-character, top-level domains noted below.
2-letter country-based domain names These country code domains are based on the International Organization for Standardization (ISO) country name, and are used principally by companies and organizations outside the US. The exception is the UK, which uses .uk as the top-level domain, even though the ISO country code is GB.
Table 16-1 shows the six top-level domains in use today, as defined by RFC 1591.
Table 16-1 3-Character Top-Level Domains in Use in the Internet
3-Character Domain Name
Use
com
Commercial organizations, such as microsoft.com for the Microsoft Corporation
edu
Educational institutions, now mainly four-year colleges and universities, such as cmu.edu for Carnegie Mellon University
gov
Agencies of the US Federal Government, such as fbi.gov for the US Federal Bureau of Investigation
int
Organizations established by international treaties, such as nato.int for NATO
mil
US military, such as af.mil for the US Air Force
net
Computers of network providers, organizations dedicated to the Internet, Internet Service Providers (ISPs), and so forth, such as internic.net for the Internet Network Information Center (InterNIC)
org
A top-level domain for groups that don't fit anywhere else, such as non-government or non-profit organizations (for example, reiki.org for information about Reiki)
Note: While these are the only 3-letter domains available today, there is pressure to expand this number; we may well end up with more in the future.
Resource Records (RR)
A resource record is a record containing information relating to a domain that the DNS database can hold and that a DNS client can retrieve and use. For example, the host RR for a specific domain holds the IP address of that domain (host); a DNS client will use this RR to obtain the IP address for the domain.
Each DNS server contains the RRs relating to those portions of the DNS namespace for which it's authoritative (or for which it can answer queries sent by a host). When a DNS server is authoritative for a portion of the DNS name space, those systems' administrators are responsible for ensuring that the information about that DNS name space portion is correct. To increase efficiency, a given DNS server can cache the RRs relating to a domain in any part of the domain tree.
There are numerous RR types defined in RFCs 1035 and 1036, and in later RFCs. Most of the RR types are no longer needed or used, although all are fully supported by Windows 2000. Table 16-2 lists the key RRs that might be used in a Windows 2000 network. (For more detail on the contents of specific RRs, see the "DNS Resource Records" section later in this chapter.)
Table 16-2 Key Resource Records as Used by a Windows 2000 Network
Resource Record Type
Contents
A
Host Address
Used to hold a specific host's IP address.
CNAME
Canonical Name (alias)
Used to make an alias name for a host.
MX
Mail Exchanger
Provides message routing to a mail server, plus backup server(s) in case the target server isn't active.
NS
Name Server
Provides a list of authoritative servers for a domain or indicates authoritative DNS servers for any delegated sub-domains.
PTR
Pointer
Used for reverse lookup—resolving an IP address into a domain name using the IN-ADDR.ARPA domain.
SOA
Start of Authority
Used to determine the DNS server that's the primary server for a DNS zone and to store other zone property information.
SRV
Service Locator
Provides the ability to find the server providing a specific service. Active Directory uses SRV records to locate domain controllers, global catalog servers, and Lightweight Directory Access Protocol (LDAP) servers.
RRs can be attached to any node in the DNS tree, although RRs won't be provided in some domains (for example, Pointer (PTR) RRs are found only in domains below the in-addr.arpa domain). Thus, higher-level domains, such as microsoft.com, can have individual RRs (for example, Mail Exchange (MX) record for mail to be sent to the Microsoft Corporation) as well as having sub-domains that also might have individual RRs (for instance, eu.microsoft.com, which has a host record).
Canonical Names
The Canonical Name (CNAME) RR enables the administrator to create an alias to another domain name. The use of CNAME RRs are recommended for use in the following scenarios:
When a host specified in an (A) RR in the same zone needs to be renamed. For example, if you need to rename kona.kapoho.com to hilo.kapoho.com, you could create a CNAME entry for kona.kapoho.com to point to hilo.kapoho.com.
When a generic name for a well-known service, such as ftp or www, needs to resolve to a group of individual computers (each with an individual (A) RR). For example, you might want to be an alias for kona.kapoho.com and hilo.kapoho.com. A user will access and generally won't be aware of which computer is actually servicing this request.
DNS Query Operation
A DNS client issues a query operation against a DNS server to obtain some or all of the RR information relating to a specific domain, for instance, to determine which host (A) record or records are held for the domain named kapoho.com. If the domain exists and the requested RRs exist, the DNS server will return the requested information in a query reply message. The query reply message will return both the initial query and a reply containing the relevant records, assuming the DNS server can obtain the required RRs.
A DNS query, referred to in RFC 1034 as a standard query, contains a target domain name, a query type, and a query class. The query will contain a request for the specific RR(s) that the resolver wished to obtain (or a request to return all RRs relating to the domain).
DNS Update Operation
A DNS update operation is issued by a DNS client against a DNS server to update, add, or delete some or all of the RR information relating to a specific domain, for instance, to update the host record for the computer named kona.kapoho.com to point to 10.10.1.100. The update operation is also referred to as a dynamic update..
Traditionally, the master copy of each zone is held in a primary zone on a single DNS server. On that server, the zone has a Start Of Authority (SOA) record that specifies it to be the primary zone. To improve performance and redundancy, a primary zone can be automatically distributed to one or more secondary zones held on other DNS servers. When changes are made to the zone, for instance, to add an (A) record, the changes are made to the primary zone and are transferred to the secondary zone. The transfer of zone information is handled by the zone replication process, which is described later in the "Zone Transfer" section.
When a zone is first created in Windows 2000, the zone will only hold information about a single DNS domain name, for example, kapoho.com. After the zone is created, the administrator can then add RRs to the zone, or can set the domain to be dynamically updated. For example, the administrator could add (A) records (host records) for hosts in the domain, such as kona.kapoho.com. If dynamic updates are enabled for the zone, a Windows 2000 computer can then directly update the A and PTR records on the DNS server (if the DNS client is also a DHCP client, the administrator can configure a DHCP server to send the updates).
Once the administrator has created the zone, he can add additional sub-domains to the zone (for example, jh.kapoho.com). These might be added to provide DNS services to a new building that is managed separately from the parent domain. This sub-domain, which might reside in a separate zone, would have RRs added (for example, a host record for jasmine.jh.kapoho.com).
As Figure 16-2 illustrates, if other domains are added below the domain used initially to create the zone, these domains can either be part of the same zone or belong to another. For example, the sub-domain jh.kapoho.com, which is subordinate to kapoho.com, could be held in the same zone as kapoho.com, or in a separate zone. This allows the sub-domain to be managed and included as part of the original zone records, or to be delegated away to another zone created to support that sub-domain.
In this example, the domain kapoho.com has a sub-domain of jh.kapoho.com. Additionally, both domains contain a single host record. In this example, the domains jh.kapoho.com and kapoho.com are held in separate zones on different DNS servers. The kapoho.com zone holds one host record for kona.kapoho.com. The jh.kapoho.com domain holds the host record for the host jasmine.jh.kapoho.com.
Active Directory-Integrated Zones
A major new feature in the Windows 2000 DNS service is the ability to store DNS zones within the AD. An Active Directory-integrated zone is a primary DNS zone that's held within the AD and replicated to other AD primary zones, using AD replication (and not traditional zone transfer). Although this method of holding zones is a Microsoft proprietary approach, it can provide some useful benefits.
The main advantage of AD-integrated zones is that the zones become, in effect, multi-master, with the capability of updates being made to any DNS server. This can increase the fault tolerance of the DNS service. In addition, replication of zone information occurs using AD replication, which can be more efficient across slow links, because of the way that AD compresses replication data between sites.
Reverse-Lookup Zones
Most queries sent to a DNS server involve a search based on the DNS name of another computer as stored in an address (A) RR. This type of query expects an IP address as the resource data for the answered response. This type of query is generally referred to as a forward query. DNS also provides a reverse-lookup process, which enables a host to determine another host's name based on its IP address. For example, "What is the DNS domain name of the host at IP address 10.10.1.100?"
To allow for reverse queries, a special domain, in-addr.arpa, was defined and reserved in the Internet DNS name space. Sub-domains within the in-addr.arpa domain are named using the reverse ordering of the numbers in the dotted-decimal notation of IP addresses. The reverse ordering of the domain name is needed because, unlike DNS names, IP addresses are read from left to right, but are interpreted in the opposite manner (that is, the left-most part is more generalized than the right-most part). For this reason, the order of IP address octets is reversed when building the in-addr.arpa domain tree; for example, the reverse-lookup zone for the subnet 192.168.100.0 is 100.168.192.in-addr.arpa.
This approach enables the administration of lower limbs of the DNS in-addr.arpa tree to be delegated to an organization when it obtains a set of IP addresses from an IP registry.
The in-addr.arpa domain tree makes use of the PTR RR. The PTR RR is used to associate the IP address to the owning domain name. This lookup should correspond to an Address RR for the host in a forward-lookup zone. The success of a PTR RR used in reverse query depends on the validity of its pointer data, the (A) RR, which must exist.
Note: The in-addr.arpa domain is used only for Internet Protocol version 4 (IPv4)-based networks. In the Windows 2000 DNS Microsoft Management Console (MMC) snap-in, the DNS server's New Zone wizard will use this domain when it creates a new reverse-lookup zone. Internet Protocol version 6 (IPv6)-based reverse-lookup zones are based on the domain ip6.arpa.
Reverse Queries
A reverse query is one in which the DNS server is requested to return the DNS domain name for a host at a particular IP address. Reverse-Lookup Query messages are, in effect, standard queries, but relating to the reverse-lookup zone. The reverse-lookup zone is based on the in-addr.arpa domain name and mainly holds PTR RRs.
Note: The creation of reverse-lookup zones and the use of PTR RRs for identifying hosts are optional parts of the DNS standard. Reverse-lookup zones aren't required in order to use Windows 2000, although some networked applications can be configured to use the reverse-lookup zones as a form of additional security.
Inverse Queries
Inverse queries originally were described in RFC 1032, but now are outdated. Inverse queries were meant to look up a host name based on its IP address and use a nonstandard DNS query operation. The use of inverse queries is limited to some of the earlier versions of NSLOOKUP.EXE, a utility used to test and troubleshoot a DNS service. The Windows 2000 DNS server recognizes and accepts inverse query messages and answers them with a "fake" inverse query response.
DNS Query Classes
DNS queries fall into one of two classes: recursive queries and iterative queries.
A recursive query is a DNS query sent to a DNS server in which the querying host asks the DNS server to provide a complete answer to the query, even if that means contacting other servers to provide the answer. When sent a recursive query, the DNS server will use separate iterative queries to other DNS servers on behalf of the querying host to obtain an answer for the query.
An iterative query is a DNS query sent to a DNS server in which the querying host requests it to return the best answer the DNS server can provide without seeking further assistance from other DNS servers.
In general, host computers issue recursive queries against DNS servers. The host assumes that the DNS server either knows the answer to the query, or can find the answer. On the other hand, a DNS server will generally issue iterative queries against other DNS servers if it is unable to answer a recursive query from cached information.
DNS Resolver
In Windows 2000, the DNS resolver is a system component that performs DNS queries against a DNS server (or servers). The Windows 2000 TCP/IP stack is usually configured with the IP address of at least one DNS server to which the resolver sends one or more queries for DNS information.
In Windows 2000, the resolver is part of the DNS Client service. This service is installed automatically when TCP/IP is installed, and runs as part of the Services.Exe process. Like most Windows 2000 services, the DNS Client service will log on using the Windows 2000 System account.
DNS Resolver Cache
An IP host might need to contact some other host on a regular basis, and therefore would need to resolve a particular DNS name many times (such as the name of the mail server). To avoid having to send queries to a DNS server each time the host wants to resolve the name, Windows 2000 hosts implement a special cache of DNS information.
The DNS Client service caches RRs from query responses that the DNS Client service receives. The information is held for a set Time-To-Live (TTL) and can be used to answer subsequent queries. By default, the cache TTL is based on the TTL value received in the DNS query response. When a query is resolved, the authoritative DNS server for the resolved domain defines the TTL for a given RR.
You can use the IPCONFIG command with the /DISPLAYDNS option to display the current resolver cache contents. The output looks like the following:
D:\2031AS>ipconfig /displaydns
Windows 2000 IP Configuration
localhost.
-------------------------------------------------
Record Name . . . . . : localhost
Record Type . . . . . : 1
Time To Live . . . . : 31523374
Data Length . . . . . : 4
Section . . . . . . . : Answer
A (Host) Record . . . : 127.0.0.1
kona.kapoho.com.
-------------------------------------------------
Record Name . . . . . : KONA.kapoho.com
Record Type . . . . . : 1
Time To Live . . . . : 2407
Data Length . . . . . : 4
Section . . . . . . . : Answer
A (Host) Record . . . : 195.152.236.200
1.0.0.127.in-addr.arpa.
-------------------------------------------------
Record Name . . . . . : 1.0.0.127.in-addr.arpa
Record Type . . . . . : 12
Time To Live . . . . : 31523373
Data Length . . . . . : 4
Section . . . . . . . : Answer
PTR Record . . . . . : localhost
Negative Caching
The DNS Client service further provides negative caching support. Negative caching occurs when an RR for a queried domain name doesn't exist or when the domain name itself doesn't exist, in which case, the lack of resolution is stored. Negative caching prevents the repetition of additional queries for RRs or domains that don't exist.
If a query is made to a DNS server and the response is negative, subsequent queries for the same domain name are answered negatively for a default time of 300 seconds. To avoid the continued negative caching of stale information, any query information negatively cached is held for a shorter period than is used for positive query responses. However, this negative caching time-out value can be changed in the registry using the following NegativeCacheTime registry value:
NegativeCacheTime
Location: HKEY_LOCAL_MACHINE \System\CurrentControlSet\Services\Dnscache\Parameters
Data type: REG_DWORD—Time, in seconds
Default value: 0x12c (300 decimal, or 5 minutes)
Valid range: 00xFFFFFFFF (the suggested value is less one day, to prevent very stale
records)
Present by default: Yes
Negative caching reduces the load on DNS servers, but should the relevant RRs become available, later queries can be issued to obtain the information.
If all DNS servers are queried and none is available, for a default of 30 seconds, succeeding name queries will fail instantly, instead of timing out. This can save time for services that query the DNS during the boot process, especially when the client is booted from the network.
Zone Transfer
To improve the resilience and performance of the DNS service, it's normal to have at least one standard secondary zone for each standard primary zone, where the secondary zone is held on another DNS server. Depending on the exact nature of the organization, multiple standard secondary zones might be appropriate. When changes are made to the primary zone, it's important that the zone information is promptly replicated to all secondary zones. The process of transferring zone information from a primary to a secondary zone is called a zone transfer.
Zone transfers usually occur automatically, in intervals defined in the zone's SOA record. Zone transfers can also be performed manually by using the DNS MMC Snap-in, which might be done if the administrator suspects the secondary zone hasn't been properly updated.
When a standard secondary zone is created on a Windows 2000 DNS server, the DNS server will transfer all RRs from the standard primary zone to the new standard secondary. The DNS server does this to obtain and replicate a full copy of all RRs for the zone. In many of the early DNS server implementations, this same method of full transfer for a zone is used also when the secondary zone requires updating to align it with the primary zone, after changes are made to the primary zone. For large zones, this can be very time-consuming and wasteful of network resources. This can be an issue because a zone transfer will be needed each time the primary zone is updated, such as when a new host is added to the domain or if the IP address for a host is changed.
After the RRs have been replicated, the server on which the new standard secondary zone resides will check with the server on which the primary zone resides at regular intervals to determine if there are any changes to the primary zone. This is determined by polling the primary zone on a regular basis, the time period being defined by the Administrator in the Zone SOA record in the standard primary zone, and checking if the zone's version number has changed. If the version number has been incremented, a zone transfer is necessary. This process is shown in the following Network Monitor trace (Capture 16-01, included in the \Captures folder on the companion CD-ROM):
1 563.890835 Router Mahimahi DNS 0x6000:Std Qry for kapoho.com. of type
SOA on class INET
addr. 10.10.2.200 10.10.1.200
2 563.890835 Mahimahi Router DNS 0x6000:Std Qry Resp. for kapoho.com.
of type SOA on class
INET addr. 10.10.1.200 10.10.2.200
3 563.890835 Router Mahimahi DNS 0x4000:Std Qry for kapoho.com.
of type Req for incrmntl
zn Xfer on class INET 10.10.2.200 10.10.1.200
4 563.890835 MahiMahi Router DNS 0x4000:Std Qry Resp. for kapoho.com.
of type SOA on class
INET addr. 10.10.1.200 10.10.2.200
In this trace, the DNS server holding the secondary zone queries the primary zone. The SOA is then returned. The secondary zone discovers a higher version number on the primary DNS server and requests a zone transfer.
For manually maintained DNS servers, this traditionally has been a key troubleshooting issue—changes are made to a primary zone, but the version number is unchanged, and thus the changes are not replicated to the secondary. With Windows 2000, changes made to the zone, either via manual update using the DNS MMC Snap-in or via dynamic registration, trigger an update to the version number, thus enabling the secondary to carry out the zone transfer at the next poll interval.
Incremental Zone Transfers
For large zones, zone transfers can consume a significant amount of bandwidth, especially when a zone transfer is carried across slow WAN links. To improve the efficiency of zone transfers, Windows 2000 implements a new method of replicating DNS zones, incremental zone transfer, which involves transferring only the changes to the zone, rather than the entire zone. This can significantly reduce the traffic needed to keep a secondary zone current. Incremental zone transfer is defined in RFC 1995.
With incremental zone transfers, the differences between the source and replicated versions of the zone are first determined. If the zones are identified as the same version—as indicated by the serial number field in the SOA RR of each zone—no transfer is made.
If the serial number for the zone at the source is greater than at the requesting secondary server, a transfer is made of only those changes to RRs for each incremental zone version. For an incremental zone-transfer query to succeed and changes to be sent, the zone's source DNS server must keep a history of incremental zone changes to use when answering these queries. Windows 2000 holds the incremental zone transfer information for each zone in a text file \Winnt\system32\dns folder whose name is based on the name of the file holding the the zone data (which was specified when the zone was defined). Thus, if the zone information for the kapoho.com zone is held in the file kapoho.com.dns, the incremental update log is held in kapoho.com.dns.log.
Directory-Integrated Zone Replication
Standard zones use the traditional zone replication mechanisms to transfer zone information. Active Directory-integrated zones, however, use AD replication to replicate updates. This provides the following three key benefits:
DNS servers become multi-master. With standard DNS zones, all updates need to be made to a single DNS server—in other words, to the server containing the primary zone. With AD integration, any DNS server can accept the updates, which provide both improved performance and scaling, as well as better fault tolerance.
AD replication is both more efficient and quicker. AD replication transfers updated-only properties, and not the entire zone, which means only the changes are transmitted across the network. Additionally, replication between sites, typically involving slower links, is highly compressed.
The administrator only needs to plan and implement a single replication topology for AD. This will also replicate DNS changes.
For organizations using AD, Active Directory-integrated zones are generally recommended. If the organization is, however, using third-party DNS servers, these servers probably won't support AD-integrated zones.
Zone Delegation
DNS is a distributed database of information designed specifically to overcome the limitations of the earlier HOSTS.TXT approach to name resolution. The key to scaling DNS to handle large name spaces/networks, such as the Internet, is the ability to delegate the administration of domains. A zone delegation occurs when the responsibility of the RRs of a sub-domain is passed from the owner of the parent domain to the owner of the sub-domain.
At the heart of the Internet are 13 root servers, named A.ROOT-SERVERS.NET through M.ROOT-SERVERS.NET. The root servers are widely distributed. The root servers hold data for all the top-level domains, such as .com, .org, and .net, as well as for geographical domains, such as .uk, and .jp. These root-name servers enable Internet hosts to have access to the complete DNS database. Below the root and top-level domains are the domains and sub-domains belonging to individual organizations. In some top-level domains, additional hierarchy levels are provided. For example, in the .uk domain, there are sub-domains co.uk for UK-based companies (for instance, psp.co.uk) and ac.uk for academic institutions (for instance, ic.ac.uk for Imperial College), and so forth.
As illustrated in Figure 16-2, delegation occurs as a cut in the DNS with responsibility for the domain below the cut to be delegated from the domain above the cut. Within the kapoho.com domain is a sub-domain jh.kapoho.com. Responsibility for the subordinate domain has been delegated to a different server.
To implement a delegation, the parent zone must have both an A RR and a Name Service (NS) record—both pointing to the new delegated domain's root. In the kapoho.com zone, illustrated in Figure 16-2, there must be an A and an NS record that point to jh.kapoho.com. The Windows 2000 server has a delegation wizard to simplify the task of implementing a delegation.
Forwarder and Slave DNS Servers
If a resolver contacts a DNS server to resolve a domain name and return relevant RRs, the contacted DNS server will first attempt to perform the lookup using its own cache. If this fails, by default the DNS server will then start to issue iterative queries to resolve the domain. This will start at the root. If the DNS server is one of several at a site connected to the outside world by slow links, this default behavior might not be desirable.
As illustrated by Figure 16-3, a forwarder is a DNS server that other DNS servers contact before attempting to perform the necessary name resolution.
In this example, when any of the DNS clients send recursive queries to DNS servers A, B, and C, they'll attempt to answer the query from locally held zones or from their local cache. If this isn't successful, instead of these servers issuing iterative queries to external DNS servers, they'll send a recursive query to DNS server D, which has a better chance of answering the query from its own cache. This arrangement will reduce the external traffic needed to resolve host queries.
If the forwarder (server D in the example) is unable to answer the queries sent by DNS Servers A, B, or C, these servers will attempt to resolve the queries themselves by issuing iterative queries, which, again, might not be desirable. A Slave server is a forwarder that will only forward queries. This forces the DNS server to use only its configured forwarders for all name-resolution activities.
Round Robin Load Balancing
Round robin is an approach for performing load balancing. It's used to share and distribute the network resource load. With round robin, the answers contained in a query, for which multiple RRs exist, are rotated each time the query is answered. Round robin is a very simple method for load balancing a client's use of Web servers and other frequently queried multi-homed computers.
For round robin to work, multiple address (A) RRs for the queried name must exist in the zone being queried. For example, suppose there were three physical Web servers servicing, with the IP addresses of 10.1.1.151, 10.1.152, and 10.1.1.153. To invoke round robin, the administrator would need to define three (A) records for (pointing to the different servers). The first query for this domain would be returned in the order 10.1.1.151, 10.1.1.152, and 10.1.1.153. The following query would return 10.1.1.152, 10.1.1.153, and 10.1.1.151, and so on. Because the client usually will take the first IP address, the first query would use the IP address 10.1.1.151, while the second would use 10.1.1.152.
Dynamic Update DNS Client
For large networks, getting all the necessary RR information into the DNS and keeping it current can be a significant task. Maintenance of host records can be a full-time job for one or more people, in some environments. To simplify the task, Windows 2000 includes support for dynamic updates to DNS, as described in RFC 2136.. Option 81 instructs the DHCP server to register a PTR RR on its behalf. Windows 2000 computers that are statically configured will register both the (A) RR and the PTR RR with the DNS server themselves.
If a Windows 2000 DHCP client talks to a lower-level DHCP server that doesn't handle Option 81, the client registers a PTR RR on its own. The Windows 2000 DNS server is capable of handling dynamic updates.
This approach (client updating the (A) record, DHCP server updating the PTR record) is taken because only the client knows which IP addresses on the host map to a given host name. The DHCP server might not be able to properly do the (A) RR registration because it has incomplete knowledge. If appropriate, the DHCP server also can be configured to register both records with the DNS.
IPv6 Support
IP version 6 (IPv6) is a new version of the Internet Protocol. Although Windows 2000 won't ship with a native IPv6 TCP/IP stack, the Windows 2000 DNS server does provide support for IPv6 by implementing several additional pieces of functionality, including the following:
AAAA RR This new record type is defined to store a host's IPv6 address. A multi-homed IPv6 host, for example, a host that has more than one IPv6 address, must have more than one AAAA record. The AAAA RR is similar to the (A) resource, using the larger IP address size. The 128-bit IPv6 address is encoded in the data portion of an AAAA RR in network byte order (high-order byte first).
AAAA query An AAAA query for a specified domain name in the Internet class returns all associated AAAA RRs in the answer section of a response. A type AAAA query doesn't perform additional section processing.
IP6.ARPA domain This domain is used to provide reverse-lookup faculties for IPv6 hosts (as the in-addr.arpa domain does for IPv4 addresses).
Similar to in-addr.arpa domain for IPv4, an IPv6 address is represented as a name in the IP6.ARPA domain by a sequence of nibbles separated by dots with the suffix ".IP6.ARPA." The sequence of nibbles is encoded in reverse order; for instance, the low-order nibble is encoded first, with the highest-order nibble last. Each nibble is represented by a hexadecimal digit. For example, the inverse-lookup domain name corresponding to the address 4321:0:1:2:3:4:567:89a:b would be b.a.9.8.7.6.5.0.4.0.0.0.3.0.0.0.2.0.0.0.1.0.0.0.0.0.- 0.0.1.2.3.4.IP6.ARPA.
Finally, to support IPv6, all existing DNS query types that perform type A additional section processing, such as NS or mail exchange (MX) query types, must support both A and AAAA records and must do any processing associated with both of these record types. This means the DNS server will add any relevant IPv4 addresses and any relevant IPv6 addresses available locally to the additional section of a response when processing any one of these queries.
With Windows 2000, there's generally very little configuration to do for a client, with respect to DNS. Generally, it's only necessary to configure the host with the IP address of a primary (and a secondary) DNS server. This can be simplified by using DHCP to assign the IP address of the DNS server(s).
Usually, DNS default client behavior is adequate. However, in certain cases, some change to the default behavior might be appropriate. The registry keys described below can be used to change how the Windows 2000 DNS client works.
Specifying a Default TTL
By default, the TTL for the (A) and PTR RR updates sent by a DNS client is 20 minutes. To increase it, you can configure the following registry value:
DefaultRegistrationTTL
Key: HKEY_LOCAL_MACHINE \SYSTEM \CurrentControlSet \Services \Tcpip
\Parameters
Value type: REG_DWORD—seconds
Default: 0x4B0 (1200 decimal, or 20 minutes)
Valid range: 00xffffffff
Present by default: No
Disabling Dynamic Updates
While the automatic updating of DNS zones by a host can be useful, in some environments this might not be desirable. The following registry key can disable dynamic DNS updates either for a Windows 2000 computer as a whole, or for just one interface on that computer.
DisableDynamicUpdate
Key: KEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services
Tcpip\Parameters
Or
HKEY_LOCAL_MACHINE \SYSTEM \CurrentControlSet \Services
Tcpip\Parameters\Interfaces\<interface>
Value type: REG_DWORD—Boolean
Valid range: 0, 1 (False, True)
Default: 0 (False; dynamic DNS enabled)
Present by default: No
DNS name resolution occurs when a resolver, operating at a host, sends a DNS server a query message containing a domain name. The query message instructs the DNS to find the name and return certain RRs. The query message contains the domain name to search for, plus a code indicating the records that should be returned.
The following Network Monitor Trace (Capture 16-01, included in the \Captures folder on the companion CD-ROM) shows the process of issuing and resolving a name query.
1 4.866998 LOCAL 3COM 884403 DNS 0x1587:Std Qry for kona.kapoho.com. of type Host
TALLGUY 10.10.2.200
+ Frame: Base frame properties
+ ETHERNET: ETYPE = 0x0800 : Protocol = IP: DOD Internet Protocol
+ IP: ID = 0xEEA8; Proto = UDP; Len: 61
+ UDP: Src Port: Unknown, (4715); Dst Port: DNS (53); Length = 41 (0x29)
DNS: 0x1587:Std Qry for kona.kapoho.com. of type Host Addr on class INET addr.
DNS: Query Identifier = 5511 (0x1587)
+
2 4.866998 3COM 884403 LOCAL DNS 0x1587:Std Qry Resp. for kona.kapoho.com. of type
10.10.2.200 TALLGUY IP
+ Frame: Base frame properties
+ ETHERNET: ETYPE = 0x0800 : Protocol = IP: DOD Internet Protocol
+ IP: ID = 0x7BAA; Proto = UDP; Len: 77
+ UDP: Src Port: DNS, (53); Dst Port: Unknown (4715); Length = 57 (0x39)
DNS: 0x1587:Std Qry Resp. for kona.kapoho.com. of type Host Addr on class INET addr.
DNS: Query Identifier = 5511 (0x1587)
+ DNS: DNS Flags = Response, OpCode - Std Qry, AA RD RA Bits Set, RCode - No error
DNS: Question Entry Count = 1 (0x1)
DNS: Answer Entry Count = 1 (0x
DNS: Answer section: kona.kapoho.com. of type Host Addr on class INET addr.
DNS: Resource Name: kona.kapoho.com.
DNS: Resource Type = Host Address
DNS: Resource Class = Internet address class
DNS: Time To Live = 1200 (0x4B0)
DNS: Resource Data Length = 4 (0x4)
DNS: IP address = 10.10.2.200
In the trace shown above, a client sends a DNS query to request the DNS server to return all A records for kona.kapoho.com. The query response contains the question entry and the answer RR(s). In this case, there's only one A record to return pointing to 10.10.2.200.
Network Monitor trace 16-2 (Capture 16-02, included in the \Captures folder on the companion CD-ROM) shows a Reverse-Lookup Query message. In this trace, the querying host tries to discover the host name for the host at 10.10.1.52. To determine this, the resolver queries for 52.1.10.10.in-addr.arpa and requests any PTR records. The DNS has the relevant PTR record, which shows the host to be kapoholt.kapoho.com.
If the resolver is attempting to perform name resolution on a name that a user provided, it won't know in advance whether the name relates to a Host (A) RR or to a CNAME. If it relates to the CNAME, the server can return the CNAME. However, in this instance, the CNAME must still be resolved. To avoid extra DNS traffic, when a DNS server returns a CNAME in response to a Host record lookup, the DNS server will also return the A record relating to the CNAME.
The following Network Monitor Trace (Capture 16-03, included in the \Captures folder on the companion CD-ROM) shows the process of issuing and resolving a canonical name.
1 6.559432 DNS Server DNS Client DNS 0x1590:Std Qry for
ns1.kapoho.com. of type Host A TALLGUY 10.10.2.200
+ Frame: Base frame properties
+ ETHERNET: ETYPE = 0x0800 : Protocol = IP: DOD Internet Protocol
+ IP: ID = 0xEFCD; Proto = UDP; Len: 60
+ UDP: Src Port: Unknown, (4761); Dst Port: DNS (53); Length = 40 (0x28)
DNS: 0x1590:Std Qry for ns1.kapoho.com. of type Host Addr on class INET addr.
DNS: Query Identifier = 5520 (0x1590)
+
2 6.569446 DNS Client DNS Server DNS 0x1590:Std Qry Resp. for
ns1.kapoho.com. of type 10.10.2.200 TALLGUY IP
+ Frame: Base frame properties
+ ETHERNET: ETYPE = 0x0800 : Protocol = IP: DOD Internet Protocol
+ IP: ID = 0x807B; Proto = UDP; Len: 95
+ UDP: Src Port: DNS, (53); Dst Port: Unknown (4761); Length = 75 (0x4B)
DNS: 0x1590:Std Qry Resp. for ns1.kapoho.com. of type Canonical name on class INET addr.
DNS: Query Identifier = 5520 (0x1590)
+ DNS: DNS Flags = Response, OpCode - Std Qry, AA RD RA Bits Set, RCode - No error
DNS: Question Entry Count = 1 (0x1)
DNS: Answer Entry Count = 2 (0x
DNS: Answer section: ns1.kapoho.com. of type Canonical name on class INET addr.(2
records present)
+ DNS: Resource Record: ns1.kapoho.com. of type Canonical name on class INET addr.
+ DNS: Resource Record: kona.kapoho.com. of type Host Addr on class INET addr.
In this trace, the DNS client sends a DNS query to the DNS server requesting the Host record for ns1.kapoho.com, which is actually an alias for kona.kapoho.com. In the DNS reply, there are two answer RRs. The first is the CNAME RR for ns1.kapoho.com, and contains the canonical name. The second answer RR is the Host record for kona.kapoho.com, which will contain the IP address of this computer.
Dynamic updating of DNS zones, described in RFC 2136, is a mechanism that enables DNS clients to add or delete RRs or sets of RRs (RRSets) to a zone. In addition, update requests can state prerequisites (specified separately from update operations), which can be tested before an update can occur. Such updates are said to be atomic, that is, all prerequisites must be satisfied for the update operation to be carried out. The Windows 2000 TCP/IP client and the DHCP server issue dynamic update requests to update the DNS with host A and PTR records.
More Info Dynamic updating of DNS zones is described in RFC 2136, which can be found in the \RFC folder on the companion CD-ROM.
The following Network Monitor Trace (Capture 16-04, included in the \Captures folder on the companion CD-ROM) shows the process of dynamically registering an (A) RR.
1 6.270000 DNS Client DNS Server DNS 0x61:Dyn Upd PRE/UPD
records to KAPOHOLT.kapoho.c 10.10.1.52 195.152.236.200
+ Frame: Base frame properties
+ ETHERNET: ETYPE = 0x0800 : Protocol = IP: DOD Internet Protocol
+ IP: ID = 0x1082; Proto = UDP; Len: 115
+ UDP: Src Port: Unknown, (3276); Dst Port: DNS (53); Length = 95 (0x5F)
DNS: 0x61:Dyn Upd PRE/UPD records to KAPOHOLT.kapoho.com. of type Canonical name
DNS: Query Identifier = 97 (0x61)
+ DNS: DNS Flags = Query,
2 6.270000 DNS Server DNS Client DNS 0x61:Dyn Upd Resp.
PRE/UPD records to KAPOHOLT.ka 195.152.236.200 10.10.1.52
+ Frame: Base frame properties
+ ETHERNET: ETYPE = 0x0800 : Protocol = IP: DOD Internet Protocol
+ IP: ID = 0x86BD; Proto = UDP; Len: 115
+ UDP: Src Port: DNS, (53); Dst Port: Unknown (3276); Length = 95 (0x5F)
DNS: 0x61:Dyn Upd Resp. PRE/UPD records to KAPOHOLT.kapoho.com. of type Canonical name
DNS: Query Identifier = 97 (0x61)
+ DNS: DNS Flags = Response,
In this trace, the dynamic update message is sent from the DNS client to the DNS server to update the (A) RR for the host kapoholt.kapoho.com, which is now at IP address 10.10.1.52.
There are three methods of performing zone transfer:
Traditional Zone Transfer This approach involves the secondary requesting a full copy of the zone from the primary.
Incremental Zone Transfer This approach, as defined in RFC 1995, requires the DNS server hosting the primary zone to keep a record of the changes that are made between each increment of the zone's sequence number. The secondary can thus request only the changes that occurred since the last time the secondary was updated.
AD Zone Transfer AD zones are replicated to all domain controllers in the Windows 2000 domain using AD replication.
More Info The Incremental Zone Transfer approach is defined in RFC 1995, and the traditional zone-transfer mechanism is defined in RFC 1034. These RFCs can be found in the \RFC folder on the companion CD-ROM.
The traditional zone-transfer mechanism, which RFC 1034 defines, can be wasteful of network resources if the change in the transferred RRs is small in relation to the overall zone. The following Network Monitor Trace (Capture 16-05, included in the \Captures folder on the companion CD-ROM) shows a zone transfer.
1 60.1765 Secondary Primary TCP ....S., len: 0, seq:3436924871-3436924871, ack
2 60.1765 Primary Secondary TCP .A..S., len: 0, seq:2396712099-2396712099, ack
3 60.1765 Secondary Primary TCP .A...., len: 0, seq:3436924872-3436924872, ack
4 60.1765 Secondary Primary DNS 0x0:Std Qry for kapoho.com. of type Req for
zn Xfer on
class INET addr.
5 60.1865 Primary Secondary DNS 0x0:Std Qry Resp. for kapoho.com. of
type SOA on class
INET addr.
6 60.1865 Primary Secondary DNS 0x636F:Rsrvd for _ of type Unknown Type on class
7 60.1865 Secondary Primary TCP .A...., len: 0, seq:3436924904-3436924904, ack
8 60.2366 Secondary Primary TCP .A...F, len: 0, seq:3436924904-3436924904, ack
9 60.2366 Primary Secondary TCP .A...., len: 0, seq:2396714217-2396714217, ack
10 60.2366 Primary Secondary TCP .A...F, len: 0, seq:2396714217-2396714217, ack
This Network Monitor trace 16-5 shows a zone transfer of the zone kapoho.com from the primary to a secondary server. In this trace, the secondary DNS server first initiates a TCP connection with the primary server and issues a zone-transfer message. The primary zone's DNS server then transfers the zone RRs. In a zone-transfer, the first and last record transferred is the SOA record. After all the records are transferred, the TCP connection is terminated.
Incremental zone transfers, described in RFC 1995, can be more efficient than traditional zone transfers for both large and dynamic zones. However, they place additional processing requirements on the DNS server, which needs to keep track of the zone differences and sends only the changed records. By default, standard zones will use incremental transfers where possible.
The following Network Monitor trace 16-6 (Capture 16-06, included in the \Captures folder on the companion CD-ROM) shows an incremental zone transfer.
1 563.890835 LOCAL 3COM 6B15C7 DNS 0x6000:Std Qry for kapoho.com. of
type SOA on class INET addr.
2 563.890835 3COM 6B15C7 LOCAL DNS 0x6000:Std Qry Resp. for
kapoho.com. of type SOA on class INET addr.
3 563.890835 LOCAL 3COM 6B15C7 DNS 0x4000:Std Qry for kapoho.com. of
type Req for incrmntl zn Xfer on class INET addr.
4 563.890835 3COM 6B15C7 LOCAL DNS 0x4000:Std Qry Resp. for
kapoho.com. of type SOA on class INET addr.
In this trace, the DNS server initiating the zone transfer first queries for the SOA record, then requests an incremental zone transfer. In this example, the reply, contained in the fourth packet, fully fits inside a single UDP datagram. Had this not been the case, the reply message would have indicated that the reply was truncated, and the requesting server would have created a TCP session to the other DNS server and requested the zone transfer via TCP.
Active Directory replication is a proprietary solution, which can be used only with Windows 2000 domain controllers. Standard and incremental zone transfers rely on the servers holding secondary zones to pull changes from the primary zone. AD replication, on the other hand, is push in nature. For zones that change little, AD replication will ensure that all DNS servers holding the zone are updated quickly, while for more dynamic zones, will tend to smooth the replication traffic. Active Directory replication is beyond the scope of this book. RR. For example, a mnemonic of A indicates that the RR stores host address information.
Record-Specific Data This is a variable-length field containing information describing the resource. This information's format varies according to the type and class of the RR.
Note: With Windows 2000, nearly all of the DNS information is either automatically added to the server or can be left to a default value. For most organizations running Windows 2000, DNS will be self-maintaining once the DNS servers are installed and the relevant zones created. However, the details on RR types can be useful for those integrating Windows 2000 with a non-Windows 2000 DNS server, or for troubleshooting.
Standard DNS zone files contain the set of RRs for that zone as a text file. In this text file, each RR is on a separate line and contains all the above data items, as a set of text fields, separated by white space. In the zone file, each RR consists of the above data items, although different records will contain slightly differently formatted record-specific data.
Sample Zone Data
The zone data for the kapoho.com zone noted earlier in this chapter is as follows:
; Database file kapoho.com.dns for kapoho.com zone.
; Zone version: 22508
;
@ IN SOA kona.kapoho.com. administrator.kapoho.com. (
22508 ; serial number
900 ; refresh
600 ; retry
86400 ; expire
3600 ) ; minimum TTL
;
; Zone NS records
; There are two DNS servers holding this domain
@ NS kona.kapoho.com.
@ NS kapoholt.kapoho.com.
;
; Zone records for Kapoho.com
;
@ 600 A 10.10.1.52
@ 600 A 10.10.2.200
@ 600 A 10.10.2.211
hilo 900 A 10.10.2.211
kapoholt A 10.10.1.52
kona A 10.10.2.200
tallguy 1200 A 10.10.1.100
1200 A 10.10.2.100
;
; Delegated sub-zone: jh.kapoho.com.
;
jh NS kapoholt.kapoho.com.
; End delegation
Zone data for AD-integrated zones are held as a series of AD objects representing this data. For more detail on how the AD holds DNS-integrated zones, see the Windows 2000 Server Help.
Where Are RRs Located?
RRs for standard zones are stored in the folder systemroot\system32\dns. The RRs for each zone are held in a separate text file, which is named after the zone with an extension of .dns; for example, kapoho.com.dns.
Active Directory-Integrated Zone RRs
RRs for AD-integrated DNS zones are stored within the AD itself. The AD uses the following two main object classes to hold this DNS information:
dnsZone Represents an AD-integrated zone that contains dnsNode objects. This object class is the AD equivalent of a Standard zone held as a text file. The dnsZone objects have a dnsProperty attribute that defines key details about the zone, such as whether this zone can be dynamically updated.
dnsNode Corresponds to the individual RRs in the zone. Each dnsNode object will have a dnsRecord attribute containing the resource information.
Windows 2000 supports all RFC-compliant RRs. Many of these aren't commonly, or ever, used. The following sections list the most commonly used RRs and contain tables that include the RR type, the syntax, and an example.
Host Address (A)
This RR contains a host address RR that maps a DNS domain name to an IPv4 32-bit address.
Type
Syntax
Owner A IPv4_address
Example
kona A 10.10.2.200
IPv6 Host Record (AAAA)
This RR contains a host address RR that maps a DNS domain name to an IPv6 128-bit address.
AAAA
Owner Class IPv6_address
ipv6host AAAA 4321:0:1:2:3:4:567:89a:b
Canonical Name (CNAME)
This RR maps an alias or alternate DNS domain name in the Owner field to a canonical or actual DNS domain name. There must also be an (A) RR for the canonical DNS domain name, which must resolve to a valid DNS domain name in the name space. The fully qualified canonical name should end with a full stop (".").
Alias_name CNAME Canonical_name
ns1 CNAME kona.kapoho.com
Mail Exchanger (MX)
The MX record provides message routing to a mail-exchanger host for any mail that's to be sent to the target domain. This RR also contains a 2-digit preference value to indicate the preferred ordering of hosts, if multiple exchanger hosts are specified. Each exchanger host specified in an MX record must have a corresponding host A address RR in the current zone.
Owner MX preference mail_exchanger_host_name
kapoho MX 10 mail.kapoho.com
Pointer (PTR)
This RR, used for Reverse Name Lookup message, points from the IP address in the Owner field to another location in the DNS name space as specified by the target_domain_name. Usually, this is used only in the in-addr.arpa domain tree to provide reverse lookups of address-to-name mappings. In most cases, each record provides information that points to another DNS domain-name location, such as a corresponding host (A) address RR in a forward-lookup zone:
Owner PTR target_domain_name
200 PTR kona.kapoho.com
Service Locator (SRV)
The SRV RR enables a computer to locate a host providing specific service, such as a Windows 2000 Active Directory Domain Controller. This enables the administrator to have multiple servers, each providing a similar TCP/IP-based service to be located using a single DNS query operation. This record is mainly used to support the Windows 2000 AD, where all relevant DNS RRs can be automatically populated into the DNS.
service.protocol.name SRV preference-weight port target
_ldap._tcp.dc._msdcs 600 SRV 0 100 389 kona.kapoho.com
600 SRV 0 100 389 kapoholt.kapoho.com
600 SRV 0 100 389 hilo.kapoho.com
DNS messages are sent between a DNS client and a DNS server or between two DNS servers. These messages are usually transmitted using User Data Protocol (UDP) with the DNS server binding to UDP port 53. In some cases, the message length, particularly for responses, might exceed the maximum size of a UDP datagram. In such cases, an initial response is sent with as much data as will fit into the UDP datagram. The DNS server will turn on a flag to indicate a truncated response. The client can then contact the server using TCP (port 53), and reissue the request—taking advantage of TCP's capability to reliably handle longer streams of data. This approach uses UDP's performance for most queries while providing a simple mechanism to handle longer queries.
DNS originally provided dynamic lookup for essentially static, manually updated data, such as host records manually added to a zone. The original DNS messages involved sending a query to a DNS server and getting a response. RFC 2165 defines the dynamic update facility, which makes use of update messages, whose format is similar to and derived from query messages. Both message types are described below.
DNS Query Message Format
All DNS query messages share a common basic format, as Figure 16-4 illustrates.
As can be seen from Figure 16-4, the DNS query message consists of a fixed-length 12-byte header, plus a variable portion holding questions and DNS RRs.
DNS Query Message Header
The DNS Message header consists of the following fields:
Transaction ID A 16-bit field used to identify a specific DNS transaction. The originator creates the transaction ID and the responder copies the transaction ID into a reply message. This enables the client to match responses received from a DNS server to the requests that were sent to the server.
Flags A 16-bit field containing various service flags, described in more detail below.
Question Count A 16-bit field indicating the number of entries in the question section of a name service packet.
Answer RR Count A 16-bit field indicating the number of entries in the answer RRs section of a DNS message.
Authority RR Count A 16-bit field indicating the number of authority RRs in the DNS message.
Additional RR Count A 16-bit field indicating the number of additional RRs in the DNS message.
The Flags field contains a number of status fields that are communicated between client and server. Figure 16-5 below displays the format of the Flags field.
The individual fields in the flags field are as follows:
Request/Response This 1-bit field is set to 0x0 to indicate a name-service request, and 0x1 to indicate a name-service response.
Operation Code This 4-bit field indicates the specific name-service operation of the name-service packet, as the following table shows:
Operation Code
Operation
0x0
Query
0x1
Inverse Query
0x2
Server Status Request
Authoritative Answer Returned in a reply to indicate whether the responder is authoritative for the domain name in the question sections.
Truncation Set to 0x1 if the total number of responses couldn't fit into the UDP datagram (for instance, if the total number exceeds 512 bytes). In this case, only the first 512 bytes of the reply are returned.
Recursion Desired Set to 0x1 to indicate a recursive query. For queries, if this bit is not set and the name server contacted isn't authoritative for the query, the DNS server will return a list of other name servers that can be contacted for the answer. This is how delegations are handled during name resolution.
Recursion Available DNS servers set this field to 0x1 to indicate that they can handle recursive queries.
Reserved These 3 bits are reserved, and set to zero.
Return Code A 4-bit field holding the return code. A value of 0x0 indicates a successful response (for instance, for name queries, this means the answer is in the reply message). A value of 0x3 indicates a name error, which is returned from an authoritative DNS server to indicate that the domain name being queried for doesn't exist.
DNS Query Question Entries
In a DNS query, the question entry contains the domain name being queried. Figure 16-6 displays the Question field layout.
The question entry is made up of the following three fields:
Question Name The domain name being queried. The format of this field is discussed later.
Question Type Indicates the records that should be returned, expressed as a 16-bit integer, as shown in the following table.
Type Value
Record(s) Returned
0x01
Host record
0x02
Name server (A) record
0x05
Alias (CNAME) record
0x0C (12)
Reverse-lookup (PTR) record
0x0F (15)
Mail exchanger (MX) record
0x21 (33)
Service (SRV) record
0xFB (251)
Incremental zone transfer (IXFR) record
0xFC (252)
Standard zone transfer (AXFR) record
0xFF (255)
All records
Question Class Normally set to 0x00-01. This represents the IN question class.
The Question Name field holds the name of the domain being queried. In DNS, these domain names are expressed as a sequence of labels. The domain kapoho.com, for example, consists of two labels (kapoho and com). In the Question Name field, the domain name has a sequence for each label, as 1-byte length fields followed by the label. The domain kapoho.com, therefore, would be expressed as 0x6kapoho0x3com0x0, where the hex digits represent the length of each label, the ASCII characters represent the individual labels, and the final hex 0 indicates the end of the name.
Resource Records (RRs)
When a DNS server sends a query reply back to a DNS host, the answer, authority, and additional information sections of the DNS message can contain RRs, which answer the question in the question section. Figure 16-7 illustrates the format of these RRs.
The fields in an RR are as follows:
RR Name The DNS domain name held as a variable-length field. The format of this field is the same as the format of the Question Name field, described in the "DNS Query Question Entries" section of this chapter.
Record Type The RR type value, as noted above.
Record Class The RR class code; there's only one record class used currently: 0x00-01, Internet Class.
TTL RR Time to live, expressed in seconds held in a 32-bit unsigned field.
Resource Data Length A 2-byte field holding the length of the resource data.
Resource Data Variable-length data corresponding to the RR type.
In DNS, domain names are expressed as a sequence of labels. The DNS name kapoho.com, for example, would consist of two labels (kapoho and com). When DNS domain names are contained in an RR, they are formatted using a length-value format. With this format, each label in a DNS message is formatted with a 1-byte-length field followed by the label. The domain kapoho.com, therefore, would be expressed as 0x06kapoho0x03com0x00, where the hex digits represent the length of each label, the ASCII characters hold the individual labels, and the final hex zero indicates the end of the name.
DNS Update Message Format
The format of a DNS Update message is very similar to DNS query messages, and many of the fields are the same. The DNS Update message contains a header defining the update operation to be performed and a set of RRs, which contain the update. Figure 16-8 displays the general format of the DNS Update message.
DNS Update Message Flags
The DNS Update message has a flag section, similar to query messages but with a slightly different format. Figure 16-9 shows the format of the Flag field section for DNS Update messages.
The DNS Update message flags are used as follows:
Request/Response A 1-bit field, set to 0x0 to indicate an update request, and 0x1 to indicate an update response.
Operation Code Set to 0x5 for DNS updates.
Return Code For update responses, indicates the result of the query. The defined result codes are shown in Table 16-3.
Table 16-3 Defined Result Return Code Flags for Update Responses
Result Code Value
Meaning
No errorupdate successful.
Format errorthe DNS server was unable to understand the update request.
The name server encountered an internal failure while processing this request.
0x3
Some name that ought to exist doesn't exist.
0x4
The operation code isn't supported.
0x5
The name server refuses to perform the operation for policy for security reasons.
0x6
Some name that ought not to exist does exist.
0x7
Some RR set that ought not to exist does exist.
0x8
Some RR set that ought to exist doesn't exist.
0x9
The server isn't authoritative for the zone named in the Zone section.
0xA
A name used in the Prerequisite or Update section is not within the zone denoted by the Zone section.
A Name Lookup message uses the DNS message format defined in RFC 1034 and described earlier in the "DNS Query Message Format" section of this chapter. Network Monitor trace 16-1 (Capture 16-01, included in the \Captures folder on the companion CD-ROM) shows an example name query. In this trace, the following fields are set:
Query Identifier Set to a unique number so that the resolver can match the response to the query
Flags Set to indicate a standard query, with recursion if necessary
Question Count Set to 1
Question Entry Set to the domain name to resolve (kona.kapoho.com) and the RR to return (the host A record)
A Name-Query Response message is sent in response to a Name Query and is sent using the same query message format as the query response. Network Monitor trace 16-1 (Capture 16-01, included in the \Captures folder on the companion CD-ROM) displays an example query response in which the following fields are set:
Query Identifier Set to the unique number set in the query, to allow the resolver to match the response to the original query
Flags Set to indicate a response and a successful lookup
Answer Count Set to 1
Question Entry Set to the question contained in the query message
Answer Entry The RR requested in the query (the host record, containing the IP address of the queried domain)
Network Monitor trace 16-3 (Capture 16-03, included in the \Captures folder on the companion CD-ROM) shows a slightly different response message. In this trace, a resolver is attempting to resolve the (A) RR for ns1.kapoho.com. There's no Host (A) RR for this name, but there's an alias (CNAME). In the response, the replying DNS server returns two RRs: the CNAME RR, as well as the A Record for the canonical name (kona.kapoho.com).
Reverse-Name Query messages use the same message format as normal queries. The only differences in the contents are as follows:
The domain name being queried is different. For a reverse lookup, the resolver will construct a domain name in the in-addr.arpa domain based on the IP address that's being queried.
The queried record will be a PTR record, rather than an (A) record.
The Reverse-Name Query Reply message is also the same as a Query Reply message, except that a PTR record, rather than a host record, is returned. A reverse lookup can be seen in Network Monitor trace 16-2 above. In the trace, the resolver is looking for the host name of the host at 10.10.1.52, and thus queries for the domain 52.1.10.10.in-addr.arpa. The Reverse-Name Query Reply returns the requested PTR record, which shows the host name at this IP address to be kapoholt.kapoho.com.
Name Update messages use the Name Update message format defined in RFC 2136 and described earlier in the "DNS Update Message Format" section of this chapter. Network Monitor trace 16-4 shows an example Name Update message. In this update, the key update message fields are set as follows:
Query Identifier Like query messages, update messages contain an identifier to enable the sender to match the response to the original update.
Flags Set to indicate a request and a dynamic update.
Update Zone Set to 1, and the zone section contains the zone to be updated.
Prerequisites Zone Set to 2, with two prerequisite records specified.
Update Zone Contains the RR that's to be updated.
A Name Update Response message is issued in response to a Name Update Request. Network Monitor trace 16-4 contains an example of this in which the response can be seen to be identical to the request, except that the DNS flags in the message header are set to indicate this is a successful response. If the response had been unsuccessful, the response message would have contained an error code.
DNS was once an option for most Windows NT networks that used WINS (NetBIOS) for most domain operations, and as the basis of file and print sharing. DNS is now a key component in Windows 2000 networks and is required in those networks that deploy Windows 2000 Active Directory. In this chapter we have examined what DNS is and how it works, including DNS message formats and how the message appears on the wire. The chapter also has shown a number of Network Monitor captures, which are also contained on the companion CD-ROM for deeper study.
Thomas Lee is an independent computer consultant who has been working with Windows NT since 1993.
Joseph Davies is a Microsoft employee and has been a technical writer and instructor of TCP/IP and networking technology topics since 1993. | http://technet.microsoft.com/en-us/library/bb726935.aspx | crawl-002 | refinedweb | 12,039 | 62.48 |
I have a cluster created in GCP with autoscaling enabled on the cluster. In my case, few pods are getting evicted from node A due to Memory Pressure and are running on new node B. But the evicted pods are not getting removed. Its still visible when I run 'kubectl get pods'. Is this an expected behavior? Do these evicted pods consume any resources or cause any other issue, if not deleted/removed?
That's perfectly normal. Seeing the pods there with the error helps you troubleshoot errors / failures. If they were auto deleted, you'd never know.
If it is not running, it is not consuming resources.
You can do something like the command below to clear them if it bothers you.
kubectl delete pod $(kubectl get pods | grep Error | awk '{print $1}')
In this case replace 'Error' with whatever state you want to clear.
- 1A one liner to delete all evicted pods across all namespaces - github.com/kubernetes/kubernetes/issues/… – Daniel t. Sep 29 '19 at 1:32 | https://serverfault.com/questions/985711/evicted-pods-not-getting-removed-from-the-cluster-when-autoscaling-is-enabled | CC-MAIN-2021-21 | refinedweb | 170 | 77.43 |
hi - Hibernate
hi hi,
what is object life cycle in hibernate
hibernate how to write join quaries using hql Hi satish...:
Thanks
Hi - Hibernate Interview Questions
Hi please send me hibernate interview
Hi - Struts
Hi Hi Friends,
Thanks to ur nice responce
I have sub package in the .java file please let me know how it comnpile in window xp please give the command to compile
hibernate web project - Hibernate
hibernate web project hi friends,very good morning,how to develop... for that,thank u in advance. Hi Friend,
Please visit the following links:
Hi... - Struts
of this installation Hi friend,
Hibernate is Object-Oriented mapping tool...Hi... Hi,
If i am using hibernet with struts then require... more information,tutorials and examples on Struts with Hibernate visit... server please tell me.
Hi friend,
For solving the problem
java - Hibernate
java HI guys can any one tell me,procedure for executing spring and hibernate in myeclipse ide,plz very urgent for me,thank's in advance. Hi Friend,
Please visit the following link: - Struts - Hibernate
Hibernate application development help Hi, Can anyone help me in developing my first Java and Hibernate application
Java programming tutorial for very beginners
Java programming tutorial for very beginners Hi,
After completing my 12th Standard in India I would like to learn Java programming language. Is there any Java programming tutorial for very beginners?
Thanks
Hi
hibernate - Hibernate
hibernate is there any tutorial using hibernate and netbeans to do a web application add,update,delete,select
Hi friend,
For hibernate tutorial visit to : (
Hi.. - Java Beginners
Hi.. Hi,
I got some error please let me know what is the error
integrity constraint (HPCLUSER.FAFORM24GJ2_FK) violated - parent key
its very urgent Hi Ragini
can u please send your complete source, - Java Beginners
Hi, Hi friends
I have some query please write the code and send me.I want adding value using javascript onChange() Events...please write the code and send me ts very.... - Java Beginners
very urgent
Hi ragini,
First time put the hard code after that check the insert query. Because your code very large. If hart code...hi.... Hi friends
i am using ur sending code but problem
Hibernate - Hibernate
one example
Hi mamatha,
Hibernate 3.0, the latest Open Source... not understandable for anybody learning Hibernate.
Hibernate provides a solution to map.../hibernate/
Thanks.
Amardeep..
Hibernate - Hibernate
a doubt in that area plz help me.That is
In Hibernate mapping file I used tag... plz help me. Hi friend,
Read for more information.
Thanks
hi roseindia - Java Beginners
hi roseindia what is java? Java is a platform independent..., Threading, collections etc.
For Further information, you can go for very good...).
Thanks/Regards,
R.Ragavendran... Hi deepthi,
Read for.... in Hibernate 4.3.1?.
Thanks
Hi,
The error "Access
Hibernate - Hibernate
Hibernate what is difference between dynamic-update and dynamic-insert? Hi friend,
It should be neccesary to have both a namespace....
Thanks
Hi.... - Java Beginners
Hi....
I hv 290 data and very large form..In one form it is not possible to save in one form so i want to break in to part....And i give...; Hi friend,
Some points to be member to solve the problem :
When
Hibernate - Hibernate
Hibernate when I run Hibernate Code Generation wizard in eclipse I'm...;Hi Friend,
Please visit the following link:
Hope that it will be helpful for you.
Thanks
Hibernate - Hibernate
Hibernate SessionFactory Can anyone please give me an example of Hibernate SessionFactory? Hi friend,package roseindia;import...;1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate
Ple help me its very urgent
Ple help me its very urgent Hi..
I have one string
1)'2,3,4'
i want do like this
'2','3','4'
ple help me very urgent
plz.If any application send me thank u (in advance). Hi friend....
For read more information:
Hi,
Hi, Hi,what is the purpose of hash table
hibernate - Hibernate
Hi Radhika,
i think, you hibernate configuration... Hibernate;
import org.hibernate.Session;
import org.hibernate.*;
import....
Hi..
Hi.. null is a keyword.True/False?
hi friend,
In Java true, false and null are not a Java keyword they are literals in Java. For reading in detail go through the following link The null keyword | http://roseindia.net/tutorialhelp/comment/4240 | CC-MAIN-2015-48 | refinedweb | 709 | 59.09 |
Visualize data with matplotlib
In this tutorial, you will learn to visualize data by using the Matplotlib library. While learning, you will perform the following tasks:
Find out which US airport had the highest ratios of delayed and cancelled flights in 2003-2016.
See how that ratios changed over time.
Highlight some general trends..
Prepare an example
If you have completed the previous tutorial, just proceed to Transform data. Otherwise, download the data set and add it to the DataSpell workspace as described in the section Add data to the workspace.
In this tutorial, we will use the "Airline Delays from 2003-2016" dataset by Priank Ravichandar licensed under CC0 1.0. This dataset contains the information on flight delays and cancellations in the US airports for the period of 2003-2016.
You should have a notebook with the following cell:
You can also download the full notebook and add it to your DataSpell workspace: ds_visualize_tutorial.ipynb
Transform data
Our first goal is to find the airport with the highest ratios of delayed and cancelled flights. For that purpose we need only the following columns:
Airport.Code
Statistics.Flights.Total(total number of flights)
Statistics.Flights.Delayed(number of delayed flights)
Statistics.Flights.Cancelled(number of cancelled flights)
Let's select the required columns from the
data DataFrame and put them into
airport_data by adding the following code to the first cell:
Note that DataSpell provides automatic completion for column headers:
This is what you'll see in the output after you run the cell by pressing Ctrl+Enter or clicking
:
Scroll the rows down. You see that each row contains data for one month in one specific airport. We need statistics for the whole period, so let's group data by airport codes and summarize the values:
Here is the full code of the cell:
... and its output:
Before we continue, let's create another code cell. Click Add Code Cell Below in the cell toolbar:
We will compare the airports by the ratios of delayed and cancelled flights. Looks like we should add some data to the DataFrame. Let's create two new columns:
Ratio Delayed.Total and
Ratio.Cancelled Total. The data in those columns will result from calculations. The variables are introduced for code readability:
Run the cell to make sure that two columns have been added to the DataFrame:
Visualize data
Let's start with visualizing our newly created
airport_data DataFrame in the form of a bar chart.
You need to add
import matplotlib.pyplot as plt to the beginning of your first code cell. Don't forget to rerun that cell after editing, for example, by clicking
or pressing Shift+Enter.
Create a bar chart
First of all, let's improve the readability of the future chart and sort the rows in
airport_databy using the sort_values method:airport_data = airport_data.sort_values(by='Ratio Delayed.Total', ascending=False)
Now assign the variables:airport_code = airport_data.index delayed = airport_data['Ratio Delayed.Total'] cancelled = airport_data['Ratio Cancelled.Total']
Note that when we created the
airport_dataDataFrame, the
Airport.Codecolumn became the index column. It means that airport codes are used as row addresses in this DataFrame, and you shouldn't specify the column name to read them.
The following code creates a figure with the specific width and height in inches, as well as a Matplotlib Axes. They will contain all the elements of the future bar chart.fig, ax = plt.subplots(figsize=(15,5))
To plot a bar chart, use the bar() method. It accepts the x and y coordinates as the first two positional arguments. The label will be used to render the chart legend.ax.bar(airport_code, delayed[airport_code], bottom=cancelled[airport_code], label='Delayed') ax.bar(airport_code, cancelled[airport_code], label='cancelled')
When plotting the first bar chart, we use an additional
bottomparameter to stack the delays bars on top of the cancellations bars.
Set the labels for axes, the chart title, and show the legend:ax.set_xlabel('Airport codes') ax.set_ylabel('Ratio') ax.set_title('Ratio of delayed and cancelled flights to total flights') ax.legend()
Finally, use
plt.show()to render the whole thing. This is the full code of the cell:# Sort DataFrame rows airport_data = airport_data.sort_values(by='Ratio Delayed.Total', ascending=False) # Assign variables airport_code = airport_data.index delayed = airport_data['Ratio Delayed.Total'] cancelled = airport_data['Ratio Cancelled.Total'] # Create a figure and set its size to 15x5 in. fig, ax = plt.subplots(figsize=(15,5)) # Plot bar charts ax.bar(airport_code, delayed[airport_code], bottom=cancelled[airport_code], label='Delayed') ax.bar(airport_code, cancelled[airport_code], label='cancelled') # Add axes labels and title ax.set_xlabel('Airport codes') ax.set_ylabel('Ratio') ax.set_title('Ratio of delayed and cancelled flights to total flights') # Show legend ax.legend() # Show plot plt.show()
And here is the result:
You can see that the highest ratio of delayed flights was in the Newark Liberty International airport (EWR). Let's continue researching the data for this particular airport. It would be interesting to find out how the number of cancelled and delayed flights changed over time.
Create a line chart
Let's start with selecting the necessary data from the dataset:ewr_data = data[data['Airport.Code']=='EWR']
This code can be translated as "select the rows from
datathat have EWR in the
Airport.Codecolumn and put them into the
ewr_dataDataFrame".
Assign the variables:date = ewr_data['Time.Label'] delayed = ewr_data['Statistics.Flights.Delayed'] cancelled = ewr_data['Statistics.Flights.Cancelled']
Again, create a figure and an Axes:fig, ax = plt.subplots(figsize=(15,5))
For line charts, use the plot() method:ax.plot(date, delayed, label='Delays') ax.plot(date, cancelled, label='Cancellations')
Add the axes labels, the title, and the legend:ax.set_xlabel('Year/Month') ax.set_ylabel('Flights (delayed/cancelled)') ax.set_title('Cancellations and delays in EWR 2003-2016') ax.legend()
Here is the full code cell for copy-pasting:# Select rows with 'EWR' in the first column ewr_data = data[data['Airport.Code']=='EWR'] # Assign variables date = ewr_data['Time.Label'] delayed = ewr_data['Statistics.Flights.Delayed'] cancelled = ewr_data['Statistics.Flights.Cancelled'] #() # Show plot plt.show()
And the output:
There are too many ticks on the x-axis. To show only every 12th of them, put the following line before
plt.show():ax.set_xticks(date[::12])
It looks better now:
As you can see, the number of cancellations didn't change much over time. But there is a clearly visible fall in the number of delayed flights somewhere in the end of 2009. Did they hire a new manager? Or maybe that's somehow connected with the total number of flights? Let's check!
Show more data
We will add another line chart with the total number of flights. But that numbers are far greater than delays. The solution is to add another Axes that will share the same x-axis but have its own y-axis. That can be done by using the twinx() method:total = ewr_data['Statistics.Flights.Total'] ax2=ax.twinx() ax2.plot(date, total, '--', color='g', label='Total flights') ax2.set_ylabel('Flights (total)') ax2.legend(loc='upper center')
Note the third positional argument of the
plot()method. Dashes will result in a dashed line. The color is also customizable. We also specified the location of the legend, so that it doesn't interfere with another one.
The full code:# Select rows with 'EWR' in the first column ewr_data = data[data['Airport.Code']=='EWR'] # Assign variables date = ewr_data['Time.Label'] delayed = ewr_data['Statistics.Flights.Delayed'] cancelled = ewr_data['Statistics.Flights.Cancelled'] total = ewr_data['Statistics.Flights.Total'] #() # Decrease the density of ticks on x-axis ax.set_xticks(date[::12]) # Plot another chart with extra y-axis ax2=ax.twinx() ax2.plot(date, total, '--', color='g', label='Total flights') ax2.set_ylabel('Flights (total)') # Add legend in center ax2.legend(loc='upper center') # Show plot plt.show()
And the chart:
So, there is no magic. The overall number of flights decreased significantly in the middle of 2008, which naturally resulted in fewer delays.
Keep researching
What happened in 2008? Did the number of flights decrease only in EWR? Let's find out by analyzing the whole dataset.
Now we are interested only in dates and numbers. Let's just group the rows of the
data DataFrame by the time label in YYYY/MM format, and then summarize the values. There will be invalid values in some columns (like
Time.Month and
Time.Year), but we won't use them. All the rest is similar to the previous tutorial steps:
And yes, there was a drop in total flights in all US airports:
Speaking about drops, do you see that periodic negative peaks on the chart? Seems like they repeat every year. Let's build a chart to see how did the total number of flights change throughout the year.
This time we will group the data by month name. The
sort_values(by='Time.Month') part is needed to range the months in chronological order:
Definitely, February is the low season for the US civil aviation:
Summary
You have completed the matplotlib visualization tutorial. Here's what you have done:
Selected necessary data and transformed it
Built bar charts and line charts
Discovered statistical trends | https://www.jetbrains.com/help/dataspell/visualize-data-with-matplotlib.html | CC-MAIN-2022-40 | refinedweb | 1,524 | 52.05 |
May 31, 2013 03:35 AM|OzgurAkin|LINK
I need to create a web service used by a government project. I am using vb.net 2010. The procedure should be like this:
function sendfile(byval reqdoc as DocumentRequest) as DocumentResponce
The type DocumentRequest should be like
public class DocumentRequest
public docType as DocumentType
end class
public Class DocumentType
Public FileName As String
Public Hash As String
Public BinaryData() As Byte
end class
Document Response is simple
Public Class DocumentResponse
Public Hash As String
Public Msg As String
End Class
I can do this using datacontract and datamember attributes. But to be able to use MTOM, I have searched internet and find that I should use messagecontract instead of datacontract. I should define messagebody as byte array and other field at messageheader. I can not define such a declaration. Even skipping middle documentrequest type and using directly document type in the function I can not use the resulted web service in other programs. Can I define such a function with WCF? With WSE 3.0 it was easy, But I can not use WSE 3.0 becouse it is obselete and IE 7.0 can not work with wse 3.0. What can I do?
May 31, 2013 05:28 PM|Illeris|LINK
Check this :
It shows you how to enable MTOM for asmx webservice.
For WCF :
Jun 01, 2013 07:21 AM|OzgurAkin|LINK
doing with asmx is easy. But we can not use wse 3.0 with IE 7.0. I need to solve the problem with WCF. I need to send a struct to the function sendfile. The example you send is a basic one, and the parameter of function is a simple stream.
Jun 03, 2013 08:24 AM|Illeris|LINK
You can use the FileResponse principle for input arguments also...
Jun 03, 2013 08:54 AM|OzgurAkin|LINK
I have tryed:
<OperationContract()>
Function sendDocument(ByVal request As DocumentType) As DocumentResponse
<MessageContract()>
Public Class DocumentType
<MessageHeader()>
Public FileName as string
<MessageHeader()>
Public Hash As String
<MessageBodyMember()>
Public BinaryData() As Byte
End Class
<MessageContract()>
Public Class DocumentResponse
<MessageHeader()>
Public Hash As String
<MessageHeader()>
Public Msg As String
End Class
When I start that and try to use from a test client, I can not see DocumentType as a type. If I manually code the type and use in th sendfile function, IDE gives an error that the procedure waits for a simple byte arrary as argument. Also, I could not find a way to constract the necessary top level struct.
I should use in the function parameter RequestType defined like
<MessageContract()>
Public Class RequestType
Public doc As DocumentType
End Class
But it is not working. There are to few examples on MTOM with WCF. I could not find any other document saying that MTOM is only avaible through MessageContract. Even MessageContract section of framework 4.0 help file does not mention anything about MTOM.
4 replies
Last post Jun 03, 2013 08:54 AM by OzgurAkin | https://forums.asp.net/t/1910732.aspx?WCF+MTOM+message+contract+creation | CC-MAIN-2018-26 | refinedweb | 498 | 64 |
I ran some IA-32 test suites last week that uncovered a bunch of issues in the IA-32 emulation layer that I wanted to report here. a) semctl doesn't check for bad cmd --- sys_ia32.c Wed Jun 5 15:39:54 2002 +++ sys_ia32.c.new Thu Dec 19 17:27:50 2002 @@ -2166,6 +2166,9 @@ else fourth.__pad = (void *)A(pad); switch (third) { + default: + err = -EINVAL; + break; case IPC_INFO: case IPC_RMID: case IPC_SET: b) getdents64 - the system call succeeds, but glibc sets EOVERFLOW. We may want to think about getting rid of "struct linux32_dirent" at some point. History from glibc sources: /* The getdents64 syscall was introduced in 2.4.0-test7. We test for 2.4.1 for the earliest version we know the syscall is available. */ #if __LINUX_KERNEL_VERSION >= 132097 # define __ASSUME_GETDENTS64_SYSCALL 1 #endif c) readv and iov_len Single UNIX spec says that readv should return: [EINVAL] The sum of the iov_len values in the iov array overflowed an ssize_t. The following (untested) patch should fix it. There may be a case for moving this check into userland. --- linux/fs/read_write.c Mon Dec 16 01:06:56 2002 +++ linux/fs/read_write.c.new Thu Dec 19 16:41:33 2002 @@ -26,6 +26,7 @@ #include <linux/uio.h> #include <linux/smp_lock.h> #include <linux/dnotify.h> +#include <linux/personality.h> #include <asm/uaccess.h> @@ -268,7 +269,10 @@ FIXME: put in a proper limits.h for each platform */ #if BITS_PER_LONG==64 - if (tot_len > 0x7FFFFFFFFFFFFFFFUL) + if ((current->personality & PER_LINUX32) + && (tot_len > 0x7FFFFFFFUL)) + goto out; + else if (tot_len > 0x7FFFFFFFFFFFFFFFUL) #else if (tot_len > 0x7FFFFFFFUL) #endif d) msgctl(id, IPC_STAT, &buf) does't behave as expected This seems to be related to linux/ipc.h: #if defined(__ia64__) || defined(__hppa__) /* On IA-64 and PA-RISC, we always use the "64-bit version" of the IPC structures. */ # define ipc_parse_version(cmd) IPC_64 #else int ipc_parse_version (int *cmd); #endif However, sys_ia32.c:msgctl32 does a version check against IPC_64 to figure out whether to use struct msqid_ds or msqid64_ds. I think it should always be using msqid64_ds, given the above comment. -ArunReceived on Thu Dec 26 13:27:33 2002
This archive was generated by hypermail 2.1.8 : 2005-08-02 09:20:11 EST | http://www.gelato.unsw.edu.au/archives/linux-ia64/0212/4428.html | CC-MAIN-2020-16 | refinedweb | 373 | 67.96 |
I have an existing Win2K domain with a solitary domain controller.
For reasons I won't go into, we need to migrate all "important" company data
onto onsite and offsite storage, and the solution decided upon is a pair of
Win2003 R2 Storage Server boxes. The sites are connected with a 100Mbps
fiberoptic line.
The intent is to have one storage server act as the "primary" repository fpr
company data, backup files, etc, and the second merely act as an offsite
mirror for disaster recovery.
Because the sites are connected with what amounts to a LAN, the initial
intent was to use DFS replication on the servers, mirror the directory
structures accordingly, and let the OS deal with all the offsite storage
issues, replication, etc. etc. The applications that use the biggest chunk of
data will need to point to the primary server, and if it suffers a
catastrophic failure we could live with manually pointing the client software
at the secondary server. So we don't feel compelled to set up a namespace and
the additional server-based functions it requires. At least not right now.
The ultimate goal basically is pictured in the online DFS help file (the
replication group image).
My questions:
The "DFS Replication Requirements" section of online help indicates that we
must run adprep.exe /forestprep from one of the Win2003 R2 CDs. Because there
isn't a specific illustration of doing this in the context of a Win2K domain,
am I going to be okay doing this? Does it make a difference running it from
the storage server box versus directly on the domain controller?
There is a relatively large volume of data (well, what we used to think was
a large volume of data) in the range of 100 GB that will eventually be
migrated to the Storage Servers and DFS folders. Is it best to move the files
to the primary server and let it replicate to the secondary? Or manually copy
to both to start?
What happens when the domain controller is rebooted / off / crashes?
Eventually we want to move off of the Win2K domain and onto a Win 2003 R2
domain structure. How much more painful will having DFS in place make this
migration? In other words, would it be seriously worth my while to do the
Win2K to Win2003 migration first? (Having done this before, I am not
relishing the idea. Our business need is to get the storage issues handled
first).
Thanks in advance for all the helpful advice.
--
GG Smith | http://fixunix.com/storage/206656-storage-server-s-dfs-replication-win2k-domain-print.html | CC-MAIN-2016-18 | refinedweb | 423 | 61.46 |
I have some entities added on datastore - made a little web app (in Python) to read and write from the datastore through endpoints. I am able to use the webapp through endpoints from javascript.
I want to access the web app from an installed application on PC. Is there a way to access endpoints from installed applications written in Python? How?
Is there any other way to access the datastore from PC installed applications written in Python?
That's one of the beauties of AppEngine's endpoints. You should use the Python Client Library for Google's APIs to communicate with your endpoints
pip install --upgrade google-api-python-client
Then you'll construct a resource object to communicate with your api using the apiclient.discovery.build function. For eg:
from apiclient.discovery import build api_root = 'https://<APP_ID>.appspot.com/_ah/api' api = 'api_name' version = 'api_version' discovery_url = '%s/discovery/v1/apis/%s/%s/rest' % (api_root, api, version) service = build(api, version, discoveryServiceUrl=discovery_url)
You can then perform operations at
service.<endpoint_method> etc
A more complete example with authentication can be found here.
EDIT:
Or as @Zig recommends, directly use the Google Cloud API
pip install googledatastore | https://codedump.io/share/6ChP3Ei4Aeww/1/how-to-access-google-datastore-from-an-installed-application-on-pc-written-in-python | CC-MAIN-2017-34 | refinedweb | 196 | 56.96 |
This is a follow up to the Lists 1 and Lists 2 problems.
When last we left you, our intrepid hero, you had created the following updated list of bird abundances across sites:
number_of_birds = [28, 32, 1, 0, 10, 22, 30, 19, 145, 27, 36, 25, 9, 38, 21, 12, 122, 87, 36, 3, 0, 5, 55, 62, 98, 32, 90, 33, 14, 39, 56, 81, 29, 38, 1, 0, 143, 37, 98, 77, 92, 83, 34, 98, 40, 45, 51, 17, 22, 37, 48, 38, 91, 73, 54, 46, 102, 273, 60, 10, 11, 27, 24, 16, 9, 23, 39, 102, 0, 14, 3, 9, 93, 64]
For your research on bird counts you need to not only know what many birds are at a single site, but also how many birds occur on groups of sites.
Use slices to answer the following questions:
1. What is the total number of birds for 5 sites starting at site 10?
2. What is the total number of birds at the last 6 sites? Have Python figure out what the last six sites are, don’t just type in their positions.
You’re going to be doing a lot of this sort of analysis, so it’s probably better to have a function that does it for you rather than doing the slicing yourself each time. Cut and paste the following function into your code:
def n_site_count(bird_counts, start_site, number_of_sites): """Count the total number of birds at a given number of sites starting at a given start site.""" start_site = start_site - 1 #convert start site to Python index sub_sites = bird_counts[start_site:start_site + number_of_sites] number_of_birds = sum(sub_sites) return number_of_birds
Use the function to calculate and return the total count of all birds for the n sites starting at the start site. For example, if there are 5 sites and number_of_birds_list = [5, 5, 10, 10, 8], then if starting_site = 2 and number_of_sites = 3 then the function should return the value 25 (5 + 10 + 10). Use the data on the number of birds given in the list above (just copy and paste it into your code) to answer the following questions.
3. What is the total number of birds for 5 sites starting at site 10?
4. What is the total number of birds for 7 sites starting at site 1?
5. What is the total number of birds for 1 site starting at site 23?
6. Think about what the funtion should do if asked for the total number of birds for 10 sites starting at site 70 (Note: there are only 74 sites). Print out a sentence that explains what it actually does. | http://www.programmingforbiologists.org/exercises/Lists-3/ | CC-MAIN-2019-09 | refinedweb | 440 | 77.81 |
interface - simple compile time interface checking for OO Perl
package Foo; use interface 'Iterator', 'Generator', 'Clonable', 'DBI::DBD';
Compile-time interface compliance testing. Inspects the methods defined in your module, and compares them against the methods defined in the modules you list. Requires no special or additional syntax.
Should you fail to implement any method contained in any of the listed classes, compile will abort with an error message.
Methods starting with an underscore are ignored, and assumed not to be part of the interface.
The modules listed on the
use interface line will be added to your
@ISA array. This isn't done to re-use code from them - interface definitions should be empty code stubs, or perhaps a reference implementation. It is done so that your module asses the
->isa() test for the name of the package that you're implementing the interface of. This tells Perl that your module may be used in place of the modules you implement the interface of.
Sample interface definition:
package TestInterface; sub foo { } sub bar { } sub baz { } 1;
A package claiming to implement the interface "TestInterface" would need to define the methods
foo(),
bar(), and
baz().
An "interface" may need some explaination. It's an Object Orientation idea, also known as polymorphism, that says that you should be able to use interchangeable objects interchangably. Thank heavens the OO people came and showed us the light!
The flip side of polymorphism is type safety. In Perl,
->isa() lets you check to make sure something is derived from a base class. The logic goes that if its derived from a base class, and we're looking for an object that fills the need of the base class, then the subclass will work just as well, and we can accept it. Extending objects is done by subclassing base classes and passing off the subclasses as versions of the original.
While this OO rote might almost have you convinced that the world works this way, this turns out to be almostly completely useless. In the real world, there are only a few reasons that one object is used in place of another: Someone wrote some really horrible code, and you want to swap out their object with a better version of the same thing. You're switching to an object that does the same thing but in a different way, for example using a database store instead of a flat file store. You're making some minor changes to an existing object and you want to be able to extend the base class in other directions in the future. Only in the last case is inherited code with subclassing even useful. In fact, there is a move towards using composition (has-a) instead of inheritance (is-a) across the whole industry, mainly because they got tired of people pointing out that OO sucks because inheritance only serves to make a great big mess of otherwise clean code.
Seperating the interface from the implementation lets you make multiple implementations of an idea. They can share code with each other, but they don't have to. The programmer has assured us that their module does what is required by stating that it implements the interface. While this isn't proof that the code works, climaing to implement an interface is a kind of contract. The programmer knows what work is required of him and she has agreed to deliver on it.
The interface definition can be a package full of stub methods that don't do anything, or it could be an actual working implementation of an object you're striving for compatability with. The first case is cleanist, and the package full of stubs serves as good documentation. The second case can be handy in cases where the first case wasn't done but someone ignored the Wisdom of the Interface and wrote a package anyway.
The Wisdom of the Interface says to write an interface for each new kind of object that could have multiple implementations. The interfaces serves as a contract for the minimum features needed to implement an object of that type. When working with objects - creating them, checking types when you accept them, etc - always work with the interface type, never the type of an individual implementation. This keeps your code generic.
In order to do the composition thing (has-a), you contain one or more objects that you need to do your work, you implement an interface that dispatches method calls to those objects. Perhaps your new() method creates those objects and stores them in instance variables.
None. EXPORT is silly. You stay in your namespace, I'll stay in mine.
Failing to implement a required method will generate a fatal similar to the following:
Baz is missing methods: bar from Stub, and import from your, and import from ImplicitThis at interface.pm line 47. BEGIN failed--compilation aborted at Baz.pm line 5.
Hear the one about the insomniac dyslexic agnostic? He stayed up all night wondering if there was a Dog.
See for more on Perl OO, including information about how and why to use interfaces.
Damian Conway. Speaking of Damian, this is a cheap knockoff of his Class::Contract module. However, we have no special syntax!
Speaking of speaking of Damian Conway, if you ever get a chance to see him talk, you should go.
NEXT.pm, by Damian Conway.
Object::Lexical, also by myself.
protocol.pm, by James Smith, also on CPAN
0.01: Initial release. 0.02: Stephen Nelson submitted a typo report. Thanks! Mention of protocol.pm by James Smith An object is now considered to implemenant an interface if it ->can() do something, not just if it has a method. Hacked on docs a bit. 0.03: Doing an "eval $caller;" in our import() doesn't get perl to finish loading the module that called us. Somewhere before 5.8.8, this seems to have stopped working. So we use CHECK { } now like we should have always.
Yes.
This will very likely break highly introspective code, for example, anything Damian Conway might write.
Does not work with packages not stored in a file where "use" can find them. This bug applies to programs run from "perl -e" and in subpackages burried in other packages. Code in the "main" package cannot use this module for this reason.
Does not work when AUTOLOAD is used to dispatch method calls. Modules that use AUTOLOAD cannot be used as an interface definition, and modules that use AUTOLOAD cannot be tested to comply with an interface definition.
It should be an error to use two different interfaces that both declare a method of the same name, as it would be ambigious which you are intending to implement. I haven't decided. Perhaps I'll just make this warning.
This module was done in pragma-style without permission. I'm interested on feedback on how to handle this.
Another arrangement worth considering is to create a Class::Interface thing that the interface uses, not your code. When you use that interface, the code is awaken, and import() inspects your code without exporting anything. This would just move the logic around. Interfaces would be marked interfaces rather than the people who use the interfaces making them as interfaces. Once again, thoughts and suggestions encouraged.
The code is frightening.
There are spelling and grammar errors in this POD documentation.
My Wiki is really slow because my computer is slow, doesn't have much memory, and its 4000 lines of code. I need to trim that down. I think I could do it in about 400 lines. Update: TinyWiki is borne. TinyWiki is no more than 100 lines, now by definition. It is fast enough.
Scott Walters, SWALTERS, Root of all Evil, <scott@slowass.net>
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. If you don't believe in free software, just remember that free software programmers are gnome-like. I wouldn't want to be visited by gnomes. | http://search.cpan.org/~swalters/interface-0.03/interface.pm | CC-MAIN-2017-39 | refinedweb | 1,348 | 65.01 |
To see how it all works, we need an example that not only demonstrates how the Java language works to let you create classes and objects, but something that demonstrates why you might go to the trouble of using it.
Consider for the moment that you need to perform some complicated calculations. You could just write a set of functions, one for each calculation, but in many cases it would be better to group them together so that they could be used as properties and methods of an object.
For example, suppose you needed to work with circles drawn on a graphic display. Then it makes sense to create a class that encapsulate all of the things you might want to do with a circle.
Start a new project called MathExample.
Add a new class called Circle.
The basic properties of a circle are its position x,y and its radius r - so let's add these as properties to the Circle class:
public class Circle{ public double x; public double y; public double r;
They are public and so accessible from outside of the class.
The data type double is a double precision number.
We also need to use the value of the constant Pi and there is no reason why we should make this available to the outside world so it can be private:
private double Pi=3.14159;
As well as storing the size and position of the circle it would be useful to have the ability to discover the circumference and so we add a public circumference method:
public double circumference(){ return 2*Pi*r; }
In the same way it would be nice to discover the area of the circle - so lets add an area method. But to do this we need to compute r squared. Let's add a private squared function that simply returns the square of any number:
private double square(double a) { return a * a; }
You could argue that square was sufficiently useful to make public but in the spirit of hiding how the calculations are performed we can also chose to make it private.
Finally the area function is:
public double area() { return Pi * square(r); }
The complete list for the class is:
public class Circle { public double x; public double y; public double r; private double Pi = 3.14159; public double circumference() { return 2 * Pi * r; } private double square(double a) { return a * a; } public double area() { return Pi * square(r); }}
public class Circle { public double x; public double y; public double r; private double Pi = 3.14159;
public double circumference() { return 2 * Pi * r; }
private double square(double a) { return a * a; }
public double area() { return Pi * square(r); }}
Now let's write a main function that makes use of the class:
public static void main(String[] args) { Circle circle = new Circle(); circle.r = 10.5; circle.x = 0; circle.y = 0; double circ = circle.circumference(); double area = circle.area(); System.out.println(circ); System.out.println(area); }
This starts off by creating a circle object from the class.
Notice that we have the problem of finding a suitable name for the class and the object - they can't both be called Circle.
This is a standard problem of class based object oriented languages and there are many ways around it. One is to always start a class name with an uppercase letter and use lowercase for objects.
So in our example the class is Circle and the object is circle - remember Java is case sensitive. In practice this name problem isn't as big in real life programming as it is in examples because you generally have more specific names ready to use for instances of a class - bigcircle, bluecircle, offsetcircle and so on.
After creating the circle object we set its radius and position and then use its methods to get the circumference and area which are displayed in the output window.
Notice you can create any number of circles now you have the Circle class and each one is independent of the others and will compute its own area and circumference.
This is just one of the reasons object-oriented programming is a good idea - there are many more more sophisticated reasons for using it.
Before ending this chapter, I should add that our example doesn't do things in the best possible way.
There are better ways to do things. For example, instead of using public variables as properties it is better to use methods to acces private variables. That is instead of letting users of the class directly access x,y an r we would introduce accessor functions like getX and setX. This is so standard in Java that giving direct access to member variables is almost never encountered. However when you are learning Java you need to know how things actually work. We will return to get and set methods later.
There's still a lot to learn about classes and objects, including constructors, inheritance and more.
These ideas are the subject of later | https://www.i-programmer.info/ebooks/134-modern-java/4569-java-working-with-class.html?start=3 | CC-MAIN-2019-35 | refinedweb | 841 | 57.81 |
Subject: Re: [OMPI users] File seeking with shared filepointer issues
From: pascal.deveze_at_[hidden]
Date: 2011-06-27 09:20:36().
Pascal
users-bounces_at_[hidden] a écrit sur 25/06/2011 12:54:32 :
> De : Jeff Squyres <jsquyres_at_[hidden]>
> A : Open MPI Users <users_at_[hidden]>
> Date : 25/06/2011 12:55
> Objet : Re: [OMPI users] File seeking with shared filepointer issues
> Envoyé par : users-bounces_at_[hidden]
>
> I'm not super-familiar with the IO portions of MPI, but I think that
> you might be running afoul of the definition of "collective."
> "Collective," in MPI terms, does *not* mean "synchronize." It just
> means that all functions must invoke it, potentially with the same
> (or similar) parameters.
>
> Hence, I think you're seeing cases where MPI processes are showing
> correct values, but only because the updates have not completed in
> the background. Using a barrier is forcing those updates to
> complete before you query for the file position.
>
> ...although, as I type that out, that seems weird. A barrier should
> not (be guaranteed to) force the completion of collectives (file-
> based or otherwise). That could be a side-effect of linear message
> passing behind the scenes, but that seems like a weird interface.
>
> Rob -- can you comment on this, perchance? Is this a bug in ROMIO,
> or if not, how is one supposed to use this interface can get
> consistent answers in all MPI processes?
>
>
> On Jun 23, 2011, at 10:04 AM, Christian Anonymous wrote:
>
> > I'm having some issues with MPI_File_seek_shared. Consider the
> following small test C++ program
> >
> >
> > #include <iostream>
> > #include <mpi.h>
> >
> >
> > #define PATH "simdata.bin"
> >
> > using namespace std;
> >
> > int ThisTask;
> >
> > int main(int argc, char *argv[])
> > {
> > MPI_Init(&argc,&argv); /* Initialize MPI */
> > MPI_Comm_rank(MPI_COMM_WORLD,&ThisTask);
> >
> > MPI_File fh;
> > int success;
> > MPI_File_open(MPI_COMM_WORLD,(char *)
> PATH,MPI_MODE_RDONLY,MPI_INFO_NULL,&fh);
> >
> > if(success != MPI_SUCCESS){ //Successfull open?
> > char err[256];
> > int err_length, err_class;
> >
> > MPI_Error_class(success,&err_class);
> > MPI_Error_string(err_class,err,&err_length);
> > cout << "Task " << ThisTask << ": " << err << endl;
> > MPI_Error_string(success,err,&err_length);
> > cout << "Task " << ThisTask << ": " << err << endl;
> >
> > MPI_Abort(MPI_COMM_WORLD,success);
> > }
> >
> >
> > /* START SEEK TEST */
> > MPI_Offset cur_filepos, eof_filepos;
> >
> > MPI_File_get_position_shared(fh,&cur_filepos);
> >
> > //MPI_Barrier(MPI_COMM_WORLD);
> > MPI_File_seek_shared(fh,0,MPI_SEEK_END); /* Seek is collective */
> >
> > MPI_File_get_position_shared(fh,&eof_filepos);
> >
> > //MPI_Barrier(MPI_COMM_WORLD);
> > MPI_File_seek_shared(fh,0,MPI_SEEK_SET);
> >
> > cout << "Task " << ThisTask << " reports a filesize of " <<
> eof_filepos << "-" << cur_filepos << "=" << eof_filepos-cur_filepos <<
endl;
> > /* END SEEK TEST */
> >
> > /* Finalizing */
> > MPI_File_close(&fh);
> > MPI_Finalize();
> > return 0;
> > }
> >
> > Note the comments before each MPI_Barrier. When the program is run
> by mpirun -np N (N strictly greater than 1), task 0 reports the
> correct filesize, while every other process reports either 0, minus
> the filesize or the correct filesize. Uncommenting the MPI_Barrier
> makes each process report the correct filesize. Is this working as
> intended? Since MPI_File_seek_shared is a collective, blocking
> function each process have to synchronise at the return point of the
> function, but not when the function is called. It seems that the use
> of MPI_File_seek_shared without an MPI_Barrier call first is very
> dangerous, or am I missing something?
> >
> > _______________________________________________________________
> > Care2 makes it easy for everyone to live a healthy, green
> lifestyle and impact the causes you care about most. Over 12
Millionmembers!
> Feed a child by searching the web! Learn how
>
> > users mailing list
> > users_at_[hidden]
> >
> >
>
>
> --
> Jeff Squyres
> jsquyres_at_[hidden]
> For corporate legal information go to:
>
>
>
> _______________________________________________
> users mailing list
> users_at_[hidden]
> | http://www.open-mpi.org/community/lists/users/2011/06/16770.php | CC-MAIN-2014-42 | refinedweb | 535 | 53.81 |
Test::Warnings - Test for warnings and the lack of them
version 0.026, you'll have discovered that these two features do not play well together, as the test count will be calculated before the warnings test is run, resulting in a TAP error. (See
examples/test_nowarnings.pl in this distribution for a demonstration.)
This module is intended to be used as a drop-in replacement for Test::NoWarnings: it also adds an extra test, but runs this test before
done_testing calculates the test count, rather than after. It does this by hooking into
done_testing as well as via an
END block. You can declare a plan, or not, and things will still Just Work.
It is actually equivalent to:
use Test::NoWarnings 1.04 ':early';
as warnings are still printed normally as they occur. You are safe, and enthusiastically encouraged, to perform a global search-replace of the above with
use Test::Warnings; whether or not your tests have a plan.
It can also be used as a replacement for.
You can use this construct as a replacement for Test::Warn::warnings_are:
is_deeply( [ warnings { ... } ], [ 'warning message 1', 'warning message 2', ], 'got expected warnings', );
or, to replace Test::Warn::warnings_like:
cmp_deeply( [ warnings { ... } ], bag( # ordering of messages doesn't matter re(qr/warning message 1/), re(qr/warning message 2/), ), 'got expected warnings (in any order)', );
Warnings generated by this code block are NOT propagated further. However, since they are returned from this function with their filename and line numbers intact, you can re-issue them yourself immediately after calling
warnings(...), if desired.
Note that
use Test::Warnings 'warnings' will give you a
warnings subroutine in your namespace (most likely
main, if you're writing a test), so you (or things you load) can't subsequently do
warnings->import -- it will result in the error: "Not enough arguments for Test::Warnings::warnings at ..., near "warnings->import"". To work around this, either use the fully-qualified form (
Test::warnings) or make your calls to the
warnings package first._warnings test via
END (see examples/warning_like.t). Instead, write this:
like( warning { ... }, qr/foo/, 'foo appears in the warning' );
allow_warnings(qr/.../)- allow some warnings and not others
done_testing.
the need for special warning testing
Bugs may be submitted through the RT bug tracker (or bug-Test-Warnings@rt.cpan.org).
There is also a mailing list available for users of this distribution, at.
There is also an irc channel available for users of this distribution, at irc://irc.perl.org/#perl-qa.
I am also usually active on irc, as 'ether' at
irc.perl.org.
Karen Etheridge <ether@cpan.org>
A. Sinan Unur <nanis@cpan.org>
This software is copyright (c) 2013 by Karen Etheridge.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. | http://search.cpan.org/dist/Test-Warnings/lib/Test/Warnings.pm | CC-MAIN-2016-36 | refinedweb | 476 | 64.61 |
A customer wanted to know if "there was a way to hide the properties of a shortcut."
We asked for an explanation of the problem they were trying to solve, so we could understand what their question meant. The customer liaison explained:
The customer is insisting on this, even though I think it's really the wrong approach. They want to put a password into the parameters of a shortcut, but they don't want their employees to see the password when they right-click the shortcut and select Properties. We're trying to convince them of better ways of doing this, but right now they want to see if they can solve it by marking the field as "hidden" somehow.
If the password is anywhere in the shortcut file, the employees can dig it out. After all, the shell needs to dig it out, and since the shell runs with the user's privileges, in order for the shell to see it, the user must be able to see it. In other words, you can't hide anything in a shortcut because the user can just open the shortcut in Notepad and see all your "hidden" data. Or they can go to Task Manager and ask to see the command line. Or they can connect a debugger to Explorer and set a breakpoint on the
CreateProcess function.
It's like saying, "I want my employees to be able to bake cakes, but I don't want them to have access to an oven. To block access to the oven, I put a combination lock on the oven controls. On the other hand, I want to write a cake recipe that lets the employees bake cakes in the oven. Therefore, the recipe says Step 5: Go to the oven and press 1234. But now the employee can just read the recipe and find out the combination to the oven! Is there a way I can write a cake recipe that lets them bake a cake without revealing the oven combination?"
The recipe executes with the privileges of the employee. If you want the employee to be able to bake a cake by following the recipe, then they need to be able to perform the steps in the recipe, and that means being able to go to the oven and press 1234.
The oven analogy does provide some ideas on how you can solve the problem. For example, if you simply don't want employees to be able to email the oven combination to their friends with the subject line Here's the combination to the oven!, then change the way access to the oven is managed. Instead of putting a combination lock on the oven, put an employee ID card scanner on the oven that enables the oven controls if the employee has oven privileges.
For the original problem, this means changing your database so that instead of using a single password to control access and trusting each client to use it wisely, it uses the security identity of the client to control access. (I'm assuming that the password on the command line is a database password.)
On the other hand, if your goal is to prevent employees from using the oven to do anything other than bake at 350°F for one hour, you can change the employee ID card scanner so that it checks the employee for cake-baking privileges, and if so, sets the oven to bake for 350°F for one hour and locks the controls (except perhaps for a cancel button). If you have multiple recipes—say, cakes and cookies—the ID card scanner checks which recipes the employees are allowed to use and lets them choose which preset they want to activate.
For the original problem, this means changing your database so that the user identity selects which operations are permitted on the database. Some users have permission to see only records for active clients, whereas others have permission to see all records, and still others have modify permission.
If your goal is to prevent employees from doing anything other than baking cakes according to this specific recipe, then you need to move even more actions "behind the counter", because you have no way of knowing that "that pan full of batter" was created according to your walnut cake recipe, or whether it's some unauthorized recipe with extra cinnamon. If you don't trust your employees to follow recipes, then you need to take the recipe out of their hands. The instructions are now Step 1: Order a walnut cake from the cafeteria.
For the original problem, this means changing your database so that instead of letting the employee access records directly, the employee submits the action to the database ("change client 23 address to 123 Main Street"), and the database verifies that the employee has "change a client address" permission, and if so, performs the record update.
Of course, if you want to ignore all the security guidance and "just hide the password in the shortcut file, why won't you answer my question?", you can just put the password somewhere other than the shortcut file. You could, say, have the shortcut run a batch file, and the batch file has the password.
This sounds very complicated. I'll just give them admin privileges. Right after looking at this attachment the nice Russian lady sent me. Yes.
That's amazing! I've got the same combination on my luggage!
The analysis is all well and good, no disagreement there. But there actually is a half-way, not-completely-awful option for the customer: have the program use a single encrypted/signed parameter (encoded as base64) that incorporates the password and any other options for the execution of the program. Then the data in the shortcut can be used by the user only to run the program in exactly the way intended.
Of course, the user can still hack the program itself to retrieve the private key/decryption algorithm and decode the shortcut. But that's going to be true in any scenario where the password is both stored and used under the user's credentials (e.g. in a separate file).
One possible fix to that problem would be to implement security-critical components as a service instead of in the executable the user runs. The encrypted parameter block is passed to the service which the user has no access to at all, not even to view the binaries. Then the service performs whatever action is needed on the user's behalf.
None of this is meant to suggest that these ideas are better than simply putting the sensitive resource itself behind an identity-protected layer and requiring user credentials. IMHO that's the best solution. But there are acceptable alternatives for scenarios where that's not possible/practical for some reason.
Only MS has the exclusive right to create shortcuts whose target says: notused (e.g. Metro style app shortcuts) or a greyed out target field (e.g. advertised shortcuts).
Of course, if this were Unix, the "shortcut" (script) could just use setuid to get the password from a file the logged on user doesn't have access to.
"The target is grayed out for any namespace extension." But at least it shows the target there instead of saying "notused" and the shortcut is launchable from anywhere, not just explorer.exe shell:::{4234d49b-0245-4df3-b780-3893943456e1}.
The obvious solution is to put a decoy password in the shortcut but embed the real password using LsaStorePrivateData. Logging in with the decoy password trips an alarm.
Let me get this straight, the customer is jumping through all of these hoops so they can avoid using proper permissions/security groups on the database?
The use of the password to access a database is an assumption by Raymond. All that's known for certain is that the password is passed a a command line parameter to a program.
@Raymond: obviously any Windows feature xpclient doesn't understand is some kind of evil conspiracy against the common developer. It can't simply be a Windows feature xpclient doesn't understand.
[And then do what with it? Run the database program directly? But then the database program would run as the setuid user. -Raymond]
That's exactly what a lot of UNIX developers would do. It turns out that X message passing is slightly more secure than Windows message passing (you can still fake it out pretty good but things like EM_GETSEL for overwriting memory in the target process don't exist).
I suspect xpclient is looking at a Windows Installer COM shortcut, whereby the text shown in the "Target" field comes from some MSI property (I forget which) and so can say pretty much anything it wants as the actual shortcut is resolved via the Windows Installer service.
And no, nothing exclusive to Microsoft about those either.
I don't think that you always want to grant access based on the user ID: it may make sense to do it based on the tool that the person is using.
Taking a real life example, there was a company with two applications. App 1 was the stock control system. App 2 (mine) had read-only access to the stock control system to look up product codes, but it stored all its information in its own database. Both apps used SQL authentication, i.e. one username/password per application. Shortly after App 2 was installed, they found a problem in their stock control database (missing/incorrect data) and they immediately blamed me for it. I was able to clear myself, because a) my app didn't make any changes, and b) even if I'd got drunk and written the wrong commands, my app didn't have permission to make any changes. However, if both apps had used the end user's credentials then I wouldn't have had that safety net/excuse.
The best workaround I've come up with is pete.d's method, which is similar to the way that websites usually work: the database can have a single set of credentials (used by the ASP.NET code), then each person who logs into the website can have their own separate credentials (stored elsewhere). However, it seems a bit unwieldy. Is there a "best practice" approach to this?
@jader3rd: I have seen many highly intelligent folk jump through all kind of hoops to avoid doing what specialists know is the correct/better way of doing things. It seems like they get their mind set on one solution then put blinders on and won’t really consider any other path to a solution. It doesn’t seem to matter what kind of problem it is either. If there is hardware to fix a problem, they will say “hardware is expensive, fix it in the software” then spend more $$ on a software solution than the hardware would have cost, then complain that it doesn’ work as well as they would like. Or, as in this case, there is a perfectly good way to do things in software, but it isn’t the way they think it should be done so they aren’t satisfied. OK, rant over. :)
This doesn't seem any different from the standard Unix guidance not to put any potentially compromising information in the arguments passed to a program because command lines can be seen by any user (using "top", for example). There comes a point where you have to roll with the system, not fight it, and security is one of those points for me.
@AndyCadley: The implementation of MSI shortcuts are exclusive to MS since it has its own datablock in the .lnk with some encoded text (EXP_DARWIN_LINK) You can not invent your own custom data block (And even you could, Windows would not know that it should gray out things)
Actually my first thought was that they were trying to start a RunAs-variant that accepts a password on the command line to do some admin job for the user or start a program the users need that cannot cope with non-admin privileges. Sometimes I would have found this handy myself…
@James Schend
He's just inflating his post count the only way he knows how. There's not much point reading his messages generally and even less point replying. If he *actually* cared about the issues he complains about then he wouldn't be airing the issues in the comments section of a blog belonging to someone who has no control over the features in question.
Just use the file name as password. Putting the password right in front of the user. The user shouldn't have guessed it. [/sarcasm]
Nope I am looking at a shortcut to any Metro style app that says notused in the target, hides the actual target: and can't be launched from anywhere except the "Applications" namespace extension in Windows 8. Or even for MSI advertised shortcuts, you need a tool like this:…/determine-the-target-path-of-windows-installer-shortcuts to see the target, which is masked and greyed out.
@Marcel: I sometimes port little application without UI as service, so I can change the account it's running on (such as to poll data to local Access database), and place a little shortcut on desktop to tell user to run it when they need it. (The application is written as part of DR plan, so normally it won't be run as the cold standby database server won't be running)
In that case, Raymond's tips on how to allow non-admin user start a service is helpful and inspiring.
Man, I'd be willing to pay a buck 'o five for an oven that could bake a range of cakes with just the swipe of a card. And it'd be the *right* way to do things too! (The boss' grandmother can keep her recipes secret)
Diego's comment misses out that SETUID can't apply here, but it is indeed reminiscent of it.
When working on that problem, I have noticed that it's possible on Windows to have an executable file that can be executed but not read (like say, a program with a password in resources). However that doesn't prevent a determined user from debugging the program once it's running.
As for the SETUID problem itself, the root of it seems to be that on Windows you can't log a user on without that user's credentials, unlike Unix where the superuser can do that.
@Medinoc It's possible for privileged processes to impersonate, so that they can access local resources in another user's security context, without knowing their password. (Vista makes this really easy via Task Manager.) I have some vague recollection that things worked differently on a domain controller though.
Did I even say the word "evil"? My point is it masks information from the user which should be shown.
@xpclient Maybe next time you don't understand something, first think, then search and then maybe annoy us all with some conspiracy theories? Obviously that would at least halve your post count, but winning a bumper sticker for your 10.000th misguided complaint isn't the goal here or is it?
@James Schend, Kemp and voo, three clueless morons and counting who haven't the faintest idea of what's the discussion is about between Raymond and me. There's no question of "not understanding" and "evil conspiracy". The point is MS hides the target of certain shortcuts and provides no way for end users to resolve them.
I'm with xp.client on his previous post. Its cheap to bash him without a clue about the subject of discussion. As it turned out, he was right with the "notused" thing and others was wrong by their purely theoretical assumptions about this topic.
@Medinoc: It turns out it is possible to log on without a password if you don't want network resources.
continues to be confused by "xpclient" and "xp.client". Are you two the same person?
So, what exactly is wrong with the batch file attempt? You can give rights to execute and deny rights to read the batch file, can't you?
Sven2: It's impossible to execute a batch file that you can't read because it's executed by first reading the file.
@Maurits, yes sorry about that. Depends on which Live ID I sign in first to check my email. :) | https://blogs.msdn.microsoft.com/oldnewthing/20120426-00/?p=7773/ | CC-MAIN-2016-40 | refinedweb | 2,768 | 68.2 |
Welcome Bob. Sublime Text doesn't have this baked in, but the magic is in how easy it is to extend its features via plugins. This one's especially easy to do via some regex's:
Make a folder under your Data/Packages folder, call it "Straight Quotes"
Create a file in there called "Straight Quotes.py" and paste in the following:[code]import sublime, sublime_plugin
class StraightQuotesCommand(sublime_plugin.TextCommand): def run(self, edit): for rgn in self.view.find_all("“”]"): self.view.replace(edit, rgn, "\"") for rgn in self.view.find_all("‘’]"): self.view.replace(edit, rgn, "\'")[/code]
{
"id": "edit",
"children":
{"id": "wrap"},
{ "command": "straight_quotes" }
]
}
]
You could also easily bind it to a keyboard shortcut, or add it to the command palette if you wish
Wow, I'm surprised there isn't a package already for for this. I just made my own. This forum thread really saved me! Thank you so much!!
Greetings. This looks very handy indeed for some of the copy/paste Word documents I have to work with. I am running into a slight glitch in that I followed the instructions exactly and the Straight Quotes option shows up in my Edit menu when I have text loaded but the Straight Quotes menu item is grayed out and thus not clickable.
As this is my first added plugin, does it have to be initialized or the like before it can be used? I've been reading up on plugins for ST and that doesn't seem to be the case so I'm a little lost with getting off the ground working with plugins. Suggestions welcomed.
I am using ST on Ubuntu 13.10 and it otherwise works great so I believe it is installed correctly. And I tried the same, installing it on my iMac (running the new Mavericks OS) with the same results; i.e., Straight Quotes appears in the Edit menu but is grayed out.
Thank you for sharing the code.
Samantha
If it's greyed out it can't find the command, which probably means you've put the .py file in a subdirectory of your User (./Packages/User) folder, and not a direct subdirectory of ./Packages. For some reason though, sublime-menu files are picked up from subdirectories of User. Weird I know.
So, you need the two files either in a direct subdirectory of ./Packages, or in the Packages/User folder, but not in a subdirectory of Packages/User.
So on Linux, the directory will be directly under ~/.config/sublime-text-?/Packagesor you can dump the files into ~/.config/sublime-text-?/Packages/User (with no subdirectory)where ? is 2 or 3
@MKANET, thanks for the thanks
I've been using this new menu option regularly. I noticed that there is one more issue when copying scripts from a web browser. The minus symbol is also incompatible. So, the below lines of code:
$ints = @( 1, 2, 3, 4, 5)
for ($i=0; $i -le $ints.Length – 1; $i++)
{Write-Host $ints$i]}
...will cause this kind of an error:At Z:\Desktop\dev\temp.ps1:3 char:34+ for ($i=0; $i -le $ints.Length – 1; $i++)
Could someone please kindly tell me how to enhance the Staighten Quotes code so that it automatically replaces
–
with
-
I think after I add this fix, I'll rename this menu option to "WebCode Normalize"
Anyone? I'm guessing anyone who knows python would know this. Unfortunately, I dont.
Add the following lines to the plugin above:
for rgn in self.view.find_all("–"):
self.view.replace(edit, rgn, "-")
Untested, but surely you get the gist? Find this, replace that.
Thank you. I now know how to add more things to replace!
Could you also please tell me how to rename the plugin and menu command to: "Web Code Normalize"? I already tried renaming, but every time I did it the menu item would be greyed out/disabled.
Thank again, you're very helpful!
I tried adding the custom plugin described above to ST3 but ran into the same problem as zambucca. I am no programmer but I did a little Googling and got it to work. The code for main.sublime-menu remains the same, but here's the new code for Straight Quotes.py.
Paste into Straight Quotes.py:
import sublime
import sublime_plugin
class StraightQuotesCommand(sublime_plugin.TextCommand):
def run(self, edit):
for rgn in self.view.find_all("“”]"):
self.view.replace(edit, rgn, "\"")
for rgn in self.view.find_all("‘’]"):
self.view.replace(edit, rgn, "\'")
(The difference between the ST2 and ST3 versions is the import syntax.)
I am running Mac OS Mavericks and saved the Straight Quotes directory (with the two files inside) to /Users/*[username]*/Library/Application Support/Sublime Text 3/Packages/
That seems strange. I'm no Python programmer, but the Python 3 docs say that
import sublime, sublime_plugin
is exactly the same as
import sublime
import sublime_plugin
See docs.python.org/3/reference/sim ... tml#import:
I'm trying to get this customization to also replace all occurrences of the following string:"
with"
I tried adding the below code to the script; however, I'm not sure how to tell it to search for the entire string between the two quotes (instead of each character in between the quotes). Thanks very much in advance!
for rgn in self.view.find_all("""):
self.view.replace(edit, rgn, "\"") | https://forum.sublimetext.com/t/straighten-quotes-option/11722/9 | CC-MAIN-2017-43 | refinedweb | 894 | 66.33 |
Chapter 1 is a lot of review for my second-year students. The new bit is relativistic momentum, and the revelation that our definition of momentum from last year was really just a special-case limit.
One of my themes for the year is 'pulling back the veils' on all of those more complicated bits that we approximated and hand-waved away last year. I want this to be a major selling point of the course. Unfortunately, as presented, I think that the momentum definition isn't accessible or real to the kids. We can't really discover it, and it's just an abstraction at first.
I wrote a VPython program to give this some context. You can run it twice for the students - in each case, a 60 g block is pushed from rest by a constant 1 million Newton force. The momentum and velocity of the block are graphed as time goes on.
Here's where another pillar of the course is going to come in to play: fundamental laws of the universe. Really, we didn't deal with too many last year, at least not on a really visceral and important level. Here, though, the universal speed limit becomes important. Look at the v graph pass right by it without blinking, when the program uses the classical definition of p (and finds v from there):
That's a problem. The problem's with our model, though: momentum just doesn't really equal mass times velocity. Uncomment the gamma definition in the program to use the real relationship now:
Here's a great way to distinguish which is the fundamental principle here: the momentum principle still holds just fine, even in the relativistic case, but our definition of v (as determined from the momentum) was broken. With the relativistic relationship, the velocity approaches the universal speed limit. Two days in and kids not only know a fundamental law of the universe, but they know how it really does fit in with what they knew about momentum and what the missing piece in their model was.
Script:
from __future__ import division, print_function from visual import * from visual.graph import * scene.background = color.white scene.height = 50 scene.width = 50 scene.x = scene.y =0 ## Josh Gates 2012, started with kernel of Ruth Chabay program print (""" Click anywhere in display window to start. Click to stop. Momentum and velocity are shown as .6 kg block is pushed with a constant 1,000,000 N force. Uncomment gamma line to remove classical p def'n/assumption""") ## CONSTANTS delta_t = 0.01 ## for 100 steps mblock = 0.06 c=3e8 Fnet = vector(1e6,0,0) ## OBJECTS & INITIAL VALUES pblock = mblock*vector(0,0,0) gamma = 1 # start time at 0 t = 0 scene.center = (0,.1,0) # move camera up scene.range = 0.15 ## GRAPH STUFF gp = gdisplay(background=color.white, foreground=color.black, y=0, x=250, height=300, title='Momentum vs. time: block with constant F', xtitle='Time (s)', ytitle='Position (m)', ymax=3e7,xmax=30) blockp = gcurve(color=color.magenta) blockp.plot(pos=(t,pblock.x)) ## initial pos.x of block gv = gdisplay(background=color.white, foreground=color.black, y=300, x=250, height=300, title='Velocity vs. time: block with constant F', xtitle='Time (s)', ytitle='Velocity (m/s)', ymax = 3e8, ymin=0, xmax=30) blockv = gcurve(color=color.blue) blockv.plot(pos=(t,pblock.x/(gamma*mblock))) #initial velocity asymptote=gcurve(color=color.red) scene.mouse.getclick() stopper='go' a=.1 while a<1000: asymptote.plot(pos=(30/a,3e8)) a=a+1 ## CALCULATIONS while stopper=='go': rate(500) pblock = pblock + Fnet*delta_t # comment to make classical approximation #gamma = (1-(pblock.x)**2/(mblock**2 * c**2+(pblock.x)**2))**-.5 # update time t = t + delta_t # plot pos.x, velocity.x of block blockp.plot(pos=(t,pblock.x)) blockv.plot(pos=(t,pblock.x/(gamma*mblock))) ## print t, block.y if scene.mouse.clicked: stopper='stop'
I love the idea of showing the difference beteween relativistic and non-rel momentum using a VPython program. This really gets to some big ideas that we want students to see about computational thinking—that they use the program to explore the behavior of physical laws in situations they couldn't possibly recreate, and that a few small changes to the laws underlying a program can produce wildy different responses. I also think this would hit home the idea of the non-rel approximation of momentum being a good approxiamation at low speed much more nicely than just a handfull of well chosen calculations. It'd be easy for students to add a plot showing how big the difference is as the speed increases. | http://tatnallsbg.blogspot.com/2012/07/m-and-i-chapter-1-relativistic-vs.html | CC-MAIN-2017-34 | refinedweb | 784 | 57.77 |
What are Map Data Structures?
The Map interface maps unique keys to values. The key is an object we use to retrieve a value.The Dictionary class defined a data structure for mapping keys to values. It was most useful when we wanted to access data with a specific key instead of an integer index. It’s an obsolete class now and the Map interface is used to obtain key/value storage features.
How & Why use Map Data Structures?
- Store the value of a key in a Map object, to be retrieved later with it’s key.
- When no items are found in the Map, several methods throw a NoSuchElementException.
- ClassCastException is thrown when an object is incompatible with the map elements.
- If null is not allowed in the map and we attempt to use a null object, a NullPointerException is thrown.
- If we try to change a unmodifiable map, an UnsupportedOoperationException is thrown.
Code sample to show map functionality with HashMap class:
import java.util.*;
public class MapDemo {
public static void main(String[] args) {
Map map1 = new HashMap();
map1.put("Monica", "5");
map1.put("Walter", "8");
map1.put("Isaac","7");
map1.put("Leola","3");
System.out.println();
System.out.println(" Map Elements ");
System.out.print("t" + map1);
}
}
Code Output:
Map Elements
{Walter=8, Isaac=7, Leola=3, Monica=5}
You must log in to post a comment. | https://monigarr.com/2014/08/28/map-data-structure-tutorial/ | CC-MAIN-2021-17 | refinedweb | 228 | 60.11 |
Overview
Atlassian Sourcetree is a free Git and Mercurial client for Windows.
Atlassian Sourcetree is a free Git and Mercurial client for Mac.
OpenPyxl is a Python library to read/write Excel 2007 xlsx/xlsm files.
It was born from lack of existing library to read/write natively from Python the new Open Office XML format.
All kudos to the PHPExcel team as openpyxl is a Python port of PHPExcel
== User List == Official user list can be found on
== Contribute == Any help will be greatly appreciated, there are just a few requirements to get your code checked in the public repository: * Mercurial bundles are the preferred way of contributing code, compared to diffs written in a text file. Forks are encouraged, but don't forget to make a pull request if you want your code to be included :) * long diffs posted in the body of a tracker request will not be looked at (more than 30 rows of non-syntax highlighted code is simply unreadable). Please attach your bundle files to the issue instead. * every non-trivial change must come with at least a unit test (that tests the new behavior, obviously :p). There are plenty of examples in the /test directory if you lack know-how or inspiration.
== Easy Install == Releases are also packaged on PyPi, so all you have to type to get the latest version is:
$ easy_install openpyxl
== Features ==
- ** Supported data types **
- String (shared, Inline not currently supported)
- Integer
- Float
- Date
- ** Supported Excel features **
- Names ranges
- Number formats (built-in and custom formats)
- ** Handy features **
- Implicit conversion between Python types and Excel types:
- Dates
- Floats
- Percentages
- Optimized modes to read and write extremely large files
== Python 3.x support ==
Openpyxl supports python (even if some tests can fail on 2.4) from 2.4 to 3.2.
== Full documentation== With tutorial, examples, API documentation:
== Quick Examples ==
=== Write a workbook ===
#!python from openpyxl.workbook import Workbook from openpyxl.writer.excel import ExcelWriter
from openpyxl.cell import get_column_letter
wb = Workbook()
dest_filename = r'empty_book.xlsx'
ws = wb.worksheets[0]
ws.title = "range names"
- for col_idx in xrange(1, 40):
-
col = get_column_letter(col_idx) for row in xrange(1, 600):ws.cell('%s%s'%(col, row)).value = '%s%s' % (col, row)
ws = wb.create_sheet()
ws.title = 'Pi'
ws.cell('F5').value = 3.14
wb.save(filename = dest_filename)
=== Read an existing workbook ===
#!python from openpyxl.reader.excel import load_workbook
wb = load_workbook(filename = r'empty_book.xlsx')
sheet_ranges = wb.get_sheet_by_name(name = 'range names')
print sheet_ranges.cell('D18').value # D18
=== Number Formats ===
#!python import datetime from openpyxl.workbook import Workbook
wb = Workbook() ws = wb.worksheets[0]
# set date using a Python datetime ws.cell('A1').value = datetime.datetime(2010, 7, 21)
print ws.cell('A1').style.number_format.format_code # returns 'yyyy-mm-dd'
# set percentage using a string followed by the percent sign ws.cell('B1').value = '3.14%'
print ws.cell('B1').value # returns 0.031400000000000004
print ws.cell('B1').style.number_format.format_code # returns '0%' | https://bitbucket.org/agronholm/openpyxl | CC-MAIN-2017-47 | refinedweb | 489 | 51.75 |
The content of this page has not been vetted since shifting away from MediaWiki. If you’d like to help, check out the how to help guide!
These are a set of plugins that are used to work with data in the frame direction. The F_Project plugin projects the images in the frame direction into a lower dimension using different methods. The F_Profiler pulgin plots the contents of an ROI through the frame direction. The Frame_Slider provides sliders to step though the frames of a hyperstacks based on the variable/values in the slice labels.
F_Project
When run as a plugin from the gui the image used is identified on the top line. A subset of the slices and frames can be used as the source data; see syntax for Make Substacks…. When the identified frames is ‘label’, the frames are grouped by identical labels. When the frames are identified by ‘repeats var’, where var is the name of the variable in the slice label, these frames are treated as repeats of data.
Transpose? Swap frames for slices. (Π si-n)n
GeoMean Geometric Mean - prescaled product (Π si-n)
SumSq Sum of Squares
Magnitude Pythagoras
LinReg Linear least squares regression - frames returned m, b, r2
TheilSen Theil Sen linear regression with Center estimator - frames m, b
Theilsen2 Theil Sen quadratic regression with with Center estimator - a,b,c
Centroid Centroid).
TreeMap<String,Double> getVars(ImagePlus imp, int f)
Extract variable/value pairs from frame’s slice label.
TreeMap<String,TreeMap<Double,Double>> getVars(ImagePlus imp)
Extract variable/values from all frames’ slice labels.
LinkedHashMap<String,String> overRepeats(ImagePlus imp, String var)
Determine the subsets (keys) that exist and the associated comma separated frames (values), where var is the repeater.
see ‘repeats var’
TreeMap<Double,String> sortFramesByLabel(ImagePlus imp)
returns comma separated list of frames for each unique label.
void removeVarFromLabels(ImagePlus imp, String var)
Remove superfluous variable var from all slice labels
void replaceVarValWithInLabel(ImagePlus imp, String var, String val)
Replace all the values for var with val in all the slice labels.
int findVarInLabel(ImagePlus imp, String var)
Determines position of var in the slice label variables. -1 not found or error.
TreeMap<Double,String> sortFramesByLabel(ImagePlus imp, String var)
Determine frames (values - comma separated) that corrosponds to each var values (keys).
ImagePlus extractFramesByVar(ImagePlus imp, String var, double val)
Extract all frames that have the variable / value pair var/val.
TreeMap<Double,ImagePlus> extractFramesByVar(ImagePlus imp, String var)
Extract the frames (as an ImagePlus) that corresponds to each value (key) for slice label
ImagePlus sortFramesByVar(ImagePlus imp, String var)
Rearrange frame order to that of increasing var values.
double center(double[] a)
weighted mean weighted to the median
double[] theilsen(double[] ... _x)
theilsen regressor for linear.
can be called as x[],y[] or xy[][] but only the first pair computed
double[] theilsen2(double[] ... _x)
theilsen regressor for quadradic.
can be called as x[],y[] or xy[][] but only the first pair computed
double[] linreg(double[] x, double[] y)
linear least squares regressor
can be called as x[],y[] or xy[][] but only the first pair computed
double centroid(double[] x, double[] y)
Centroid
public interface Compute { public double[] compute(double[] x, double[] y); return (x == null) ? new double[NV] : process(x,y); } ImagePlus compute(ImagePlus imp, Compute fp) ImagePlus compute(ImagePlus imp, String slices, String frames, Compute fp) ImagePlus compute(ImagePlus imp, Compute fp, ImagePlus mask) ImagePlus compute(ImagePlus imp, String slices, String frames, Compute fp, ImagePlus mask)
ImagePlus[] split(ImagePlus imp)
fit and compute have
ImagePlus[] method(..., ImagePlus[] imps);
imps is syntactic sugar. Nota bene: Works even when there is only one slice in the Z direction.
Uses
ASL - MRI);
ADC - MRI
/*);
Arbitrary proccessing
IJ.run(mask,"Convert to Mask", "method=Huang background=Default calculate"); ImagePlus[] pimp = F_Project.compute(imp, new F_Project.Compute() { @Override public double[] compute(double[] x, double[] y) { if (x == null) return new double[10] return nonlinearFit(x,y); } }, mask, new ImagePlus[0]);
F_Profilier
Given a Hyperstack image, draw an ROI and start plugin. Manipulate the ROI and the plot changes. Check out Interactive_Fitting plugin.
Frame_Slider
When you have one or more Hyperstacks open and want to step though the images per the variables in the slice labels, start the Frame_Slider with the dataset with the most variables, select the other datasets, and step through them using the sliders. The datasets should all be governed by the same set of variables, i.e., The two left images are the raw data with repeats and the two right images are the mean and SNR projections, to see why click the scrollbars.
Install
Unzip Frames.zip into ImageJ 1.x plugins File › Show Folder › Plugins or plugins/jars directories. Source code in jar file.
ChangeLog
- 1 April 2018 - Initial Version.
- 1 April 2019 - Updated. | https://imagej.net/plugins/frames | CC-MAIN-2022-05 | refinedweb | 799 | 55.03 |
Data frames are one of R’s distinguishing features. Exposing a list of lists as an array of cases, they make many formal operations such as regression or optimization easy to represent.
The R data.frame operation for lists is quite slow, in large part because it exposes a vast amount of functionality. This sample shows one way to write a much faster data.frame creator in C++ if one is willing to forego that generality.
#include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] List CheapDataFrameBuilder(List a) { List returned_frame = clone(a); GenericVector sample_row = returned_frame(0); StringVector row_names(sample_row.length()); for (int i = 0; i < sample_row.length(); ++i) { char name[5]; sprintf(&(name[0]), "%d", i); row_names(i) = name; } returned_frame.attr("row.names") = row_names; StringVector col_names(returned_frame.length()); for (int j = 0; j < returned_frame.length(); ++j) { char name[6]; sprintf(&(name[0]), "X.%d", j); col_names(j) = name; } returned_frame.attr("names") = col_names; returned_frame.attr("class") = "data.frame"; return returned_frame; }
Here is the result of comparing the native function to this version.
library(rbenchmark) a <- replicate(250, 1:100, simplify=FALSE) res <- benchmark(as.data.frame(a), CheapDataFrameBuilder(a), order="relative", replications=500) res[,1:4]
test replications elapsed relative 2 CheapDataFrameBuilder(a) 500 0.104 1.0 1 as.data.frame(a) 500 16.730 160.9
There are some subtleties in this code:
— It turns out that one can’t send super-large data frames to it because of possible buffer overflows. I’ve never seen that problem when I’ve written Rcpp functions which exchanged SEXPs with R, but this one uses Rcpp:export in order to use sourceCpp.
— Notice the invocation of clone() in the first line of the code. If you don’t do that, you wind up side-effecting the parameter, which is not what most people would... | http://www.r-bloggers.com/quick-conversion-of-a-list-of-lists-into-a-data-frame/ | CC-MAIN-2014-42 | refinedweb | 303 | 60.72 |
Allocating array (list) algorithm permutations in python
So i'm having trouble to solve the following problem:
given an array size, lets say for the ease of the question size =20
it is filled with zeros as follows arr = [0]*20 ==> [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
we have couple of constant sample sizes, such as 4,3,2
SampleA=4, SampleB=3, SampleC= 2
i need to have the permutations/variations of how to allocate the list.
i can put each sample in different place/index
for example, sampleA= 4 i can put it in indexes of 0:3, or 1:4... 15:19.. (as you can see, there are quite a lot of possibilities)
the thing gets complicated once it get more crowded, for example:
3+2+3 +4
[0, x, x, x, 0, 0, x x, 0, x, x, x, 0, 0, 0, 0, x, x,x, x]
what i basically need, is to find all the possibilities to allocate samples,
i get a dictionary: key = sample size of indexes, and the value=many times it repeats.
for the upper example: {3:2,2:1,4:1}
and i would like the function to return a list of indexes !=0
for this example: [0, x, x, x, 0, 0, x x, 0, x, x, x, 0, 0, 0, 0, x, x,x, x]
the function will return: list_ind = [0,5,6,9,13,14,15,16]
1 answer
- answered 2018-07-12 09:58 Danny Kaminski
so i asked a colleague to help, and we came into a solution:
i put an example of: 4:2, 3:1, 2:1
or verbally:
two times 4, one time 3, one time 2 the code below:
*if someone can optimize, will be great
size_of_wagon = 20 dct = {4:2,3:1,2:1} l = [item for sublist in [[k] * v for (k, v) in dct.items()] for item in sublist] def gen_func(lstOfSamples, length, shift): try: # print(f'lstOfSamples={lstOfSamples}') sample = lstOfSamples[0] # Take first sample for i in range(length - sample): for x in gen_func(lstOfSamples[1:], length - (sample + i), shift + sample + i): yield [(shift + i, sample)] + x except: yield [] g = list(gen_func(l, size_of_wagon, 0)) for i in g: print(i) print(len); }
- From 4 given arrays(not sorted), find the elements from each array whose sum is equal to some number X
Suppose there are 4 unsorted arrays as given below:
A = [0, 100, -100, 50, 200] B = [30, 100, 20, 0] C = [0, 20, -1, 80] D = [50, 0, -200, 1]
Suppose X is 0, so the few of the possible O/P should be (pick 1 element from each array which satisfy condition):
0,0,0,0 -100, 100, 0, 0 -100, 30, 20,50
I was able to devise the algorithm which can do this in O(n^3LogN), is there any better way to achieve the same?
My Solution:
1- Sort each array.
2- Fixed the element from array A.
3- run three loops for the rest of the arrays and take the sum of each element:
if sum > 0 (return -1, no such elements exit) if sum == 0 (return current elements) if sum < 0 (then advance the pointer from the array for which the current element is minimum.)
Any suggestion over this?
- I thought "NlogN" is "N" times "logN", but why is it described as "double PLUS an amount proportional to N"
- Transform python `cycle` to `list`
Is there a way to transform
cyclefrom itertools into
list? Applying
list(my_cycle)freezes my computer.
I would like to periodically switch between a collection of objects infinitely. They are stored in a cycle. If one of my objects become 'inactive' I would like to delete it from cycle. I solved it with another list with inactive objects but it looks like bad workaround.
- Find n permutations of a list of length p python
So I have an array of about 40 items and need to find n permutations of the list. I know I can use itertools.permutations but that would give me all 40! different orderings which would take longer.
Is there a way I can create exactly n permutations of the list?
- Number of permutation with repetition in Python?
is there a function to calculate the number of permutations with repetition in Python? I know with itertools I can generate them but I want only a faster way to do the calculation and avoid calculating the factorials, I'm not interested in generating all possible permutations.
Example: calculate the possible strings composed by 4 As, 3 Bs, 5 Cs.
res= 12!/(4!3!5!)
or in code:
from math import factorial from functools import reduce rep=[4,3,5] result= factorial(sum(rep))//reduce(lambda x,y: x*y, map(factorial, rep)) | http://quabr.com/51299478/allocating-array-list-algorithm-permutations-in-python | CC-MAIN-2018-39 | refinedweb | 814 | 59.67 |
Available items
The developer of this repository has not created any items for sale yet. Need a bug fixed? Help with integration? A different license? Create a request here:
Vertigo allows you to treat raw bytes like a normal Clojure data structure. This allows for faster reads and reduced memory footprint, and can also make interop with C libraries significantly simpler and more efficient. With certain safety checks turned off, this yields performance a bit faster than Java arrays on a much wider variety of datatypes.
Full documentation can be found here.
[vertigo "0.1.4"]
To define a typed structure, we use
vertigo.structs/def-typed-struct:
(use 'vertigo.structs)
(def-typed-struct vec3 :x float64 :y int32 :z uint8)
Each field is defined as a pair: a name and a type. The resulting typed-struct can itself by used as a type:
(def-typed-struct two-vecs :a vec3 :b vec3)
In the
vertigo.structsnamespace, there are a number of predefined primitive types, including
int8,
int16,
int32,
int64,
float32, and
float64. Any integer type can be made unsigned by adding a
uprefix, and all primitive types can have an
-leor
-besuffix for explicit endianness. Without a suffix, the endianness will default to that of the underlying buffer.
We can also define a fixed-length n-dimensional array of any type using
(array type & dims):
(def-typed-struct ints-and-floats :ints (array uint32 10) :floats (array float32 10))
To create a sequence, we can either marshal an existing sequence onto a byte-buffer, or wrap an existing byte source. To marshal a sequence, we can either use
vertigo.core/marshal-seqor
vertigo.core/lazily-marshal-seq:
> (require '[vertigo.core :as v]) nil > (def s (range 5)) #'s > (v/marshal-seq uint8 s) (0 1 2 3 4)
While the marshaled seq is outwardly identical, under the covers it is just a thin object wrapping a 5 byte buffer. In this case we could get an identical effect with an array, but this extends to types of any size or complexity:
> (def x {:ints (range 10), :floats (map float (range 10))}) #'x > (v/marshal-seq ints-and-floats [x]) ({:ints (0 1 2 3 4 5 6 7 8 9), :floats (0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0)})
Using
marshal-seqwill realize and copy over the entire sequence at once. For large or unbounded sequences,
lazily-marshal-seqis preferred. While the performance characteristics of the two methods may differ, the resulting seq is otherwise the same.
To create a sequence that wraps an already encoded source of bytes, you may use
vertigo.core/wrap. Vertigo seqs created via
wrapor
marshal-seqcan be turned back into bytes using
byte-streams/to-*from the byte-streams library.
While we can use
first,
rest,
nth,
get-inand all the other normal Clojure functions on these sequences, we can also do something other data structures can't. Consider the above example of a map containing sequences of ints and floats. To get the fifth element under the
:floatskey, we call
(get-in s [:floats 4]). This will first get the sequence under the
:floatskey, and then look for the fifth element within the sequence.
However, in our data structure we're guaranteed to have a fixed layout, so we know exactly where the data is already. We don't need to fetch all the intermediate data structures, we simply need to calculate the location and do a single read. To do this, we use
vertigo.core/get-in:
> (def ^:int-and-floats s (v/marshal-seq ints-and-floats [x])) #'s > (v/get-in s [0 :floats 4]) 4.0
Notice that we have hinted the sequence with the keyword
:ints-and-floats. To work with our compile-time
get-in, all sequences must be hinted with their element type in this way. In return, we get a read time that even for moderately nested structures can be several orders of magnitude faster.
Since everything's just bytes under the covers, we can also overwrite existing values. While this isn't always necessary, it's certainly useful when you need it. To write to the sequence, we may either use
vertigo.core/set-in!or
vertigo.core/update-in!:
> (def ^:int8 s (v/marshal-seq int8 (range 5))) #'s > (v/set-in! s [5] 42) nil > (v/update-in! s [0] - 42) nil > s (-42 1 2 3 42)
Calling something like
mapon a Vertigo sequence means that we can no longer use
vertigo.core/get-in,
update-in!, or any of the other special operators that only work on Vertigo sequences. This is mostly unavoidable, but in the specific case where we simply want to pull out a subset of the sequence, we can hold onto these properties using
(over s fields):
> (require '[vertigo.structs :as s]) nil > (def matrix (s/array s/int64 2)) #'matrix > (marshal-seq matrix [[0 1] [2 3]]) ((0 1) (2 3)) > (def s *1) #'s
;; if we define both indices as 'free', then we see a flattened iteration over all elements > (over s [_ _]) (0 1 2 3)
;; if we fix the first index, we only iterate over the first array > (over s [0 _]) (0 1)
;; if we fix the second index, we only iterate over the first elements of each array > (over s [_ 0]) (0 2)
A free variable is either
_or anything that begins with
?, like
?ior
?a-gratuitously-long-name.
Since we can directly access the underlying memory, we can do very efficient iteration, but Clojure's normal iteration primitives use too many levels of indirection for us to realize this.
Instead, Vertigo provides
doreduce, a primitive that is a fusion of Clojure's
doseqand
loop:
> (def ^:s/int64 s (marshal-seq s/int64 (repeat 100 1))) #'s > (doreduce [x s] [sum 0] (+ sum x)) 100
Notice that
doreducetakes two binding forms, one for sequences, and another for accumulators. Unlike
loop, the
recurhere is implicit; the value returned for one element is propagated to the next. If we want to propagate multiple values, we simply return a vector:
> (doreduce [x s] [sum 0, product 1] [(+ sum x) (* product x)]) [100 1]
Note that we're not actually allocating a new vector for each element, it's just sugar over a multi-value recursion.
If we explicitly don't want to recur, we can use
break:
> (doreduce [x s] [all-even? true] (if (odd? x) (break false) true))
We can iterate over multiple sequences in parallel:
> (doreduce [x s, y s] [sum 0] (+ x y sum)) 200
We can also iterate over subsets of sequences using the
oversyntax:
> (doreduce [x (over s [?i])] [sum 0] (+ x ?i sum)) 5050
Finally, we can set the
:stepand
:limitfor iteration:
> (doreduce [x s, :step 2, :limit 10] [sum 0] (+ x sum)) 5
Or, if there are multiple iterators,
:stepsand
:limits:
> (doreduce [x (over s [?i]), :steps {?i 2}, :limits {?i 10}] [sum 0] (+ x sum)) 5
Common use cases are exposed as
vertigo.core/sum,
every?, and
any?.
By default, every index is checked at compile time if possible, and runtime if necessary. However, if your access patterns are predictable and no runtime exceptions are thrown, you can turn off bounds checking by adding
-Dvertigo.unsafeas a command-line parameter. When this is enabled,
(vertigo.core/sum s)is ~10% faster than the equivalent operation using Clojure's
areduce, and ~10x faster than
(reduce + array).
Any long-lived data which has a fixed layout can benefit from Vertigo, both with respect to performance and memory efficiency. However, sequences which contain sub-sequences of unpredictable length cannot be represented using Vertigo's structs, and sequences which are discarded after a single iteration won't be worth the trouble of calling
marshal-seq.
Distributed under the MIT License | https://xscode.com/ztellman/vertigo | CC-MAIN-2020-45 | refinedweb | 1,315 | 61.06 |
At a glance: Learn about integrating Facebook Ads with AppsFlyer.
Facebook Ads setup guide
How long does it take to start attributing your Facebook mobile app ads with AppsFlyer?
If you already have the AppsFlyer SDK integrated into your app, and already have defined your app on Facebook, the answer is less than a minute!
You don't need to implement Facebook Login or integrate your app with Facebook's SDK for mobile attribution. Just follow the basic step-by-step setup instructions below. Afterward, check out advanced setup options for Facebook.
Related reading
For a complete picture of working with Facebook Ads in AppsFlyer, check out these articles:
- Facebook Ads integration setup (this article)
- Facebook Ads in-app events mapping
- Facebook SKAN interoperation
- Facebook Ads FAQ (general / cost / SDK / attribution)
- Facebook Ads discrepancies
- Facebook marketing partners configuration (Bidalgo / Kenshoo / Adquant / Webpals)
- Instagram setup
- Facebook Canvas ads
- Attributing app installs to non-mobile ads
Facebook App ID
To integrate Facebook Ads in AppsFlyer, first, create and retrieve the Facebook App ID.
To create the Facebook App ID:
- In Facebook, go to your App Dashboard.
- Under Apps, click Create New App.
- Complete the name for your app, and enter a unique namespace. Make sure to add the correct platform for your app, otherwise, installs might not be attributed correctly.
To retrieve the Facebook App ID:
- In Facebook, go to your App Dashboard.
- Click the required app.
- To copy the Facebook App ID, click on it at the top of the screen.
AppsFlyer attributes data per App ID. The same Facebook App ID can be used for both your Android and iOS apps. Note that for iOS 14+, Facebook Ads limits ad accounts to nine accounts per app.
Effective October 29th, 2021, only aggregate reporting is available to advertisers. This means that both view-through and click-through attribution data appear as “restricted” in raw data reports. Other fields related to the media source aren't populated. See Raw data content restriction.
This applies to all advertisers, operating systems, and MMPs. It relates to the device-level data for all iOS and Android users, regardless of ATT consent status or ads personalization.
AppsFlyer continues to receive device-level data from Facebook, meaning that our attribution and reporting abilities (including multi-touch attribution, LTV, ROI, cohort, retention reports, fraud protection, Audiences, and other services) remain unchanged. See aggregate and analytics reporting tools.
How to get user-level data for Android installs?
Although user-level data is restricted, Facebook Ads shares campaign metadata with advertisers for Android app ads that direct to Google Play Store. In this case, attribution fields are available to advertisers in the Google Install Referrer which must be integrated into your app. The fields provided via the referrer populate AppsFlyer raw data reports available to you once the decryption key is submitted and an install is attributed to Facebook Ads. This enables AppsFlyer to attribute users who don't have an advertising ID (LAT-enabled).
Campaign attribution fields available via the referrer:
- Ad ID
- Ad name
- Adset ID
- Adset name
- Campaign ID
- Campaign name
- Account ID
- Channel
Note! AppsFlyer SDK must be V5.4.0+ for the referrer data to be passed properly. Referrer data has priority over data provided by API and isn't restricted. This solution applies to click-through attribution and not view-through attribution.
Data in the referrer is encrypted by Facebook and is decrypted using a key available to you in your Facebook developer account. You must provide us with the decryption key described in the actions required row. The decryption key needs to be submitted only once per app.
Note that if the key is not provided or was deleted, there are some cases in which Facebook Ads is still attributed for the install based on the referrer - even without the campaign attribution fields (mentioned in the list above). This happens when:
- Facebook Ads didn’t claim the install
- The Facebook install referrer was received but wasn’t decoded
- And this was the last click.
To get your decryption key from Facebook:
- Log in to your Facebook developer portal.
- Navigate to My Apps in the upper right-hand corner.
- Select the app for which you would like to access your decryption key.
- Navigate to Settings > Basic on the left-hand side of the page.
- Scroll down to the Android section and you will see your decryption key labeled Install Referrer decryption key underneath the Package Names field. Note: This is the same section in which you configured your package name and the Google Play Store.
To set the decryption key in AppsFlyer:
- [Mandatory] Verify that AppsFlyer SDK V5.4+ is adopted in your app. Don't rely on earlier versions.
- In AppsFlyer, go to Configuration > Integrated Partners.
- Select Facebook.
- In the Integration tab, paste the key in Install Referrer Decryption Key. This needs to be done only once per app.
- Click Save integration.
Cost, clicks, and impressions data
Enabling the Facebook Cost feature gets you the cost data for your Facebook campaigns, adsets, ads, and channel levels. It also gets you the aggregated clicks and impressions data for them. See the ad network cost integration table for full details on the supported dimensions, metrics, and features. Note: Cost data requires an Xpend subscription.
To enable the cost API:
- Make sure you are logged into the Facebook user account, which is enabled to handle the account's campaigns on Facebook. The user signing in must have permission to run all the campaigns in Facebook Business Manager.
- Go to the Cost tab.
- Turn on Get Cost, Clicks and Impressions Data.
- Click the Facebook Login button.
- When prompted, allow AppsFlyer to access your Facebook campaign data.
Note: In the first data sync after integration, as well as subsequent syncs, AppsFlyer receives Facebook cost data for up to the last 7 days retroactively. regular behavior.
- If you have several users with permissions to Facebook, the best practice is to perform the Facebook login for all of them, to avoid getting partial data.
Cost data sync status
View your cost API status and the last time AppsFlyer managed to pull matching cost data in either the cost (and ad revenue) integration status dashboard, or in the individual ad network dashboard.
Facebook allows you to sync several accounts for pulling cost data. For each synced account, AppsFlyer shows the status of cost integration and the last time AppsFlyer managed to pull matching cost data.
Learn more about enriching your Facebook information with cost, clicks and impressions data.
In-app events mapping
To map in-app events:
- Turn on In-App Event Postbacks.
When enabling the Facebook in-app events mapping for an app for the first time, af_app_open is automatically mapped to session_start.
- Fill in the following parameters:
- To add an SDK event to the list, click Add Event..
- Turn on retargeting in_2<< Ads
Verify the app ID is correct and matches the value in the Facebook Ads dashboard. Ads updates
Important!
Effective October 29th, 2021, only aggregate reporting from Facebook Ads is available to advertisers. This includes both installs and in-app events. This change applies to all advertisers, operating systems, and MMPs. It relates to the device-level data for all iOS and Android users, regardless of ATT consent status or ads personalization.
Raw data for installs and in-app events brought before the change (October 29, 2021) continues to be available.
Note that user-level data can be received via the Google Install Referrer.
See the news bulletin for more details.. | https://support.appsflyer.com/hc/en-us/articles/207033826-Facebook-Ads-integration-setup | CC-MAIN-2022-27 | refinedweb | 1,254 | 56.25 |
First, we do three things to make an applet program
- Create three Ovals, one in the face, two for the eyes.
- Fill
eyes, ovalwith black color.
- Create an arc for the smile in the face.
Also, you can use the Java compiler to compile a
Applet program in Java to draw a face
Implementation.
Import java.awt.*; import java.applet.*; public class smiley extends Applet { /* <applet code = "smiley" width = 300 height = 300> </applet> */ public void paint(Graphics g){ Font f = new Font("Helvetica", Font.BOLD,20); g.setFont(f); g.drawString("Keep Smiling!!!", 50, 30); g.drawOval(60, 60, 200, 200); g.fillOval(90, 120, 50, 20); g.fillOval(190, 120, 50, 20); g.drawLine(165, 125, 165, 175); g.drawArc(110, 130, 95, 95, 0, -180); } }
Output:
In the command line.
C:\A> smiley.java C:\A> smiley.html
Also View: – Write a program to create a registration form using AWT.
Also View- Write a java program to create a window using swing.
One Comment on “Applet program in java to draw a face”
Good way of describing, and nice piece of writing to get data on the topic of my presentation subject, which i am going to deliver in college.| | https://technotaught.com/applet-program-in-java-to-draw-a-face/?noamp=mobile | CC-MAIN-2022-21 | refinedweb | 202 | 76.32 |
24th March 2012 6:23 pm
Yet Another Tutorial for Building a Blog Using Python and Django - Part 3
Welcome back! In this instalment, we’ll make some changes to our URL structure for blog posts, we’ll add support for multiple authors and static pages, and we’ll add some more templates.
First of all, our URL structure. The existing structure works fine, but it would be better if we included a representation of the date of publication. If you’re familiar with WordPress, you’ll know it offers several different URL forms, one of which is the post name alone as we’re using here, and another of which is the year, month and name. We’ll use the latter of these URL schemes with our blogging engine.
This seems like a good opportunity to introduce the interactive Python shell that comes with Django. Make sure you have a few dummy posts set up, then in the project directory (DjangoBlog/, not the top-level one but the one inside that), enter the following command:
python manage.py shell
This will start up an interactive Python shell which you can use to interact with your Post objects. Now, the first step is to import your Post model:
from blogengine.models import Post
We now have access to our Post objects – let’s take a look at them:
You may have completely different post objects, or a different number of them, but that’s fine. Remember we set
__unicode__(self) to return self.title? Here we see that each blog post is represented by its title. Now let’s get one of our Post objects:
In the first line above, we get the Post object with the primary key of 1, and store a reference to it as p. We then demonstrate that it is, indeed, one of our blog posts by outputting its title.
If you’re not familiar with relational database theory, a primary key is a value in a database table that refers uniquely to one entry in the table, so that if you refer to an entry by its primary key, you can be sure you’re getting the correct value. By default, Django models generate a field called id in addition to the ones you define, which is set as the primary key, and this is set to auto-increment, so for instance, every time you add an additional blog post, it gets the next number as its id. Here, we just want to get access to a single blog post object, so we just enter 1 as the primary key in order to get the earliest blog post.
Next, we get the publication date:
This returns a datetime.datetime object. If you look at the documentation for Python’s datetime module, you’ll notice that it has attributes called day, month and year. Here’s how we can use these to get the information we want:
It’s that simple – we just refer to the attribute we want to retrieve. So, it should now be pretty easy to understand how we can get the date for each blog post.
Exit your Python shell with Ctrl-D and head back into the blogengine/ folder. Then open models.py in your text editor and add the following method to the bottom of your Post class:
Now, you haven’t seen get_absolute_url before. Every time you create a model in Django, you should really create a get_absolute_url method for it. In essence, it defines a single, canonical URL for that object, whether it’s a blog post, a user, or what have you. By creating one method that defines the structure for the URL for this type of object and referring to it elsewhere, we only need to change it in one place if we want to make any changes to how we determine the URL for that type of object.
What we do here is we define the URL as being /year/month/slug/. If you want, you can quite easily make it include the day as well like this:
With our model updated, let’s change our URLconf accordingly. Return to the inner DjangoBlog/ directory and open up urls.py, then amend the lines for the blog posts as follows:
What we’ve changed here is that we’ve told urls.py to expect blog posts that look like 4 digits, then a forward slash, then one or two digits, then another forward slash, then a slug that can include hyphens, upper or lower case letters, and numbers.
With that done, we just need to update our template. Edit templates/posts.html to look like this:
Literally all we do is replace post.slug with post.get_absolute_url and remove the leading forward slash. If you then run python manage.py syncdb, restart the development server and go clicking around your posts, you should be able to see that our new URL system is now up and running.
With that done, the next step is to add support for multiple authors. Now, you might think that we’re going to have to create a new model for users, but that’s not so – Django ships with a number of useful models already, and we’re going to use one of them here.
Now, first of all, we need to amend our Post model to include the author’s details. Edit your blogengine/models.py to look like this:
There are two significant changes here. First, we import User from django.contrib.auth.models. User is a model provided by the auth model, and we’re going to use it here to represent the author of a given post. Then in the class definition of Post, we add a new field called author.
Note here that author is a foreign key field, and is passed a User object. Again for those unfamiliar with relational databases, a foreign key is a field in a database table that is also a primary key in another database table. Here we’re declaring that the author is one of the entries in the User table.
As well as this, we need to make some changes to the admin interface. By default, when we make a field in a model a foreign key, the admin interface will show a dropdown list of all of the instances of that object (so here, it would be a list of all the users on the system). But we don’t want that. We want the author to automatically be set as the current user, and for there to be no way to override this.
Open up admin.py and change it to look like this:
The changes made here are simple. We import the User model, and in the PostAdmin class definition we exclude the author field – this means that we don’t show this field at all.
Note the addition of the save_model method. In Django it’s easy to create a new object using your models:
However, the new object won’t actually be stored in the database properly until you call the save() method. Here, you would need to enter p.save() (Note this won’t actually work unless you enter all the fields manually). What we’re doing in admin.py is overriding the default save() method to set the author to the name of the user who wrote the post.
Now run python manage.py syncdb again. Note that as you’ve changed the Post model, your existing posts will be lacking the required author field, and so you may need to add these again manually – this will be a numeric ID mapping to a user id. If you only have one user set up, you should just be able to set this to 1 by using an UPDATE SQL query.
If you now make sure the development server is running and log into the administrative interface, the first page you see should have a section marked “Auth”, with two items underneath named Groups and Users.
Now, cast your mind back to when you activated the admin interface and synced the database. If you recall, at this time you were asked to create a superuser account in order to log into the admin interface. This was actually provided by the django.contrib.auth application, one of the applications that are shipped with Django and are active by default. This contains the User and Group models.
If you’re familiar with Linux or Unix, the Auth application will feel very familiar. The account you created at the start was a superuser account, much like the root account on a Unix system, with unlimited privileges. Other users can be created, and given permissions on an individual basis. You can also create groups and add users to those groups, and then set the privileges for those groups en masse. For instance, in a large collaborative blog with many authors, you may have one group for people who contribute articles who can create new posts, editors who can edit existing posts and so on. Similarly, if you had a working comments system, you could easily set up a moderators group who can delete comments, and add people to that group.
Let’s create another user account so we have more than one. From the main admin page, click on the link for Add next to Users. You’ll be taken to a screen that prompts you for a username and password for the new user. Fill these in (there are two password fields for confirmation purposes) as you wish – here I’m setting the new user as bob. On the next screen you can add some additional details for the new user account, such as first name, last name and email address – do this so you have some information to work with.
Lower down you’ll see a dialogue for entering the permissions. You can make the new user a superuser so that they have permission to do anything, you can say whether or not they are staff (they need to be staff to use the admin interface, so check that), and whether they are active (making it easy to deactivate a user account without the need to delete it). Below you’ll see another dialogue showing the available permissions and allowing you to allocate them to that user. Further down, you’ll see a dialogue for changing the start date and last login date for the user, and finally a dialogue for adding new groups and adding the user to existing groups.
Save the user details once you’re done, then go into your superuser account and add a first and last name so we have some data to work with for that as well. Note that just as with a root account on a Unix box, it’s not a great idea to use a superuser account for everyday work (you should create an account that has the minimum privileges you need and use that), but we’ll stick with it for now just for learning purposes – don’t forget if you should roll out a public facing Django-powered site in future, though!
With that done, we now have some data to work with to identify the author of a given post. Let’s fire up the interactive shell again with python manage.py shell:
Here, we can see that it’s easy to get the author’s details from the post. We define p as a reference to the single Post object,then we get the author, which in this case is called root. As I’ve defined a first and last name, we can get those too with p.author.first_name and p.author.last_name, which are strings containing the first and last name respectively. Note the ‘u’ before the string – this just indicates that the string is Unicode.
So from here, it’s pretty easy to display the author’s name in each post. Go into templates/posts.html and add the following line where you want your author details to appear:
<h3>By {{ post.author.first_name }} {{ post.author.last_name }}</h3>
Now, as long as you’ve added a first name and last name to that author’s details, if you visit, you should see the appropriate details.
Our next step is to add the facility to create flat pages, somewhat like the Pages functionality in WordPress. Again, Django comes with an application that will handle this, called flatpages, but it’s not enabled by default. Go into DjangoBlog/settings.py and at the bottom of INSTALLED_APPS, add the following:
'django.contrib.flatpages',
Then run python manage.py syncdb again to add the appropriate tables to your database. Now, we need to add a flat page. Go back to the main page of the admin interface, and you should see that you now have the facility to add flat pages. Click on the Add link for flat pages, and give your page a URL, a title, and some text (here I’m giving it a URL of /about/ and a title of About), add it to a site at the bottom (this will say example.com, but don’t worry about that, it’s to do with the Sites application, which we’re not looking at right now) then save it. You should now have a FlatPage object available.
Let’s take a look at the tables created for flatpages using the sqlall command:
python manage.py sqlall flatpages
So we can see that django_flatpage, which contains the details about the actual flat pages, has the fields id, url, title, content, enable_comments, template_name, and registration_required. Some of these options are under the advanced options in the flat page interface, so you may have missed them. Now fire up python manage.py shell again:
Here we have one FlatPage object only (note that get() should only be used if you will only get one result back), which is represented by a string that includes the URL and title.
We can easily access any of the fields in the flat page. Now, we need to define some URLs for our flat pages. Exit the Python shell and open urls.py, then insert the following rule underneath the one for blog posts:
Note that this must be the last rule in your urls.py, because it will match anything. Now, you can try and load /about/, or whatever page you’ve created, but you’ll get an error stating that the template does not exist, so we need to create that. Go into your template directory, and create a directory inside that called flatpages. Then create a new file in there called default.html, and add the following code to it:
Now, make sure you have the development server running and try to load, or whatever your flat page URL is, and you should see your flat page’s title and content.
One final task for this lesson – we’re going to refactor our templates a little so that as little code as possible is duplicated and if we want to change anything we need to only do so in one place. Go to your template directory and edit posts.html to look like this:
Here we’re taking the header and footer of the page out and replacing them with code that includes another file there instead. Next, we need to create those files in the same directory. Here’s header.html:
And here’s footer.html:
None of this is terribly complex – we’re just moving the code into another file so that other templates can use the same files. Now save a copy of posts.html as single.html – we’re going to create a template for a single blog post. Edit the original posts.html to look like this:
We’re just removing the date and author details from the template that shows multiple posts. Our existing single.html file can remain as it is for now, since that still has all the additional information we want to include in an individual post.
While we’re here, let’s update our flat pages to use the same header and footer. Go into the flatpages directory and change default.html to look like this:
Note that the path to the template files is not relative to flatpages/default.html, but relative to the root of the template directory.
The last thing to do is to amend the view for our blog to use the correct templates. Go into blogengine/views.py and change the getPost (NOT getPosts) function to pass the single.html template to render_to_response, instead of the posts.html template:
You should now notice that the single posts and multiple posts are using different templates.
Hope you’ve enjoyed this lesson, and I’ll do another one as soon as I can. The code is available on GitHub if you prefer to get it that way. | https://matthewdaly.co.uk/blog/2012/03/24/yet-another-tutorial-for-building-a-blog-using-python-and-django-part-3/ | CC-MAIN-2020-40 | refinedweb | 2,840 | 70.23 |
DaveMalcolm/PythonIdeas
From FedoraProject
Multiple Python configurations
What might we want to vary?
"Debug" versus "standard" build
Python can be built with various debugging options, typically just used when working on Python itself. In my experience "--with-pydebug" roughly halves the speed of the interpreter, but adds lots of extra checking (e.g. reference leaks). It also changes the ABI.
We could produce an entirely separate "debug" python stack, with various debugging checks configured in (breaking ABI, and slowing things down); hope was to make it trivial to run /usr/bin/python2.6-debug (provided you also have the debug build of all of the modules, etc; doesn't work, you need -debug of full stack, I think; you'd have a yum-debug, with -debug of all the stack).
I believe Debian's python packages have worked this way for a year or two; as I understand it they embed the debug build into their "-dbg" subpackages (the equivalent of our "-debuginfo" subpackage)
(See pyconfig.h)
--with-valgrind (not needed if --without-pymalloc)
--enable-profiling ?
Future work: we may want to have with/without LLVM as a build option
"--with-pydebug" is the big one, implying various ABI-breaking changes.
Might want to turn off optimizations, or only optimize lightly, whilst we're at it (e.g. "-Os" ?)
Would need to do as a Feature. Do it for python3 as well, potentially giving 4 subpackages per build.
So for package "coverage" (with C extension modules) you might have the python-coverage.src.rpm emit the following subpackages as part of its build:
- python-coverage (or "python2-coverage"?)
- python-dbg-coverage (or "python2-dbg-coverage"?)
- python3-coverage
- python3-dbg-coverage
- python-coverage-debuginfo
whereas for package "setuptools" (without C extension modules) you might have the python-setuptools.src.rpm emit the following subpackages:
- python-setuptools (or "python2-setuptools"?)
- python3-setuptools
UCS2 vs UCS4
Is it sane to double the number of configurations, offering UCS2 vs UCS4? I don't think so, but listing it here for completeness. I'm not convinced that the choice of UCS4 is correct; are we merely doing it due to historical precedent?
Multiple minor versions
- advance versions of 2.7 and 3.2
Alternate Implementations
Can we use the following to build out multiple stacks? (e.g. share pure-python modules between Jython and CPython?)
- Unladen Swallow
- Jython
- PyPy
Dealing with multiple python implementations
What would packaging guidelines look like? Generalization of current guidelines to add additional builds.
Expressing variability within Koji
See my idea on this sent to the packaging list before. It was roundly rejected at the time, but I'm still fond of it.
Expressing variability within a single build
We do this at the moment for emitting python2 and python3 from within a single build of a src.rpm. Can it be generalized, so that on a given platform we have a set of python 2 and python 3 runtimes, and all builds emit a set of subpackages automatically?
e.g. thinking alouf here, a "python-meta-build" rpm containing: a /etc/python-runtimes.d/ directory, with each runtime dropping a python-foo.conf file (e.g. "python27-debug-ucs2.conf"). The python-meta-build rpm could have requires on all of the supported runtimes for an OS release, so that e.g. Fedora 15's python-meta-build might have:
Requires: python-devel Requires: python-debug-devel Requires: python3-devel Requires: python3-debug-devel Requires: python27-devel Requires: python27-debug-devel Requires: python32-devel Requires: python32-debug-devel Requires: unladen-swallow-devel Requires: unladen-swallow-debug-devel
and then e.g.
python-coverage might have
BuildRequires: python-meta-build
We could have separate arch and noarch meta-packages and directories.
python-coverage.spec might then look like this:
%prep %setup -q -n coverage-%{version} #FIXME: what to do about running 2to3? %build for conf in $(rpm-pyconfig --list) ; do $(rpm-pyconfig --exe $conf) setup.py build done %install for conf in $(rpm-pyconfig --list) ; do $(rpm-pyconfig --exe $conf) setup.py install -O1 --skip-build --root %{buildroot} done %clean rm -rf %{buildroot}
thus using a tool ("rpm-pyconfig", say) to enumerate the runtimes and query properties on them (by reading the .conf files in
/etc/python-runtimes.d/)
It could even support this kind of syntax (somehow need to express the python binary in a way that will be expandable by the tool in its iteration):
%build rpm-pyconfig --foreach "$PYTHON setup.py build" %install rpm-pyconfig --foreach "$PYTHON setup.py install -O1 --skip-build --root %{buildroot}"
(perhaps with a "--foreach2" and "--foreach3" option?)
Difficult issues with this approach:
- what do to about python2 versus python3 sources (i.e. when there's a single tarball for python 2 that has 2to3 run on it for python 3)
- how do we list all of the subpackages, and all of the %files sections; is this doable in rpm as-is? (need to see what the kernel specfile does; this uses macros to great effect)
- how do we conditionalize? perhaps "python-foo" doesn't build properly against 2.7 - is this analogous to ExcludeArch? What if a module builds everywhere, - except say that the 2.7 build doesn't build on ppc: how does the maintainer control that?
Perhaps something like this: each config file becomes an executable
%prep %setup -q -n coverage-%{version} %if 0%{?with_python3} rm -rf %{py3dir} cp -a . %{py3dir} pushd %{py3dir} 2to3 --nobackups --write . popd %endif # if with_python3 # Ensure each variant gets its own pristine copy of the sources: rpm-pyconfig --foreach-2 "cp -a . %{rpm-pyconfig-srcdir}" rpm-pyconfig --foreach-3 "cp -a %{py3dir} %{rpm-pyconfig-srcdir}" # perhaps the above could be done by a macro? %build for pyconf in $(rpm-pyconfig --list) ; do pushd $($pyconf --srcdir) $($pyconf --exe) setup.py build popd done %install for pyconf in $(rpm-pyconfig --list) ; do pushd $($pyconf --srcdir) $($pyconf --exe) setup.py install -O1 --skip-build --root %{buildroot} popd done %clean rm -rf %{buildroot}
Or even:
%prep %setup -q -n coverage-%{version} %if 0%{?with_python3} rm -rf %{py3dir} cp -a . %{py3dir} pushd %{py3dir} 2to3 --nobackups --write . popd %endif # if with_python3 rpm-pyconfig --foreach-2 \ --copy-source-from . rpm-pyconfig --foreach-3 \ --copy-source-from %{py3dir} %build rpm-pyconfig --foreach --in-srcdir --exe \ setup.py build %install rpm-pyconfig --foreach --in-srcdir --exe \ setup.py install -O1 --skip-build --root %{buildroot} %clean rm -rf %{buildroot}
I've deliberately laid out the above so that each iteration is expressed with the control part on the first line, and the action is expressed on the second line.
Fleshed out and sent to the list here:
Other things we could change
dist-packages rather than
site-packages ?
Debian uses "dist-packages" for things coming as part of the distribution, to avoid PyPi users splatting "site-packages"; should we? It seems more logical to me, keeping site-packages for site-specific use. | http://fedoraproject.org/wiki/DaveMalcolm/PythonIdeas | CC-MAIN-2014-52 | refinedweb | 1,146 | 56.66 |
PyEBICS 1.3.0
SEPA EBICS-Client for Python
This package contains all the functionality that is required to work with EBICS and SEPA. The usage has been realised as simple as possible but also as flexible as necessary.
Features
- Obtain bank account statements (CAMT and MT940)
- Submit SEPA credit transfers (pain.001)
- Submit SEPA direct debits CORE, COR1, B2B (pain.008)
- Mostly full SEPA support
- Automatic calculation of the lead time based on holidays and cut-off times
- Integrated mandate manager (beta)
- Validation of IBAN and BIC
- Bankcode/Account to IBAN converter according to the rules of the German Central Bank
- DATEV converter (KNE)
PyEBICS provides you the possibility to manage all of your everyday commercial banking activities such as credit transfers, direct debits or the retrieval of bank account statements in a flexible and secure manner.
All modules can be used free of charge. Only the unlicensed version of the EBICS client has few restrictions. The upload of SEPA documents is limited to a maximum of five transactions and bank account statements can not be retrieved for the last three days.
Example
from ebics.client import EbicsClient client = EbicsClient( keys='~/mykeys', passphrase='secret', url='', hostid='MYBANK', partnerid='CUSTOMER123', userid='USER1', ) # Send the public electronic signature key to the bank. client.INI() # Send the public authentication and encryption keys to the bank. client.HIA() # Create an INI letter that must be printed and sent to the bank. client.create_ini_letter('MyBank AG', '~/ini_brief.pdf') # After the account has been activated the public bank keys # must be downloaded and checked for consistency. print client.HPB() # Finally the bank keys must be activated. client.activate_bank_keys() # Download MT940 bank account statements data = client.STA( start='2014-02-01', end='2014-02-07', )
Changelog
- v1.3.0 [2014-07-29]
- Fixed a few minor bugs.
- Made the package available for Windows.
- v1.2.0 [2014-05-23]
- Added new DATEV module.
- Fixed wrong XML position of UltmtCdtr node in SEPA documents.
- Changed the order of the (BANKCODE, ACCOUNT) tuple to (ACCOUNT, BANKCODE) used by the Account initializer.
- v1.1.25 [2014-02-22]
- Minor bug fix of the module loader.
- v1.1.24 [2014-02-21]
- First public release.
- Downloads (All Versions):
- 65 downloads in the last day
- 782 downloads in the last week
- 2116 downloads in the last month
- Author: Thimo Kraemer
- Keywords: ebics,sepa
- License: Proprietary, see
- Package Index Owner: joonis
- DOAP record: PyEBICS-1.3.0.xml | https://pypi.python.org/pypi/PyEBICS/1.3.0 | CC-MAIN-2015-32 | refinedweb | 406 | 56.96 |
IntroI've split the introduction to this post into two parts. The first part is long and sentimental, describing my personal journey with monads up to now. The second part is short and to the point. Feel free to skip over the next section if you're not interested in the sappy stuff - you won't be missing anything important.
Sappy IntroI've been programming Scala for a little over two years now, and I love it. I was an old-time Java hack, firmly embedded in the OO programming paradigm. Scala to me was largely like a souped up Java, with all the clunky, broken things about Java fixed (aside from type erasure). I had taken courses Scheme and the lambda calculus in college, and I thought I had a pretty good understanding of functional programming. However, while programming Scala, and getting exposure to the language, libraries, and community, I began to discover that there is a lot more to functional programming than I originally thought. By far the most prominent example of this was the the importance of the concept of the monad in the Scala community.
I didn't know what a monad was, and over the past couple of years, I've made various efforts to try to understand it. For the most part, the videos I watched, and the articles I read, left me with one of two impressions: Either it didn't make any sense, or I just couldn't see what the big deal was. As I continued to explore, I began to notice that most of the explanatory examples are in Haskell, and not understanding the Haskell language or syntax was a serious impediment for me. At that point, I set out specifically searching for monad examples in Scala, and found this excellent series of blog posts by James Iry: Monads are Elephants (see also parts two, three, and four). Finally, monads were beginning to make sense! But after reading these articles, I realized I was going to have to implement some monads myself to really grok them. I also knew that I would have to follow by example to do this. Which meant that I really needed to bite the bullet and look at some monad examples in Haskell.
No Nonsense IntroI found an excellent exposition on monads in this Haskell Wikibook, and set out to translate the examples into Scala. In this blog post, we will present a translation of the Maybe/Person example presented in the first page the chapter on monads. In future blog posts, I hope we can do the same for the rest of the pages of this chapter.
A Note on the CodeAll the code presented below is based on the Understanding monads page of the Haskell Wikibook. I am very grateful to the authors for making this available. It's very well written! I am also deeply appreciative of the fact that they provide this material under the terms of the Creative Commons License. While I rely heavily on the code presented here, none of it is re-presented here. Most sections of this blog post provide links to the section of the page being discussed. It may help if you read through the wikibook chapter before tackling the Scala presented here, but it isn't strictly necessary.
All the Scala code presented here is my own. The code can be found in this monads-in-scala project on GitHub. I tagged the code as it is presented here as monads-in-scala-1, as I anticipate modifying this code in future blog posts. Be sure to look at the code in src/test/scala tree there as well. Launch sbt in the project, run ~ test, play around and make some edits, and see what happens.
Implementing the Maybe MonadLet's first translate the definition of the Maybe monad from Haskell into Scala. We'll present the Scala solution first, and then we'll break it down:
Definition of MonadA monad is defined in the wikibook, and in Wikipedia, as having three parts:
- A type constructor
- A unit function, commonly called return in Haskell
- A binding operation, commonly called >>= in Haskell
Type ConstructorIn Scala, a type constructor is just the definition of a type that has a type parameter. In our case, the type definition is trait Maybe[+A]. The A is the underlying data type. The + indicates covariance, which means that if an A is a B, then a Maybe[A] is also a Maybe[B]. This is the typical type variance for a container where, once constructed, we can read out what is contained inside, but we cannot write in to the container. In other words, an immutable container.
Because MaybeNot is an empty container, we can use the same MaybeNot instance for all maybes, regardless of the type parameter. To achieve this, we make the type parameter the special Scala type Nothing, which is a sub-type of every other type. Thanks to the covariance of A in Maybe[+A], the type parameter of MaybeNot matches regardless of what is chosen for A.
We use MaybeNot here where the Haskell example uses Nothing, to avoid confusion with Scala's Nothing.
Unit FunctionThe unit function is a function from the contained type to the container type, i.e., from A to Maybe[A]. The unit function is typically named return in Haskell. A natural place to put a function like this in Scala is as an apply method of a companion object. Because apply methods are automatically generated by the compiler for case classes, we get our unit function for free in method Just.apply(A).
Binding OperationThe binding operation, as a Scala function, would have the following signature:
def bind[A, B](Maybe[A])(A => Maybe[B]): Maybe[B]In Haskell, this is implemented as a function named >>=. As Scala is an object oriented language, it is natural to implement this as a method on type Maybe[A]. It's also customary to name such Scala methods flatMap.
As you can see, we make use of polymorphism in the above definition of flatMap. This might not please the hard-core functional programmers out there. A non-polymorphic implementation can be achieved with the Scala match operator, and is a more direct translation of the Haskell example:
Maybe Monad MotivationThe initial motivating example for Maybe in the wikibook is a family database where lookups on father and mother may or may not return a result. The wikibook does not define the functions mother and father, but we provide implementations of them in Scala, since we want to be able to test our code. We also provide a list of people to use for testing via companion object method Person.persons. The only thing of note here is that we provide mother and father as instance methods, and not just regular functions:
Maternal GrandfatherThe wikibook goes on to explain the usefulness of the Maybe monad by defining a maternalGrandfather function using >>=. What follows is an implementation of maternalGrandfather using flatMap, the equivalent version using match, and a simple test showing the two functions produce the same results.
Both GrandfathersA similar example follows for bothGrandfathers. This function returns Nothing unless both grandfathers are found. The match version here is greatly simplified by the fact that we can match on two parents at once using pairs.
To demonstrate the usefulness of matching tuples in Scala, let's rewrite the non-flatMap version to avoid matching pairs:
Both Grandfathers Using ForThe wikibook proceeds to rewrite the bothGrandfathers example using a Haskell do loop. The Scala equivalent is a for loop, but to make the for loop work, we need to go back and add a map method to Maybe. The equivalent operation to map in Haskell is >>, pronounced then. We can define map in terms of the unit function and the binding operation:
Now we can proceed to write bothGrandfathers using a for loop:
Monad LawsThe wikibook continues by explaining that the unit function and the binding operation cannot be just any old operations; They must obey the three provided laws: left unit, right unit, and associativity. It's obviously not exhaustive and not a proof, but we provide some test code that exercises the three laws with test values. We iterate over all the Person objects in Person.persons to substitute for x. For m, we substitute MaybeNot, plus Just(p) for every p in Person.persons. We take instance method Person.mother as f, and Person.father as g. Here's our test code to help convince ourselves that the monad laws are satisfied:
Monads and Category TheoryThe wikibook page on understanding monads concludes with a brief foray into category theory. Two extra functions on monads, fmap and join, are introduced. The Scala equivalent to fmap is map, presented above. The Scala equivalent to join is flatten, which can also be defined in terms of the unit function and the binding operation. However, flatten is tricky to define in Scala, because it requires that the type parameter A is itself a monad. This is achieved in Scala by adding an implicit parameter with type <:<, like so:
To understand this, let's start with the Scaladoc documentation for scala.Predef.<:<, which reads, "An instance of A <:< B witnesses that A is a subtype of B. Requiring an implicit argument of the type A <:< B encodes the generalized constraint A <: B." So the implicit parameter in flatten provides a sort of identity mapping function that maps type Maybe[A] onto type Maybe[Maybe[B]]. The Scala library is designed so that the compiler will guarantee that Maybe[A] is a sub-type of Maybe[Maybe[B]] at any point flatten is called. For instance, the following code:
Just(1).flattenWill produce the following compiler error:
Cannot prove that maybe.Maybe[Int] <:< maybe.Maybe[maybe.Maybe[B]].Within the body of flatten, the implicit parameter asMaybeMaybe acts as a type converter from Maybe[A] to Maybe[Maybe[B]]. After performing the type conversion, we simply apply the definition of join as presented in the wikibook. (The identity function is provided in scala.Predef.) Here is a short code sample testing that the flatten implementation is correct: | http://scabl.blogspot.com/2013/02/monads-in-scala-1.html | CC-MAIN-2014-52 | refinedweb | 1,709 | 61.36 |
When was this solution from the unity forum which I adapted to my needs. Thanks for the code. Hopefully the improvement in this post is helpful for someone.
The basic idea is to have a language file for each language. A language file consists of keys and contents. The language files need to be stored in the Unity solution (in Unity Editor) in a folder called Resources. To configure the Unity game with a language the script loads the textfile from the resources, parses it and stores the texts and keys in a dictionary. To retrieve a localized text call
GetText(key).
TextManager Class Definition
using UnityEngine; using System.IO; using System.Collections.Generic; using System; using Assets.Scripts; public class TextManager : MonoBehaviour { private static readonly IDictionary<string, string> TextTable = new Dictionary<string, string>(); private static TextAsset _language;
Singleton Constructor
TextManager is a singleton. I wanted to make sure there is only one TextManager in the system and the resource file should only be read once. Note the private constructor and the method instance.
DontDestroyOnLoad() makes sure the object is not destroyed when a new scene is loaded.
private TextManager() { } private static TextManager _instance; public static TextManager instance { get { if (_instance == null) { _instance = GameObject.FindObjectOfType<TextManager>(); // Tell unity not to destroy this object when loading a new scene! DontDestroyOnLoad(_instance.gameObject); } return _instance; } }
Awake to Destroy Additional Instances
When during the game you switch from a scene that does not have TextManager in its GameObjects list to a scene with TextManager then a new GameObject is created and the
Awake() method is called on it. So if you use
DontDestroyOnLoad() you would add another TextManager to the currently instanciated GameObjects. To make sure we only have one TextManager the implementation of
Awake() destroys all additional TextManagers.
void Awake() { if (_instance == null) { // If I am the first instance, make me the Singleton _instance = this; DontDestroyOnLoad(this); SetDefaultLanguage(); } else { // If a Singleton already exists and you find // another reference in scene, destroy it! if (this != _instance) Destroy(this.gameObject); } }
Set the Default Language
Persistence.GetLanguage() returns the name of the language that the player has configured. It just reads a value from the
PlayerPrefs. If the code is running for the first time we try to set the language that is set in the operating system. Definitions.GermanName, Definitions.EnglishName and Definitions.DefaultLanguages are constant strings.
Persistence.SetLanguage() sets a value in the
PlayerPrefs.
public static void SetDefaultLanguage() { string language = Persistence.GetLanguage(); if (language == "") { var osLanguage = Application.systemLanguage; if (osLanguage == SystemLanguage.German) { language = Definitions.GermanName; } else if (osLanguage == SystemLanguage.English) { language = Definitions.EnglishName; } else { language = Definitions.DefaultLanguage; } Persistence.SetLanguage(language); } SetLanguage(language); }
Load the Text File from the Resources
The method
SetLanguage() loads the language text file in memory and calls
LoadLanguage().
public static void SetLanguage(string langFilename) { // Load a asset by its AssetName. // The text file must be located within 'Resources' subfolder in Unity ('Assets/Resources' in Visual Studio). TextAsset newLanguage = Resources.Load(langFilename) as TextAsset; if (newLanguage == null) { Debug.LogError(String.Format("No valid asset file.")); } else { LoadLanguage(newLanguage); _language = newLanguage; } }
Parse the Text File to Create the Dictionary
LoadLanguage() parses the language text file and stores all entries in a dictionary. For the expected file format see below.
private static void LoadLanguage(TextAsset asset) { TextTable.Clear(); var lineNumber = 1; using (var reader = new StringReader(asset.text)) { string line; while ((line = reader.ReadLine()) != null) { int firstSpaceIndex = line.IndexOf('='); if (firstSpaceIndex > 0) { var key = line.Substring(0, firstSpaceIndex); var val = line.Substring(firstSpaceIndex + 1); if (key != null && val != null) { var loweredKey = key.ToLower(); if (TextTable.ContainsKey(loweredKey)) { Debug.LogWarning(String.Format( "Duplicate key '{1}' in language file '{0}' detected.", asset.text, key)); } TextTable.Add(loweredKey, val); } } else { Debug.LogWarning(String.Format( "Format error in language file '{0}' on line {1}. Each line must be of format: key=value", asset.text, lineNumber)); } lineNumber++; } } }
Retrieve the Localized Text
This is the implementation that retrieves the localized text from the dictionary.
public string GetText(string key) { string result = ""; var loweredKey = key.ToLower(); if (TextTable.ContainsKey(loweredKey)) { result = TextTable[loweredKey]; } else { Debug.LogWarning(String.Format("Couldn't find key '{0}' in dictionary.", key)); } return result; } }
Text File Format
The language files are expected to have this format:
English.txt:
firstkey=first english text key2=another english text
German.txt:
firstkey=erster deutscher Text key2=Noch ein deutscher Text
The keys need to be the same in all language files.
German Umlauts
To make sure the german umlauts (äöü) are properly displayed I set the encoding of the text file to UTF-8. For instance use Notepad++ and you find the Encoding in the menu.
Unity 3d
Add the TextManager to the list of GameObjects in Unity. You only need to add it to the scene that is loaded first. The way we defined the constructor and the Awake() method the TextManager will always be there and exactly once.
To get localized text use this line of code:
TextManager.instance.GetText("key");
So that’s it. Happy coding!
| http://www.huwyss.com/level-it/localization-textmanager-for-unity3d | CC-MAIN-2019-47 | refinedweb | 832 | 52.46 |
React and Redux Use Provider to Connect Redux to React
In this video you will learn how to start using Redux in React. Let's jump right into it.
Content
In previous video we build the Redux example in plain JavaScript to understand the core features of Redux. If you didn't watch that video or you don't know what dispatch, subscribe, getState from Redux are working I highly recommend you to watch that video first.
So our goal in this video is to build a Redux example in React world. We want to have a list of users and an input with the button so we can add new users to the list.
Here I have a generated create-react-app application. If you don't know how to generate it or what is it at all I already made a video on that.
Our first step to start using Redux inside React is to install react-redux package. What is this? It's a package for React that makes bindings to Redux. Which means we can use React with Redux easier. We also need to install Redux.
yarn add redux yarn add react-redux
Now we need to create store in the same way like we did in our javascript example.
index.js
import { createStore } from "redux"; const store = createStore();
As you can see we are getting the error that we need to provide a reducer inside. Let's create a reducer.js file and put an action here. Just to remind you action is what we dispatch from our store in order to somehow change the state.
const reducer = (state = [], action) => { return state; }; export default reducer;
Now we can pass it in our createStore.
import reducer from "./reducer"; const store = createStore(reducer);
The next this that we need to do is to wrap all our components in the Provider component which react-redux is giving us.
import { Provider } from "react-redux"; ... ReactDOM.render( <React.StrictMode> <Provider store={store}> <App /> </Provider> </React.StrictMode>, document.getElementById("root") );
So We wrapped our whole application in Provider and passed our store inside. Now the question is why we are doing this? So we want that every our component has access to the store. In React world this can be achieved by using React context. It's a way to create some global data or functions and they will be available in all components which are inside a Provider. As you can see we are passing our store inside exactly to make it available in all our components.
So let's move our markup to render users in our App component.
import { Component } from "react"; class App extends Component { state = { username: "", }; handleUser = (e) => { this.setState({ username: e.target.value }); }; addUser = () => { console.log("addUser", this.state.username); }; render() { return ( <div> <input type="text" value={this.state.username} onChange={this.handleUser} /> <button onClick={this.addUser}>Add user</button> <ul></ul> </div> ); } } export default App;
So here we created a React class because we need a state for our input. So we adding input change and addUser function. As you can see everything is working and it is plain javascript.
Now how we can use Redux here?
We need to use connect function from react-redux. It's our single way to work with Redux from every component. As you can see we wrap our component in connect and provide inside as a first parameter mapStateToProps function. What is it? It's a way to describe what fields we want to get from Redux. So first of all we want to read user data from our store.
import { connect } from "react-redux"; ... const mapStateToProps = (state) => { console.log("state", state); return { users: state, }; }; export default connect(mapStateToProps)(App);
As a first parameter we get our state. It's exactly what we got previously with store.getState. The only important thing here is to return an object back. Because the idea is that we want to read some data from state and make them available in our component. In this case we returned our users which is actually the whole state. But of course later we can have hundrends fields inside our state.
Now if we console.log props in our App component you can see that we get users property from connect inside.
render() { console.log("props", this.props); ... }
Let's render our users.
<ul> {this.props.users.map((user, index) => ( <li key={index}>{user}</li> ))} </ul>
To test that it's working we can change the initial array that we have.
Now actually we want to dispatch our changes like we did previously. As you saw when we logged props we got there also dispatch function because connect gives it for us out of the box. Let's use it inside addUser.
addUser = () => { console.log("addUser", this.state.username); this.props.dispatch({ type: "ADD_USER", payload: this.state.username }); };
Now we need to update our reducer in our to change the state after ADD_USER action.
const reducer = (state = [], action) => { if (action.type === "ADD_USER") { return [...state, action.payload]; } return state; }; export default reducer;
Call to action
As you can see everything is working and we are using Redux inside React now. The most important that you understand that there is no magic in redux or react-redux. Redux is a library with less that 50 lines of code and react-redux is just bindings for React with lots of sugar and performance optimisations.. | https://monsterlessons-academy.com/p/react-and-redux-use-provider-to-connect-redux-to-react | CC-MAIN-2021-31 | refinedweb | 907 | 67.35 |
JSP Interview Questions
- 1) Explain What is JSP?
- 2) What is the el in JSP?
- 3) How to print variables in JSP?
- 4) Explain OUT Implicit Object in JSP?
- 5) How to write comments in JSP?
- 6) Enlist types of JSP tags?
- 7) What are directives in JSP?
- 8) How we use an expression in JSP?
- 9) What is the use of < Jsp: param> tag?
- 10) Enlist different scope values for the <jsp:useBean> tag?
- 11) How to create and remove a session in JSP?
- 12) What is the difference between JSP and JSPX?
- 13) What is the use of the Include directive in JSP?
- 14) Which attribute specifies a JSP page that should process any exceptions thrown but not caught in the current page?
- 15) Explain what is JSTL?
- 16) What are Custom Tags in JSP? How do you create it?
Below are the list of Best JSP Interview Questions and Answers
JSP, expanded as Java Server Pages is a Java-based technology to create dynamic web pages. Released in 1999 by Sun Microsystems, JSP is based on technologies such as HTML, SOAP, XML, etc. JSP can be viewed as a servlet architecturally as it is translated into a servlet at runtime. JSP can also be used as a view component in MVC architecture with JavaBeans as a model and Servlets as the controller. JSP allows static content like HTML along with java code to be executed on the server-side. The resulting bytecode from the JSP must the executed on the JVM. In an overview, JSP can be thought of as an ASP or PHP technology to create web application but instead, JSP uses Java.
The EL (Expression Language) in the JSP is used to access the data stored in the JavaBeans along with implicit objects like requests, sessions, etc. It uses arithmetic and logical expressions to compute the accessed data. JSP supports data types such as integers, float, string, Boolean, and null.
Syntax
${EL expression}
Example
<jsp:setProperty //here . is used to access a property of the entry
Expression Language supports most of the arithmetic and Logical operators for basic computation along with special operators like ‘.’ to access a property, ‘[]’ to access an array or list, and ‘()’ to group expression.
Functions can also be created using the JSP EL
Syntax
${ns:func(param1, param2, ...)} //ns is the function namespace and func is the name of the function.
JSP uses the Java programming language. So, most of the statements in JSP follows the Java code. To print a variable in JSP,
<% String name=request.getParameter("Pname"); //initializing the variable name with Pname value. out.print("welcome "+name); //statement to print the variable in JSP %>
JSP has several implicit objects or predefined variables that developers can call without being explicitly declared. These are just Java objects and one such object is called Out implicit object.
The out implicit object is an instance of a JspWriter object that is used to send data or some content in response. This object can be declared based on the buffering of the page. The methods provided by this object are,
- out.print(data type dt) - it prints a data type value.
- out.println(data type dt) - it prints a data type value and terminates with a new line.
- out.flush() - it flushes the data stream.
The syntax for JSP comment is,
<%-- comment --%>
It tells the JSP container to ignore this part from the compilation as a comment.
<%--An Example for JSP comment--%>,
- <%@page...%> - it defines page-dependent attributes.
- <%@include...%> - it includes a file.
- <%@taglib...%> - it declares a tag library to be used on the page.()%>
The JSP directive provides information to the container on how to process the JSP page into its respective servlet.
Syntax
<%@ directive attribute = "value" %>
There are three JSP directive attributes. They are,
- <%@ page ... %> - this is a page directive and it provides information about the JSP page like a scripting language, buffering requirements to the container. It has a number of attributes like buffer, autoFlush, contentType, session, etc to provide information.
- <%@ include ... %> - this is an include directive and it includes files pertaining to the translation phase.
- <%@ taglib ... %> - this is a tag library directive to define custom user-defined tags.
Expressions in the JSP can be used in the expression tag to be evaluated. The expression tag converts the expression into a value of a string object and inserts it into the implicit output object to be displayed in the client browser. The semicolon is also no need to signal the end of the statement in the expression tag.
Syntax
<%= expression %>
Example
<%= "Expression Statement" %> //no need for output statement as the expression tag converts the string into output object and the “Expression Statement” is displayed.
JSP param tag is one of the JSP action tags that is used to perform some specific tasks. The JSP param action is used to give information in the form of key/value pair. It can be used with JSP include, forward, and plugin action tag.
Syntax
<jsp:param
Example
<jsp:forward //JSP param is used with the JSP forward action tag. </jsp:forward>
The JSP useBean action tag is used to locate the bean class is the bean object is instantiated or it instantiates the bean object. It has many attributes like id, scope, class, type, and beanName. The scope attribute in the useBean action tag is used to represent the scope of the bean. The default scope is the page, but different scopes are available such as request, session, and application.
- Page – The default scope that specifies the scope of the bean within the JSP page.
- Request – specifies the scope of the bean to all the JSP page that processes the same request.
- Session – specifies the scope of the bean to all the JSP page that has the same session irrespective of its request.
- Application – specifies the scope of the bean to all the JSP pages in the same application.
JSP Session uses HttpSession to create a session for each user. To create a session in JSP, we need to use setAttribute from the session implicit object.
Creating Session
session.setAttribute("user", name); //it creates the session for the object name.
To remove the object from the session.
session.removeAttribute("user"); //deletes the session for the object name.
To remove the entire session.
session.invalidate(); - it kills the entire session and all the objects that are associated with this session.
JSPX file is nothing but an XML format for creating JSP pages. JSPX forces the separation of code from the view layer in different files. Javascript and XML are written in different files in JSPX whereas Java code and XML code are written in the same file in the JSP. Writing an XML format code is better in some cases than writing the native JSP. The XML code is easy to manipulate, errors can be rectified faster. Also, the JSPX file has a simpler syntax in XML than JSP pages. But, executing the logical or arithmetic expression in JSPX is difficult and hard. Dynamic content is easily generated on the JSP page than in the JSPX file.
The include directive is used to include file to the JSP page during translation. These files can be an HTML, JSP, or normal text files. These files are useful in creating templates for user views. It is also used to break the pages into header, footer and sidebar sections.
Syntax
<%@ include….%>
Example
<%@ include file="header.jsp" %> //it includes header.jsp to the current file.
14) Which attribute specifies a JSP page that should process any exceptions thrown but not caught in the current page?
ErrorPage Attribute process specifies a JSP page that should process any exceptions thrown but not caught in the current page.
JSTL (JSP Standard Tag Library) is a collection of tags that brings valuable functionality to build JSP applications. According to their functions, JSTL is divided into 5 types.
- Core tags – this tag provides support for variables, URL management, and control flow by importing core libraries.
- Function tags – It provides support for string manipulation functions.
- Formatting tags – it provides formatting functions such as message formatting, date & time formatting, etc.
- XML tags – it is used to create and manipulate XML documents.
- SQL tags – As the name suggests, it provides SQL support to interact with databases.
The custom tags are just user-defined elements that are converted into some operation on an object when the JSP is translated into a servlet. Custom tags are instantiated from the SimpleTagSupport class. With this, scriptlet tag use is removed. And also, the custom tags can be reused.
To create a custom tag in jsp, do the following steps.
- Create the tag handler class and override the doStartTag() method.
- Create the TLD file which contains information about the tag and the tag handler class.
- Create the JSP file and use the created tag in. | https://www.onlineinterviewquestions.com/jsp-interview-questions/ | CC-MAIN-2021-31 | refinedweb | 1,474 | 66.84 |
USDA Feed Outlook
15 August 2012
US feed grain supplies for 2012/13 are projected sharply lower again this
month with corn production forecast 2.2 billion bushels lower and sorghum production
forecast 92 million bushels lower, according to the USDA Feed Outlook.
Feed Outlook - August 2012
The forecast US corn yield is reduced 22.6 bushels per acre to 123.4 bushels as extreme heat and dryness continued, and in many areas worsened, during July across the Plains and Corn Belt. Sorghum production is also forecast lower this month due to drought. Total US corn supplies for 2012/13 are projected down 2.0 billion bushels at a 9-year low. The large reduction in forecast corn supplies this month is expected to result in record-high prices, which will ration demand and lower use. Corn use is projected 1.5 billion bushels lower with large cuts in feed and residual use; food, seed and industrial use; and exports. Ending stocks are forecast down 533 million bushels to 650 million bushels, the lowest since 1995/96. Record corn prices for 2012/13 reduce projected foreign corn imports and use this month, but a record corn crop in China and 2 years of large crops in Brazil support some growth in foreign corn feed use in 2012/13.
US Feed Grain Supply Prospects Plunge
Forecast US feed grain beginning stocks in 2012/13 are raised 3.0 million tons
from last month but are down 3.5 million tons from the previous year, an 11-percent
reduction. US feed grain production is forecast at 285.9 million metric tons, 57.9
million below last month and 37.7 million below the 2011/12 estimate. Compared
with volumes in 2011/12, production is down sharply for corn but up for sorghum,
barley, and oats. This month saw sharp declines in projected production for corn
and sorghum and slight gains for barley and oats. Feed grain supply is projected at
318.7 million metric tons this month, 53.5 million short of last month’s projection
and 39.7 million below 2011/12.
Total 2012/13 feed grain use is projected 39.4 million metric tons lower from last month and 30.2 million short of 2011/12. This month’s reduction reflects lower estimates for feed and residual disappearance; food, seed, and industrial (FSI) use; and exports for corn and sorghum due to rationing on higher prices. Sharply lower forecast use for fuel ethanol is accompanied by declines in most other FSI categories. FSI is projected at 155.1 million metric tons in 2012/13, compared with 169.0 million in 2011/12. Exports are forecast at 35.8 million metric tons, down 8.6 million from the previous estimate and 5.2 million below last season.
The US Census Bureau issued revised numbers for calendar 2011, affecting trade
estimates this month for corn and sorghum in 2010/11 and for barley and oats in
2011/12. Imports are raised slightly for 2010/11 and 2011/12 and are projected up
1.4 tons for 2012/13, with notable increases for corn and barley. Marketing year
exports for feed grains in 2010/11 are raised slightly to 50.7 million metric tons,
mostly reflecting a large upward revision for sorghum shipments. In 2011/12,
estimated exports are raised for barley and lowered for oats based on the latest
Census data, as the marketing year is over. Sorghum and corn export forecasts (the
2011/12 marketing year ends at the end of August) are also adjusted based on the pace of shipments, with corn down 10 times as much as sorghum is increased. Feed
grain exports for 2011/12 are projected 1.1 million metric tons lower to 41.0
million. Ending stocks for 2011/12 are up 3.0 million metric tons to 28.7 million.
Exports projected for 2012/13 are lowered 8.6 million metric tons to 35.8 million,
as tight supplies and high prices affect the export market.
When converted to a September – August marketing year, feed and residual use for
the four feed grains plus wheat in 2012/13 is projected to total 113.1 million tons,
down from 132.2 million last month and down 12 percent from the 2011/12 forecast
of 128.0 million. Corn is estimated to account for 92 percent of total feed and
residual use in 2012/13, up from 90 percent in 2011/12.
Projected grain-consuming animal units (GCAUs) for 2012/13 are lower than last month at 92.1 million. Estimated GCAUs for 2011/12 are also lower on the month at 93.4 million compared with July’s estimate of 93.7 million. For 2012/13, feed and residual use per animal unit is projected at 1.23 tons, down from last month’s 1.42 tons due to lower cattle carcass weights and lower hog numbers and the impact of tight feed supplies and higher prices.
As Drought Continues, Forecast Yield Is Lowered 23 Bushels per Acre
The NASS August 10 Crop Production report forecast U.S. 2012/13 corn yields 22.6 bushels per acre lower at 123.4 bushels, compared with last month’s forecast of 146 bushels. As forecast, the 2012/13 corn yield would be the lowest since 1995/96. The yield reduction, combined with lower expected harvested acres, down 1.5 million acres from last month’s projection, results in a crop of 10,779 million bushels, 2,191 million bushels lower than July’s projection and 1,580 million below last season. This forecast would result in the lowest production since 2006/07. Harvested acreage for 2012/13 is forecast at 87.4 million acres for grain, up 3.4 million from the previous year. Unusually high temperatures and well below average precipitation across much of the Corn Belt in July sharply reduced yield prospects, despite the early planted crop. As of August 5, only 23 percent of the corn crop was rated in good-to-excellent condition in the 18 major corn-producing States, down 37 percentage points from a year ago. Fifty percent of the crop was in the very poor-to-poor range, compared with 48 percent the previous week and 16 percent at this point last season, a year when yields fell below trend. Corn conditions are extremely variable, with crops in close proximity having very different yield potential.
U.S. Corn Use Expected To Slip
Tight supplies and higher prices are expected to force rationing among corn users.
Total US corn use for 2012/13 is forecast down 1,495 million bushels to 11,225
million this month as a result of decreased feed and residual use, FSI use, and
exports. Total FSI is projected 470 million bushels lower with corn for ethanol
lowered 400 million bushels, along with declines in most other FSI categories.
Feed and residual use is projected 725 million bushels lower, one of the largest
declines ever, reflecting livestock producers’ reactions to record-high corn prices
and reduced residual disappearance with a smaller crop. U.S. exports are reduced
by 300 million bushels as high prices dampen demand and foreign feeders shift to
more competitively priced corn and wheat from foreign producers.
Total corn use for 2011/12 is forecast down 115 million bushels to 12,490 million bushels this month. Food, seed, and industrial use (FSI) is reduced 65 million bushels to 6,390 million bushels. Lower use for ethanol, down 50 million bushels to 5,000 million, plus a 15-million-bushel reduction for corn used to produce glucose and dextrose, results in the lower FSI use projection. U.S. exports for 2011/12 are reduced 50 million bushels to 1,550 million. Reductions in use leave ending stocks for 2011/12 up 118 million bushels over last month’s projection. Corn prices received by farmers for 2012/13 are projected at a record $7.50-$8.90 per bushel, up more than $2.00 on both ends of the range this month. The marketing year average reflects higher prices for corn, with tighter ending stocks and tight U.S. feed grain supplies. The 2011/12 corn price range is raised $0.10 cents on the low end for an estimated range of $6.20-$6.30 per bushel.
U.S. Sorghum Production Lower
A sharp reduction in forecast yield and lower harvested acreage resulted in a
reduced forecast for 2012/13 U.S. sorghum production this month. At 248 million
bushels, forecast production is down 92 million from last month, but is 33 million
bushels above last year’s crop estimate. Based on August 1 conditions, yield is
lowered by 16.3 bushels per acre this month and is projected 6.0 bushels per acre
below the last season’s historically low yield. Hot dry weather in Texas, Kansas,
and Oklahoma has reduced prospects for the 2012 sorghum crop. As of August 5,
25 percent of the U.S. sorghum crop was rated good to excellent, compared with 27
percent last season and 66 percent in 2009/10.
Total use of sorghum in 2012/13 is projected down 80 million bushels this month to 250 million reflecting tight supplies. Feed and residual is cut 30 million bushels to 70 million as high prices reduce feed demand by livestock producers. Sorghum FSI use is lowered 10 million bushels to 80 million, with lower expected use for fuel ethanol. Export prospects are reduced 40 million bushels to 100 million as demand from Mexico is expected to remain strong, but high prices and tight supplies limit shipments. U.S. ending stocks are projected at 25 million bushels, 12 million bushels lower than last month’s projection and slightly less than forecast for the previous season.
Total use for sorghum in 2011/12 is forecast at 215 million bushels, unchanged
from last month. Feed and residual use remains forecast at 75 million bushels.
Sorghum used for ethanol is expected lower during the summer quarter, with
tightening supplies cutting marketing year FSI use 5 million bushels to 85 million.
Exports are raised 5 million bushels to 55 million, reflecting stronger-than-expected
recent shipments. Ending stocks for 2010/11 are virtually unchanged this month at
27 million bushels.
Sorghum prices received by farmers for 2012/13 are projected higher with surging corn prices. The projected farm price range, is raised $2.00 on the low end of the range and $2.40 on the high end or the range resulting in a spread of $7.00 to $8.40. The 2011/12 average sorghum farm price is narrowed $0.05 on each end of the range to $6.05-$6.15 per bushel.
U.S. Barley Production Prospects Increase Slightly
U.S. barley production for 2012/13 is forecast at 221 million bushels, up 4 million from last month and up 65 million from 2011/12. Based on August 1 conditions, producers expect yields to average 67.6 bushels per acre, up 1.3 bushels from last month. Production is expected to recover from last season’s record lows on higher harvested acreage, which is partly offset by a lower yield as compared with last year. Area harvested for grain is forecast at 3.3 million acres, unchanged from last month’s forecast and up from 2.2 million last season. On August 5, 61 percent of this year’s U.S. crop was rated in good-to-excellent condition, compared with 72 percent a year ago.
Total projected barley supplies in 2012/13 are raised 14.3 million bushels this
month to 306 million, as a result of higher production due to improved yields and
higher expected imports. Domestic use is projected at 235 million bushels, 25
million bushels over last month. Exports are unchanged from last month’s
projection of 10 million bushels. With gains in supply more than offset by higher
use, this month’s ending stocks are projected down 11 million bushels to 61 million,
compared with 60 million estimated in 2011/12.
U.S. Census Bureau revisions for calendar year 2011 increase barley exports for 2010/11 slightly. Exports for 2011/12 are raised 2 million bushels this month based on the latest trade data and revisions. Imports are raised 2 million bushels for 2011/12 to 16 million based on the same data.
Prices received by farmers for barley in 2012/13 are expected to average $5.75- $6.75 per bushel, raised 45 cents on both ends of the range this month. This compares with $5.35 per bushel reported for 2011/12. Although prices for feed barley are expected to increase largely in line with those for corn and sorghum, price gains will be moderated for malting barley, as much of the crop is produced under contract at prices established earlier in the year.
Early Maturing Oat Crop Is Second Smallest on Record
Earlier than normal plantings combined with persistent heat in June and July
contributed to an early maturing 2012/13 oat crop. As of August 6, fully 87 percent
of the oat crop in the nine major producing States had been harvested, up 14 percent
from the previous week and up 43 percent over the same time last year.
Despite reports of droughty conditions in several of the major oat-growing areas of the United States, on July 22, the oat crop was rated as 59 percent good to excellent- -a modest improvement over conditions observed during the same time period last year. Just 12 percent of the crop in the nine-State area was rated as poor to very poor, compared with 24 percent for the same week in 2011/12.
Improved quality and increased plantings contributed to growth in the 2012/13 production estimates. The total oat crop is forecast to be 67 million bushels, an increase of 24 percent over last year’s weak harvest of just 5 million bushels. Even with significant year-to-year growth, the 2012/13 oat crop will be the second smallest on record. The 2011/12 crop was the smallest crop ever recorded.
Harvested acreage is forecast to total 1.09 million acres, an increase of 16 percent relative to last year’s harvested acreage of 0.94 million acres. Over the last 10 years, an average of 1.50 million acres of oats has been harvested; this year’s improved harvest acreage figures are still well below trend but are consistent with a 30-year decline in oat acreage.
Average yields are forecast at 61.0 bushels per acre, a modest increase over the July forecast of 59.8 bushels and an increase of 3.9 bushels over the 2011/12 estimate. Irrigation is contributing to yield gains in several States, including Texas, where a record high-yield of 54.0 bushels per acre is forecast.
Total 2012/13 oats supplies are raised slightly to a projected 217 million bushels. This compares to an estimated 215 million bushels for 2011/12. Projected oats use for 2012/13 is raised 5 million bushels to 164 million. Oats imports are projected at 95 million bushels, unchanged this month.
Revised U.S. Census Bureau figures for calendar year 2011 and the latest monthly
data reduce 2011/12 oats exports 15 percent from last month to 2.43 million bushels. This compares to a revised estimate of 2.85 million bushels for 2010/11.
Census data lower the 2011/12 oats import estimate 1 million bushels to 94.1
million. This is up from 85.1 million for 2010/11.
Projected FSI use for 2012/13 remains unchanged from July and is identical to the previous year’s estimate of 76 million bushels. With tight feed grain supplies and high corn prices, 2012/13 feed and residual use of oats is forecast up 5 million bushels this month to 85 million. The increase in use more than offsets the increase in production, trimming projected 2012/13 ending stocks 4 million bushels to 53 million. This is down slightly from the previous year.
Tightening domestic feed grain supplies are contributing to a higher anticipated average farm price for oats. At the projected range of $3.50-$4.50 per bushel, the 2012/13 season-average price is up $0.51 at the mid-point, compared with the previous year’s estimate of $3.49 per bushel. The average farm price for the 5 years prior to 2012/13 is $2.76 per bushel.
Poor Hay Crop Prompts Federal Response
Prolonged drought conditions continue to contribute to low soil moisture levels in
many parts of the country and have resulted in the lowest hay production estimates
seen in the U.S. since 1953. This year’s forecast harvest of 120.3 million tons (all
hay) follows the meager harvest of 131.1 million tons 2011/12. In response to the
poor hay crop, Secretary Vilsack has opened approximately 3.8 million acres of
Conservation Reserve Program (CRP) lands, including higher yielding CP25 lands,
for emergency haying and grazing.
Hay yields have been adversely affected by the drought and the all-hay yield is anticipated to be 2.09 short tons per acre, down from 2.36 in 2011. The 2012/13 all hay yield is about 14 percent smaller than the 10-year average yield of 2.42 tons per acre. Harvested acres for 2012/13 are forecast at 57.57 million acres, up slightly (1.94 million acres) from last year’s estimate and down very slightly from the July forecast.
Alfalfa hay production is forecast at 54.9 million tons, down more than 10 million tons relative to last year’s production of 65.3 million tons. Based on August 6 crop conditions, yields are expected to average 2.92 tons per acre, down 0.48 tons per acre from last year. If realized, this will be the lowest yield since 1988, when alfalfa yields were estimated at 2.59 tons/acre. Harvested area is forecast at 18.8 million acres, nominally changed from July and down only slightly from last year’s harvested area estimate of 19.2 million acres.
Other hay production is forecast at 65.4 million tons, and is very similar to realized production from the 2011/12 crop. Based on early August conditions, other hay yields are expected to average 1.69 tons per acre, a slight decrease from last year’s estimate of 1.81 tons per acre and the lowest yield since 1988 when a yield of 1.48 tons per acre was realized. Harvested area, forecast at 38.8 million acres, is unchanged from July but up 2.34 million acres from last year.
For the sixth year in a row, roughage-consuming animal units (RCAUs) are estimated to be down. RCAUs are expected to total 67.03 in 2012/13, a decline from the 2011/12 estimate of 67.91. With hay production dropping significantly, available supplies per RCAU also declined from 1.94 tons in 2011/12 to 1.79 tons in 2012/13. This is the lowest hay supply per RCAU ratio in more than 25 years. Scarce hay supplies have driven prices higher. The July 2012 all-hay price was $184 per ton, compared to the July 2011 price of $170 per ton. July alfalfa prices have also increased from $189 per ton last year to $198 in 2012. The July estimate for hay other than alfalfa and alfalfa mixtures is $143 per ton, up from $133 in June 2012 and up significantly from the July 2011 price of $119 per ton.
Foreign Coarse Grain Production Decline Adds to U.S. Drop
World coarse grain production for 2012/13 is projected down 62.2 million tons this
month to 1,121.4 million, with the United States accounting for 93 percent of the
drop. However, foreign coarse grain production is forecast down 4.3 million tons to
835.4 million. Expected foreign corn production is down 0.6 million tons this
month to 575.2 million, as several large changes are mostly offsetting. Foreign
barley production prospects are down 1.2 million tons to 126.0 million, as reduced
prospects for Russia and the EU are partly offset by increased output in Ukraine.
Foreign millet production is cut 2.5 million tons to 30.9 million, and sorghum
production is trimmed 0.3 million tons to 52.9 million due to a subpar monsoon in
India. Oats, rye, and mixed grain are each up slightly this month.
Changes to foreign production prospects stem from two distinct causes. Recent weather developments have confirmed above or below trend yields in several countries. And some countries, especially in the Southern Hemisphere, are responding to recent price increases with expanded planting intentions.
EU 2012/13 corn production is forecast down 3.9 million tons this month to 61.5 million, as drought and blistering temperatures struck across key areas of the Balkans into Italy. Corn conditions along the Danube in Romania and Bulgaria had been particularly good due to ample rains in May, but dryness in June was exacerbated by extreme heat in July, devastating corn pollination. Dryness and high temperatures extended across Romania, into Hungary and Serbia, and westward into northern Italy. However, in France, growing conditions have been mostly favorable with mild temperatures and good soil moisture during pollination. EU corn production this month is projected down 2.3 million tons for Romania, 1.5 million for Hungary, 0.9 million for Italy, and 0.3 million for Bulgaria; it is increased 1.0 million for France (with some smaller adjustments in other countries). EU barley production is reduced 0.7 million tons this month to 52.9 million, mostly due to reduced prospects in Spain, where harvest reports confirm the effects of extended dryness. Ample rains across northern and parts of central Europe boost prospects slightly for rye, oats, and mixed grain.
Serbia’s (not part of the EU) 2012/13 corn production is cut 1.5 million tons to 5.5 million, Croatia’s is reduced 0.4 million to 1.7 million, and Bosnia’s is trimmed 0.2 million to 0.5 million. Europe’s dryness and scorching temperatures extended eastward from Romania across Moldova, into southern Ukraine, and across into Russia, especially around Rostov. Corn in north-central Ukraine has had milder temperatures and somewhat better soil moisture, but the poor condition of the corn in southern and eastern Ukraine supports a 3.0-million-ton reduction in 2012/13 production to 21.0 million. Russia’s corn crop is cut 0.8 million tons to 7.0 million, and Moldova’s corn crop prospects are reduced 0.4 million tons this month to 1.0 million. Russia’s dryness extends through parts of the Volga, across the Urals into Kazakhstan and Siberia. Spring barley prospects are reduced 1.0 million tons in Russia, to 14.5 million, and rye is trimmed 0.3 million to 2.7 million. Kazakh barley prospects are trimmed 0.3 million tons to 1.5 million. However, harvest reports in Ukraine support increased barley production, up 0.6 million tons to 6.6 million, and rye, up 0.2 million to 0.65 million, as growing conditions in western and northern parts of the country have been favorable.
In India, the late onset of the monsoon and reduced water supplies for irrigation
have caused a reduction in coarse grain planted area. Corn production prospects are
cut 2.0 million tons to 20.0 million, millet is cut 2.5 million to 10.0 million,
sorghum is trimmed 0.3 million to 6.4 million, and the barley harvest is
reduced slightly.
Turkey reported barley yields lower than expected, reducing production 0.3 million tons to 5.5 million. Dryness in parts of Ontario supports a small reduction in corn yields for Canada, trimming production 0.25 million tons to 12.75 million.
Excessive rains in North Korea trimmed corn yield prospects, reducing production 0.1 million tons to 1.45 million. Declining production prospects are partly offset by increased production expected in some countries due to better than average weather. The 2012/13 corn production forecast for China is raised 5.0 million tons to a record 200.0 million on expectations of enhanced yield prospects. Favorable precipitation and temperatures during June and July in the Northeast, particularly in the provinces of Heilongjiang, Jilin, and Inner Mongolia, are the primary basis for the increase. Figure 10 illustrates the deviation from normal June and July rainfall for the three aforementioned provinces weighted by harvested area. These provinces accounted for 30 percent of Chinese corn area in 2010.
Corn production prospects in Mexico are increased 0.5 million tons this month to 21.5 million, as favorable rains boosted soil moisture and attractive prices encouraged increased area planted. Algeria’s barley crop was reported up 0.2 million tons to 1.8 million, with increased yields.
Several Southern Hemisphere countries are expected to respond to high corn prices with increased planted area. In Argentina, corn area is expected to increase 6 percent in 2012/13, as corn prices are attractive. Previous USDA forecasts assumed a 6-percent decline in corn area planted, as producers were expected to shift to soybeans. It is unclear what, if any, effect the government’s export policy changes this month. Corn production is increased 3.0 million tons to 28.0 million, and barley expands 0.4 million tons to 5.8 million. Also, 2010/11 corn production is raised 1.6 million tons this month as exports and estimated domestic use indicate larger production.
Brazil’s corn production response to high international prices is expected to vary
depending on region and cropping cycles. For the first or main-season crop in
southern Brazil, soybean area is expected to expand at the expense of corn
plantings. However, this is expected to be more than offset by the increased
incentive to double crop corn after soybeans in Parana, and in regions where
soybeans and corn doubled-cropped area is expanding, especially Mato Grosso and
parts of the Northeast. Total corn area for 2012/13 is projected up 5 percent yearto-
year, boosting production prospects 3.0 million tons this month to 70.0 million.
Also, government estimates of the recently harvested second-crop corn for 2011/12
showed sharply higher than expected yields, as late rains extended into the dry
season and boosted yields. Production for 2011/12 is up 2.8 million tons this month
to a record 72.8 million tons. This is the first year that second-crop corn in Brazil
has been bigger and higher yielding than the first crop.
South Africa is expected to respond to high prices and tight supplies with an increase in planted area, boosting projected corn production 0.5 million tons to 13.5 million.
Increased 2012/13 Beginning Stocks Limit Drop in Supplies
Global coarse grain beginning stocks for 2012/13 are up 5.8 million tons this month
to 168.5 million. About half of the increase is in foreign stocks, up 2.8 million tons
to 139.8 million. The most important change is for corn in Brazil, up 2.8 million
tons to 15.9 million due to increased 2011/12 production. Other changes to 2012/13
beginning stocks are smaller and offsetting. Coarse grain beginning stocks are up
0.5 million tons each for the EU and Argentina and are increased 0.3 million for
Egypt, but are cut 0.5 million for Australia, 0.4 million for Mexico, and 0.3 million
each for Canada and Indonesia.
Despite the severe U.S. production problems in 2012/13, projected world coarse grain supplies are only down 2 percent year-to-year to 1,289.9 million tons, and are less than a half percent less than in 2010/11. However, estimated global coarse grain use has increased for each of the last 9 years, and it will take record-high prices to reverse that growth in 2012/13.
High Prices To Reduce Global Coarse Grain Use
World coarse grain use in 2012/13 is projected down 43.1 million tons this month, a
4-percent reduction. Much of the reduction is in forecast U.S. use, but foreign
consumption is projected down 12.3 million tons as high prices shrink demand.
The reaction of foreign demand to the U.S. corn production shortfall is muted by
several factors: (1) several countries, such as China and Brazil, have domestic
production and stocks that cushion their domestic market from the full impact of
international prices, (2) some countries, such as China, have tariff barriers and
import quotas that limit the transmission of international prices, (3) economic
growth and increased incomes is some countries support increased meat demand
despite higher prices, (4) for the past several years, sustained, relatively high grain
prices have encouraged importers to diversify the countries they import from, and (5) foreign export competitors have increased production and market share, leaving
importers less dependent on U.S. corn. Each country has unique coarse grain
supply and demand characteristics, making it uncertain how much and when the
demand in that country will adjust to international prices.
Global coarse grain use in 2012/13 is expected to decline for the first time since 2002/03, slipping 0.7 percent to 1,137.8 million tons. World feed and residual use is forecast to increase year-to-year 1.4 million tons to 659.9 million, while food, seed, and industrial use declines 9.3 million tons to 477.9 million. Foreign feed use in 2012/13 is projected at 551.3 million tons, down 10.5 million from the previous month’s forecast but still up 12.7 million tons from feed use projected for 2011/12, when foreign feed-quality wheat was in ample supply in several countries. Some foreign consumers of feed, such as those in China, do not face price increases as steep as those in the United States because their internal market is at least partly isolated from world prices. In other countries, like Brazil, large domestic production limits internal price increases. In countries like Japan, consumers are accustomed to paying higher prices for meat, and derived demand for grain feed use may be relatively price inelastic.
EU 2012/13 coarse grain use is projected down 3.9 million tons this month to 149.0 million, with reduced feed and residual accounting for 3.4 million tons of the decline. Reduced corn production is expected to cause a shift in feed use to wheat, up 1.0 million tons this month, but most of the drop is expected to be caused by reduced meat production as financial losses cause a reduction in previously stagnating animal production.
India’s expected coarse grain disappearance is reduced 3.7 million tons this month due to reduced production. Feed and residual is expected to be down significantly, 1.1 million tons, as poultry and egg production is constrained by high grains and protein meal prices. However, most of the decline, 2.6 million tons, is in food, seed, and industrial use, with coarse grain food use concentrated among the rural poor. Wheat food use is increased 1.3 million tons, offsetting half of the decline. Russia’s coarse grain consumption is forecast down 1.6 million tons this month to 26.6 million, with 1.3 million in reduced feed and residual. Meat production growth is expected to stumble as numerous small pork producers in regions with grain production shortfalls are forced to reduce production.
Japan’s corn feed use forecast for 2012/13 is reduced 0.5 million tons as the previously forecast rebound in corn feeding is no longer expected to be as strong, with sharply higher feed prices.
Canada’s coarse grain use for 2012/13 is reduced 0.5 million tons this month as high grain prices trim meat production prospects. Food and industrial use of corn is projected higher this month based on upward revisions for 2011/12 industrial use. South Korea’s and Vietnam’s corn feed use are each reduced 0.5 million tons and Israel is trimmed 0.4 million as these countries are expected to import more wheat for feeding and less corn. There are also reductions in forecast coarse grain use this month for Indonesia, Turkey, Serbia, Croatia, Syria, Ukraine, Peru, Colombia, and Algeria.
Argentina’s expected coarse grain domestic use is increased 0.6 million tons this month, mostly due to expanded barley processing to support malt exports.
U.S. Stocks Sharply Lower; Brazil, China, and Argentina Increased
Global coarse grain ending stocks projected for 2012/13 are cut 13.4 million tons
this month to 152.1 million. The U.S. accounts for the entire reduction as foreign
stocks are forecast up 0.8 million tons to 132.9 million. While several foreign
countries are expected to react to record world corn prices by drawing down stocks
to cushion the effect of prices on use, in Brazil, China, and Argentina, increased
production is projected to support increased stocks.
In Brazil, record 2011/12 corn production and near-record prospects for 2012/13 support corn supplies. Moreover, high interior transport costs to move corn to ports and competition with bumper 2012/13 soybean supplies for space in congested ports are expected to limit corn exports, leaving significant stocks of corn in interior locations like Mato Grosso at the end of the local 2012/13 marketing year (March 2014). Coarse grain ending stocks are forecast up 3.8 million tons this month to 17.1 million.
Argentina is expected to move much of its corn surplus into exports, but the sharply increased production still boosts expected 2012/13 ending stocks of coarse grain 0.8 million tons this month to 3.0 million.
China, with a record corn harvest in 2012/13, is expected to increase coarse grain stocks even with reduced imports. Coarse grain stocks are up 2.0 million tons this month to 61.0 million.
Egypt, with higher estimated 2011/12 corn imports, is expected to hold higher stocks in 2012/13, as beginning stocks are increased 0.3 million tons this month to 1.3 million and ending stocks are up 0.1 million to 1.1 million.
However, several countries are projected to respond to higher world prices and/or reduced local production prospects by holding lower ending stocks in 2012/13. EU coarse grain ending stocks are projected down 0.9 million tons this month to 10.0 million, less than 40 percent of the level estimated 3 years earlier. India, with large government stocks of wheat and rice, is expected to let coarse grain stocks dwindle, down 0.9 million tons this month to 0.8 million. Serbia, with corn production devastated by drought, is projected to pull coarse grain stocks to minimal levels, down 0.75 million tons this month to 0.35 million. With tight U.S. supplies of corn and sorghum, Mexico is expected to rebuild coarse grain stocks less than previously projected, with 2012/13 ending stocks prospects down 0.6 million tons this month to 1.7 million. Ukraine, with reduced corn production this month, is projected to hold lower coarse grain ending stocks, down 0.6 million to 2.3 million. Ending stocks prospects are down 0.5 million tons each for Australia and Canada, as increased export prospects for 2011/12 in Australia, and for both 2011/12 and 2012/13 for Canada, trim stocks. Smaller reductions in coarse grain ending stocks are projected this month for Russia, Indonesia, Moldova, Colombia, Algeria, and others.
U.S. Corn Exports, World Trade Prospects Severely Cut
With U.S. production prospects withered by drought, U.S. corn exports for the
October-September trade year 2012/13 are cut 6.5 million tons this month to 33.5
million (a reduction of 300 million bushels to 1.3 billion bushels for the September-
August local marketing year). This is the lowest level of U.S. corn exports since
1993/94, when global corn trade was 47 percent less than projected for 2012/13.
World corn trade is forecast down 6.6 million tons this month to 90.9 million, as
some other major corn export competitors also suffered production problems.
Ukraine’s corn export prospects are down 1.5 million tons to 12.5 million; the EU is cut in half, down 1.0 million tons to 1.0 million; Serbia is reduced 0.5 million to 1.3 million; Croatia is down 0.75 to 0.25; and Moldova is trimmed 0.25 million to 0.1 million. Offsetting most of the non-U.S. reductions are increased corn exports projected in 2012/13 for Argentina, up 2.0 million tons to 17.5 million; Brazil, up 0.5 million to 13.0 million, South Africa, up 0.3 million to 2.3 million; and Canada, up 0.2 million to 1.0 million. These countries are expected to have sufficient supplies to respond to higher corn price prospects with increased exports.
High corn prices are expected to limit imports for several countries. China’s projected imports are cut 3.0 million tons to 2.0 million as the price of foreign corn landed in southern China is expected to be unattractive compared to corn produced in China. Some of the previously bought corn for delivery to China in 2012/13 may be sold back to U.S. exporters or diverted to non-Chinese destinations with a significant profit for the Chinese trader, as those contracts were made when prices were significantly lower. EU corn import prospects are cut 2.0 million tons to 3.0 million as grain prices in the EU are not expected to be as strong as the increase in global corn prices. Corn imports are reduced 0.5 million tons each for Indonesia, Japan, South Korea, Morocco, Mexico, and Vietnam. South Korea and Vietnam are expected to replace corn with imports of feed-quality wheat. Japan is not expected to increase the portion of corn in compound feed as previously forecast. In Mexico, disease problems in poultry and the high corn prices are expected to reduce corn demand, and in Indonesia, high prices will limit imports. Israel is also expected to switch to feed quality wheat, trimming corn imports 0.35 million tons. There are smaller import reductions for Colombia, Peru, and Algeria.
The United States is expected to emerge as a significant corn importer in 2012/13. Imports, while small compared to exports, are projected up 1.2 million tons to 1.9 million (up 45 million bushels for the local marketing year to 75 million bushels). Corn seed imports are expected to increase as local seed production in several areas has been hurt by drought. The routine imports of corn from Canada are expected to increase, and some imports from other origins, such as Brazil, are expected to enter feed deficit regions such as North Carolina or California.
There are small increases in projected corn imports this month for Libya, where imports for both 2011/12 and 2012/13 are returning to traditional levels faster than expected, and for Croatia, with corn production stricken by drought.
U.S. corn exports for 2011/12 are reduced 1.0 million tons to 39.0 million (down 50 million bushels to 1.55 billion bushels for the local marketing year). The pace of sales and shipments has been exceptionally slow in recent weeks as increased prices have made U.S. corn unattractive compared to competitors’ supplies. From October 2011 through June 2012 Census corn exports reached 34.7 million tons, down just 10 percent from the previous year, but in July 2012, corn exports according to Grain Inspections reached only 2.3 million tons, down more than 40 percent from a year ago. Moreover, at the end of July, Corn Outstanding Sales for shipment during the current marketing year were also down 40 percent from last year at this time.
However, world corn trade for 2011/12 is estimated up 1.5 million tons this month to a record 98.5 million. The strong pace of recent shipments boosts Argentina’s exports 1.5 million tons to 16.0 million. Ukraine’s corn exports are up 0.5 million tons to a record 14.5 million. The pace of recent exports also supports small increases for 2011/12 for South Africa, Canada, the EU, and Serbia. The recent pace has boosted 2011/12 imports for Mexico, up 0.7 million tons to 11.2 million; Egypt, up 0.5 million to 5.5 million; and South Korea, up 0.5 million to 7.5 million.
However, there are reductions to 2011/12 corn imports for Indonesia and Syria. U.S. corn imports for 2011/12 are raised 0.1 million tons to 0.65 million (up 3 million bushels to 25 million bushels for the local marketing year). Corn imports have been unexceptional in 2011/12, consisting of mostly of routine shipments of seed and cross-border trade with Canada.
U.S. 2012/13 Sorghum Export Prospects Cut, Barley Imports Raised
U.S. sorghum exports for world barley trade were small, but Australia’s 2011/12 exports are revised up 0.5 million tons this month to 5.0 million, confirming it as the world’s largest barley exporter that year.
August 2012
Published by USDA Economic Research Service
DOWNLOAD REPORT:- Download this report here | http://www.thepoultrysite.com/reports/?id=807&country=US | CC-MAIN-2018-22 | refinedweb | 6,959 | 67.86 |
public key cryptography (ECC) with libgcrypt More...
#include "platform.h"
#include <gcrypt.h>
#include <sodium.h>
#include "gnunet_crypto_lib.h"
#include "gnunet_strings_lib.h"
#include "benchmark.h"
Go to the source code of this file.
public key cryptography (ECC) with libgcrypt
Definition in file crypto_ecc.c.
Definition at line 34 of file crypto_ecc.c.
IMPLEMENTATION NOTICE:
ECDSA: We use a non-standard curve for ECDSA: Ed25519. For performance reasons, we use cryptographic operations from libsodium wherever we can get away with it, even though libsodium itself does not support ECDSA. This is why the sign and verifiy functionality from libgcrypt is required and used.
EdDSA: We use a standard EdDSA construction. (We still use libgcrypt for hashing and RNG, but not EC)
ECDHE: For both EdDSA and ECDSA keys, we use libsodium for ECDHE due to performance benefits over libgcrypt. Name of the curve we are using. Note that we have hard-coded structs that use 256 bits, so using a bigger curve will require changes that break stuff badly. The name of the curve given here must be agreed by all peers and be supported by libgcrypt.
Definition at line 59 of file crypto_ecc.c.
Definition at line 61 of file crypto_ecc.c.
Definition at line 63 of file crypto_ecc.c.
Definition at line 66 of file crypto_ecc.c.
Log an error message at log-level 'level' that indicates a failure of the command 'cmd' with the message given by gcry_strerror(rc).
Definition at line 74 of file crypto_ecc.c.
Extract values from an S-expression.
Definition at line 96 of file crypto_ecc.c.
Convert the given private key from the network format to the S-expression that can be used by libgcrypt.
Definition at line 154 of file crypto_ecc.c.
References CURVE, GNUNET_CRYPTO_EcdsaPrivateKey::d, GNUNET_assert, GNUNET_ERROR_TYPE_ERROR, LOG_GCRY, and result.
Convert the data specified in the given purpose argument to an S-expression suitable for signature operations.
Definition at line 512 of file crypto_ecc.c. | https://docs.gnunet.org/doxygen/dc/dba/crypto__ecc_8c.html | CC-MAIN-2022-40 | refinedweb | 324 | 61.33 |
COMMUNITY FORUM
Scripting to upload file to SFTP
in regards to SFTP uploading files that have been output by smartconnect.
In our test environment I’m dropping files with a static filename , then firing a smartconnect script
which copies to another location and renames the files to include formatted date and timestamps
I want to tag onto this a SFTP upload and I think possibly winSCP is the tool of choice.
Before I head off down this route I thought it would be a good Idea to check in here first for
any feedback.
Thanks In Advance
If it is just an assembly, you can use the ScriptNamespaces window in order to add a reference to it.
then code normally.
or if it has an exe component, you could call that via .NET without the reference.
Hey Patrick , thanks for the response
Here’s a link fyi
looking into the ScriptNamespaces now
Hi Patrick we are on version 20.14.1.25 and I don’t see the script namespaces in the generic connection section of the toolbar
could this be a version or permissions issue
That window does not exist in SC 2014. However the table does and you could insert the record into it manually.
Thanks Patrick , that’s good news
ok cool so it’s inbuilt functionality in 2014 that was just not exposed via the GUI :).
so I took a look the columns are as below
I’m just not sure about the IsSystem column
would the below be deemed a correct useable entry ?
all other entries have IsSystem= 1 but I thought that might be a smartconnect is internal flag or something
ScriptNamespaceId = ‘WinSCPnet’
AssemblyPath= ‘d:\Program Files (x86)\WinSCP-portable\WinSCPnet.dll’
IsSystem= 0
assuming the ScriptNamespaceId is correct, isSystem = 0 is ok I think.
you can try using a path like that.
personally i’d copy the file into the SC folder and also put it in the GAC | https://www.eonesolutions.com/discussion/scripting-to-upload-file-to-sftp/ | CC-MAIN-2022-27 | refinedweb | 326 | 68.7 |
Building a Study Guide App with Java Hashmap
Free JavaScript Book!
Write powerful, clean and maintainable JavaScript.
RRP $11.95
These days, the idea a physical dictionary is pretty old-fashioned. Consulting a physical book to learn the meaning of a word or phrase makes no sense when a simple Google search will give you all the information you need.
But a dictionary is a very useful metaphor for an important programming concept: key-value pairs. Dictionaries operate by linking a word (a “key”) to its meaning (a “value”). This key-value pair is a fundamental data model in programming.
Most programming languages use hashes to ensure the uniqueness of keys and make storage and retrieval of values more efficient. A
HashMap in Java puts all of that together to allow programmers to store key-value pairs by hashing their keys upon insertion and retrieval.
In this tutorial, we’ll learn how to build a study guide program by storing Java concepts and their corresponding meanings in a HashMap to be retrieved when it’s time to study. The source code for this tutorial can be found here
HashMap
Java maps make programs more efficient by storing key-value pairs in a single data structure. Alternatively, the same could be accomplished with two manually synced data structures — one holding keys and the other holding values — but this isn’t the best approach to mapping keys to values; that’s what a
Map is for. The
HashMap is arguably one of the most powerful of them all. All keys of the map must be of the same type, as must its values.
In the background, Java’s HashMap class stores the pairs in arrays, but we don’t have to worry much about the implementation because much of the heavy lifting is encapsulated.
The
Map interface provides methods for putting pairs in the map, replacing the value of pairs, removing pairs by key, checking for the existence of a pair by key, and clearing the map. We’ll make use of almost all of those functions today.
The Application
Our app will be a simple study guide app. We’ll build our
HashMap to store our concepts and use Java control-flow statements to loop until we have provided the correct meaning for each concept. Let’s build!
Classes
We’ll need two classes to run our study guide application. The first class will be our main class to run our program and the second will be another class to model the meaning of Java concepts and encapsulate a couple of fields and methods to simplify the study guide interface.
The first thing we need to do is create a new Java project with a main class. Once we have that set up, let’s go ahead and build our
Meaning class that will be used in our
Main.
Meaning Class
Create a new class called “Meaning”. We won’t be diving into this class, but let’s go over the importance of it. This class will model the meaning of Java concepts to be studied by holding their meaning and tokens of that meaning. Here are its important parts:
public class Meaning { /*if a user's guess at the meaning matches at least 65% of the actual meaning of a Meaning, the user is correct.*/ private static final double CORRECTNESS_THRESHOLD_PERCENTAGE = .65; //the string representation of this meaning private String meaning; //whether or not the user's input matches this meaning private boolean gotCorrect; //holds the tokens of the meaning private String[] meaningTokens; //the constructor public Meaning(String meaning) { this.meaning = meaning; tokenizeMeaning(); } //omitted ... /** * This is a naive lexical analyzer * that counts how many words match * between the user input and this meaning. * * There are many ways to improve this. * @param userInput the user's guess at what this concept means * @return true if the user's input matches * this meaning. */ public boolean userInputMatches(String userInput) { //make sure the user's input is not empty if(userInput != null && !userInput.isEmpty()) { int numMatchedTokens = 0; userInput = removeAllPunctuation(userInput); String[] userInputTokens = userInput.split(" "); //total tokens. The greater of the two int totalTokens = Math.max(userInputTokens.length, meaningTokens.length); /*get the number of matched tokens between the two sets of tokens.*/ numMatchedTokens = getNumMatchedTokens(userInputTokens); //cast to a double to get floating point result double matchPercentage = ((double)numMatchedTokens / totalTokens); //return whether or not the matched percentage meets the threshold return matchPercentage >= CORRECTNESS_THRESHOLD_PERCENTAGE; } //return false because the user's input is empty return false; } //omitted ... }
To construct a new
Meaning instance, we pass the meaning of a concept to the constructor. From there, the meaning will be tokenized and stored in an array for us to use when checking if the user’s input matches the meaning of the concept.
When the program runs, the user will be asked to input a guess at the meaning of a concept, and we’ll use that input to check if the user is correct by calling the
userInputMatches() instance method of
Meaning. This method will tokenize the user’s input and loop through the meaning’s tokens and the user’s input tokens to count their matches in order. We’ll return true if 65% of the meaning’s tokens are matched by the user’s input tokens; this means the user answer is correct and so they get a point.
That’s all we need
Meaning for, but you can view the full class in the supporting code for this tutorial.
Main Class
Our study guide will run in the main class. Feel free to call this class whatever you want, but I’ll call mine “StudyGuide”.
public class StudyGuide { //omitted ... //initialize a HashMap to hold String-Meaning (key-value) pairs. private static final HashMap<String, Meaning> studyGuide = new HashMap<>(); /*The total possible points the user can obtain. Equal to the number of concepts in the study guide.*/ private static int possiblePoints; //our main method to start our app public static void main(String[] args) { populateStudyGuide(); printInstructions(); study(); } //omitted ... }
Our
StudyGuide class begins pretty humbly. We start by initializing a
final static HashMap called
studyGuide as our study guide. All the keys of
studyGuide, representing our concepts, will be of the
String type while the values, the meanings of our concepts, will be of our custom
Meaning type.
We begin our app by calling
populateStudyGuide to populate
studyGuide with concept-meaning pairs:
/** * Populates the study guide with Java concepts. */ private static void populateStudyGuide() { //add a bunch of studyGuide.put("Variable", new Meaning( "Used to store a single value for later use.")); studyGuide.put("String", new Meaning( "A class for representing character strings.")); studyGuide.put("double", new Meaning( "A primitive datatype for representing floating point numbers.")); studyGuide.put("Double", new Meaning( "A class for wrapping a double in an Object with convenient methods.")); studyGuide.put("zero", new Meaning( "The number zero. The first index in arrays and the first position of lists.")); //set the possible points updatePossiblePoints(); }
There, we call the
put() instance method of our
HashMap five times, putting a concept and its meaning in
studyGuide each time. This method ends by calling
updatePossiblePoints() to set the possible points,
static possiblePoints, obtainable by a user:
private static void updatePossiblePoints() { possiblePoints = studyGuide.size(); System.out.println("There are " + possiblePoints + " concepts to study."); }
Note that
possiblePoints should always be equal to the number of elements in
studyGuide which we can gather by calling its
size() instance method.
Next, we call
printInstructions() to print our app’s instructions to the console for the user. After that, it’s time to study:
/** * Starts the study session */ private static void study() { //for scanning the user's keyboard for input Scanner userInputScanner = new Scanner(System.in); //to store the user's input String userInput; /*the points obtained by the user for getting the meanings of concepts correct.*/ int userPoints = 0; /*how many rounds the user takes to get all of the concept meanings correct*/ int rounds = 1; //set the default user input because the while loop needs to check it userInput = "startInConsole"; /*We'll let the user quit at any point in the app, so we must make sure they haven't quit yet*/ while(userPoints < possiblePoints && !userQuit(userInput, userPoints)) { //store the keys of the study guide in a immutable Set final Set<String> concepts = studyGuide.keySet(); for (String concept : concepts) { Meaning currentConceptMeaning = studyGuide.get(concept); //make sure currentConceptMeaning is not null if(currentConceptMeaning == null) { studyGuide.remove(concept); //move to next iteration continue; } if(!currentConceptMeaning.userGotCorrect()) { System.out.printf("\n\t\t" + OUTPUT_SEPERATOR_LINE + "\n\n> What is %s?\n\n\n", concept); if(userInputScanner.hasNextLine()) { userInput = userInputScanner.nextLine(); } if (!userQuit(userInput, userPoints)) { if (currentConceptMeaning.userInputMatches(userInput)) { currentConceptMeaning.markUserGotCorrect(); userPoints++; System.out.printf("\n> CORRECT! %s means: %s", concept, currentConceptMeaning.getMeaning()); } else { System.out.printf("\n> WRONG! %s means: %s", concept, currentConceptMeaning.getMeaning()); } } } } System.out.println(OUTPUT_SEPERATOR_LINE); System.out.printf("\n> You have %d of %d possible points at the end of round %d. ", userPoints, possiblePoints, rounds); //make sure the user hasn't scored all of the possible points if(userPoints < possiblePoints) { System.out.println("\n> Type anything to continue " + "OR remove to remove a concept \"x\" or \"quit\" to quit?"); if(userInputScanner.hasNextLine()) { userInput = userInputScanner.nextLine(); if(userInput.toLowerCase().equals("remove")) { System.out.println("\n> Remove which concept?"); if(userInputScanner.hasNextLine()) { removeConcept(userInputScanner.nextLine()); } } } } else break; //break out of the loop because the user is done } System.out.println(OUTPUT_SEPERATOR_LINE); System.out.println("Congrats! You got all the meanings correct."); }
We start studying by calling the
study() method. This method declares a couple of variables to hold information about the user’s study session. We initialize a
Scanner as
userInputScanner to capture the user’s input, which will be stored in
userInput. The user’s accumulated points will be stored in
userPoints and incremented by 1 each time the user provides the right meaning for a concept.
We use a
while loop to continue prompting the user with concepts so long as they haven’t obtained the possible points and they do not enter “x” or “quit” to quit.
At the top of the
while loop, we must store the
Set of keys in
studyGuide in a constant by calling its
keySet() instance method so that we can iterate over it. For each key, we get its value by calling the
get() instance method of
studyGuide and passing it the key. The value returned and stored in
currentConceptMeaning is a
Meaning instance representing the meaning of a concept. So long as the
currentConceptMeaning is not
null, we let the user take a guess at what they think it is. If the
userInputMatches() instance method of
currentConceptMeaning returns
true, we call its
markUserGotCorrect() instance method to set its
gotCorrect instance field to true and increment
userPoints because the user provided the correct meaning for the concept.
At the end of each round, we print out how many points the user has accumulated and we allow them to remove a concept they give up on studying if they haven’t finished the study guide; we do this by calling our
removeConcept() method:
/** * This allows the user to remove a concept they give up on from the study guide. * Removes the pair from the HashMap with a key that matches the concept. * @param concept */ private static void removeConcept(String concept) { Meaning conceptMeaning = studyGuide.get(concept); if(conceptMeaning != null) { //make sure the user hasn't already gotten the meaning correct if(!conceptMeaning.userGotCorrect()){ //remove the concept's key-value pair from the study guide studyGuide.remove(concept); System.out.println("Removed \"" + concept + "\" from your study guide."); /*update the possible points so that it matches the number of concepts left in the study guide*/ updatePossiblePoints(); } else { //don't let the user remove a concept they already know System.out.println("You know \"" + concept + "\", silly. Can't remove."); } } else { System.out.println("\"" + concept + "\" isn't in your study guide."); } }
When we call
removeConcept(), it gets the
Meaning value corresponding to the concept in
studyGuide as
conceptMeaning. If the concept is found, we call the
userGotCorrect() instance method of
conceptMeaning to check if the user got the meaning of the concept correct, and if this returns
false, we call the
remove() instance method of
studyGuide() to remove the key-value pair from the
HashMap by the concept as the key. We don’t let the user remove a concept that they already correctly defined because they already received points for it.
Our
userQuit() method checks if the user asked to quit at any point to end the program and print out the user’s points. On the other hand, if the user makes it to the end of the study guide, we call
break to break out of the
while loop. At that point, the app will congratulate the user on a successful study session and the program will end.
Conclusion
Well look at that, we’re all done! We now have a study guide built with a single
HashMap to help us study our Java concepts. We also now know how to use the
HashMap for efficiently storing and manipulating key-value pairs in Java. You’re already on your way to be a master of the maps! Play around with the source code and see how you can make the study guide better. Have questions? Leave a comment and I’ll do my best to answer.
References:
Oracle Documentation on Maps
Oracle Documentation on HashMaps
Lincoln W Daniel is a software engineer who has worked at companies big and small. Receiving internship offers from companies like NASA JPL, he has worked at IBM and Medium.com. Lincoln also teaches programming concepts on his ModernNerd YouTube channel by which he emphasizes relating coding concepts to real human experiences. | https://www.sitepoint.com/building-a-study-guide-app-with-java-hashmap/ | CC-MAIN-2020-40 | refinedweb | 2,288 | 62.68 |
I've noticed that I have a 2 step pattern for learning new framework or language features. I'm guessing this is pretty typical for most people. First, I'll use the feature within framework classes or 3rd party ddls. Then I'll leverage it more directly within my own code. What's surprising to me is the length of time which occurs between step 1 and step 2.
Take generics for example. Back in the 1.x days, I wrote a ton of repetitive classes that inherited from CollectionBase. So when 2.0 came out, I immediately and aggressively started to use generic collections. However, it was quite some time later (a year?) until I wrote my own class that leveraged them directly. Today, I don't write a new generic class every day, but I do consider them an important part of my toolbox and kinda wonder what took me so long to take them up.
CollectionBase
I have a feeling that many developers are in the same boat - it's easy to consume code that implements new features, but not so easy to grasp how to implement those same features ourselves.
As it turns out, the other day, I had another such ah-hah moment with the System.Func generic delegate. Like me, you've probably consumed it often, or at least one of its cousins: System.Action and System.Predicate. I thought I'd show how I used it, in hopes that it might open up some possibilities for you.
System.Func
System.Action
System.Predicate
First though, a brief overview. The three delegates above are essentially shortcuts that save you from having to write your own common delegate. The most common one is probably Predicate<T>, which returns a boolean. Predicte<T> is used extensively by the List<T> and Array classes. The most obvious is the Exist method:
Predicate<T>
Predicte<T>
List<T>
Array
Exist
List<string> roles = user.Roles;
if (roles.Exists(delegate(string r) { return r == "admin";}))
{
//do something
}
or the lambda version (which I much prefer)
if (role.Exists(r => r == "admin))
{
}
Func<T> is a lot like Predicate, but instead of returning a boolean it returns T. Also, Func<T> has multiple overloads that let you pass 0 to 4 input parameters into the delegate. Action<T> is like Func<T> except it doesn't return anything - it does an action.
Func<T>
Predicate
Action<T>
So, how can you make use of these within your own code? Well, here's what I did. First, I'm a big proponent of caching, as well as a big fan of unit testing. However, the two don't easily go hand-in-hand because Microsoft doesn't provide an interface to their built-in cache, which leads to tight coupling (which of course makes it difficult to change caching implementation down the road, and impossible to unit test). The first thing to do is create your own interface, a simple start might look like:
public interface ICacheManager
{
T Get<T>(string key);
void Insert(string key, object value);
}
Next comes our first implementation:
public class InMemoryCacheManager : ICacheManager
{
public T Get<T>(string key)
{
return (T) HttpRuntime.Cache.Get(key);
}
public void Insert(string key, object value)
{
HttpRuntime.Cache.Insert(key, value);
}
}
So, what does all this have to do with System.Func? Well, the above code is used in a very repetitive manner: get the value from the cache, if it's null, load it from somewhere and put it back in the cache. For example:
public User GetUserFromId(int userId)
{
ICacheManager cache = CacheFactory.GetInstance;
string cacheKey = string.Format("User.by_id.{0}", userId);
User user = cache.Get(cacheKey);
if (user == null)
{
user = _dataStore.GetUserFromId(userId);
cache.Insert(cacheKey, user);
}
return user;
}
After a year or so of writing code like this, I figured there must be a better way, which of course is where Func comes in. Ideally, we'd like to get the value, and provide our callback code all at once. So, let's change our interface:
Func
public interface ICacheManager
{
T Get<T>(string key, Func<T> callback);
void Insert(string key, object value);
}
The second parameter is the delegate we'll want to execute if Get returns null. Of course our delegate will return the same type (T) as Get would - just like in the above case where we expect a User from both Get and our data store. Here's the actual implementation:
Get
null
User
public T Get<T> (string key, Func<T> callback)
{
T item = (T) HttpRuntime.Cache.Get(key);
if (item == null)
{
item = callback();
Insert(key, item);
}
return item;
}
How do we use the above code?
public User GetUserFromId(int userId)
{
return CacheFactory.GetInstance.Get(string.Format("User.by_id.{0}", userId),
() => _dataStore.GetUserFromId(userId));
}
I know the () => syntax might be intimidating (especially if you aren't familiar with lambdas), but all it is is a parameterless delegate.
() =>
Of course, this system can easily be expanded to add additional caching instructions (absolute/sliding expiries, dependencies and so on) via overloaded Get<T> and Insert members.
Get<T>
Insert
(I just noticed this example also highlights how to use generics within your own code too!)
[Advertisement]
You've been kicked (a good thing) - Trackback from DotNetKicks.com
Very interesting article, thanks.
Pingback from Reflective Perspective - Chris Alcock » The Morning Brew #129
Good article. Just one suggestion.
callback is a horrible parameter name. It's not descriptive at all and you have to look at the implementation to know what it does. How about valueIfNull?
Good call Todd.
I think I like Func<T> ifNull or something simpler. I originally named it block, influenced by rails, tried to pick a more NETish name, but I agree callback is still vague..makes it sound like Get is asynchronous or something...
Excellent example!
I was looking for good Func<T> descriptions and examples. More! More!
As always, nice post!
Pingback from Dew Drop - July 4, 2008 | Alvin Ashcraft's Morning Dew
i saw the same pattern in a collaborative filtering library i ported from Java. It had pluggable data backends, so the cache was implemented similarly as you presented. The callback was called fetcher, FWIW
Programming links 07.05.2008
Hi, very interesting post, as always.
I'd like to thank you for your Foundations of Programming series, which I noticed quite some ago but only had time to read them carefully this weekend, in the e-book format. The topics you picked are very important, and I really like the way you explain them. Even though I'm a seasoned programmer (13+ years) reading all that stuff in a structured way helped me settle some doubts about stuff I've been studying recently, like TDD and ORM. I'll ask my trainee to read it, and hopefully she will learn things I'm not sure I know how to explain (I'm a lousy teacher), even though many of them are easier to understand when we have some experience doing things the old-hard-clumsy way :)
Thanks a lot,
Rafael
São Paulo - Brazil
Karl Seguin has an interesting post about using System.Func to fight repetitive code blocks , which actually
I generally subscribe to the attitude that premature optimizations are evil, but I strongly believe that
Introduction Three weeks ago, Jeremy Miller and Chad Myers laid down their MVC approach . From the comments
Pingback from TextBoxFor(u => u.Name) - Unleash the power - taccato! trend tracker, cool hunting, new business ideas
code{color:#833;background:#fcfcfc;} Introduction There are language features that are nothing more than
code{color:#833;background:#fcfcfc;} h4{margin:30px 0px 0px 0px;font-color:#fff;font-weight:bold;border
Here is a good example I found: codebetter.com/.../get-your-func
Pingback from Back to Basics: Delegates, Anonymous Methods and Lambda Expressions - taccato! trend tracker, cool hunting, new business ideas
Pingback from Func<T> based Generic List Initializers « If only I were
It can be frustrating to want to write unit tests, only to hit some code which is rather untest | http://codebetter.com/blogs/karlseguin/archive/2008/07/03/get-your-func-on.aspx | crawl-002 | refinedweb | 1,348 | 64.41 |
I use linux/386, but, I suspect, this procedure will apply to other host platforms as well.
First step is to build host version of go:
$ cd $GOROOT/src
$ ./make.bash
Next you need to build the rest of go compilers and linkers. I have small program to do that:
$ cat ~/bin/buildcmd
#!/bin/sh
set -e
for arch in 8 6; do
for cmd in a c g l; do
go tool dist install -v cmd/$arch$cmd
done
done
exit 0
Last step is to build windows versions of standard commands and libraries. I have small script for that too:
$ cat ~/bin/buildpkg
#!/bin/sh
if [ -z "$1" ]; then
echo 'GOOS is not specified' 1>&2
exit 2
else
export GOOS=$1
if [ "$GOOS" = "windows" ]; then
export CGO_ENABLED=0
fi
fi
shift
if [ -n "$1" ]; then
export GOARCH=$1
fi
cd $GOROOT/src
go tool dist install -v pkg/runtime
go install -v -a std
I run it like that:
$ ~/bin/buildpkg windows 386
to build windows/386 version of Go commands and packages. You can, probably, see it from my script, I exclude building of any cgo related parts - these will not work for me, since I do not have correspondent gcc cross-compiling tools installed. So I just skip those.
Now we're ready to build our windows executable:
$ cat hello.go
package main
import "fmt"
func main() {
fmt.Printf("Hello\n")
}
$ GOOS=windows GOARCH=386 go build -o hello.exe hello.go
We just need to find Windows computer to run our hello.exe. | http://code.google.com/p/go-wiki/wiki/WindowsCrossCompiling | crawl-003 | refinedweb | 259 | 78.79 |
So, I just found out that in WebGL you can't use strings to access things in get component. ( WHAT A FOOL I WAS FOR REMOVING PRAGMA STRICT!!!!)
rock.GetComponent("RockScript").hardness = 10;
//This doesn't work in WebGL
Now I have to go change like 100 errors in my code. But there's one big one that I am having trouble finding a practical solution to.
static function findscript (playern : GameObject) {
if(playern.name == "Xander"){
return "move";
}else if(playern.name == "Danny"){
return "move1";
}
}
I run this function a lot. I always use it like this
player.GetComponent(seek.findscript(player)).dead = true;
Essentially, both players have 2 different scripts with the same variables (no, I cannot make them into the same script). I simply take the game object and, using the name of the player, return the respective name of that player's script. This way, I don't have to do a long if statement before every time I want to access one of the move scripts.
But now I need to put a class into GetComponent, not a string. Sadly,
static function findscript (playern : GameObject) {
if(playern.name == "Xander"){
return move;
}else if(playern.name == "Danny"){
return move1;
}
}
Doesn't work. I get a "type could not be resolved because of a cycle." error. I'm not the best coder, but to my knowledge, I think this means I the function needs to return the same class each time.
This is a bother because the whole point of this function is to return a different function for each input.
Any ideas how I can practically deal with all of these errors? Thanks, sorry this was such a long question.
Answer by Bunny83
·
Apr 17, 2016 at 10:44 PM
Well, you can't use any dynamic code when you use pragma strict. So your whole approach here is lacking. Having two seperate scripts with the same variable is a bad approach in general. Either seperate that variable into it's own seperate script which might be used from the other two, or use some sort of interface / base class approach.
It seems UnityScript now supports declaring interfaces. So both of your classes can now implement the same interface. The interface would provide methods to get / set the dead state of the script.
// UnityScript
public interface IDeadState
{
function GetDead() : boolean;
function SetDead(state : boolean);
}
// UnityScript
public class move extends MonoBehaviour implements IDeadState
{
var dead : boolean;
function GetDead() : boolean
{
return dead;
}
function SetDead(state : boolean)
{
dead = state;
}
// [ ... ]
}
To access the script you can simply use GetComponent with the interface. This will return whatever component does implement that interface. I'm not sure if the syntax is right since i usually don't use UnityScript (it's a horrible language IMO):
var script : IDeadState = player.GetComponent(IDeadState);
script.SetDead(true);
It's not clear what those two classes actually do so we can't say which approach would be better. However i guess simply using a third script is the easiest solution
// DeadState.js
var dead : boolean = false;
You simply attach that script along side to your other two scripts. Instead of having a dead variable in those scripts, you would simply use the one in this script.
// move.js
var deadState : DeadState; // either assign in the inspector or use GetComponent in Start() to assign the reference.
ps: I would also recommend to switch to C# ^^
be ready for some hate for that last line
Answer by coolraiman
·
May 03, 2016 at 12:47 PM
i know i will get a lot of hate and down vote but maybe you should try c# instead of unity script
with c# you have more control and those kind of problem don't exist.
You also have a lot more documentation.
What's the difference between SendMessage and GetComponent?
3
Answers
get variable from a different game object
1
Answer
Turn off CharacterControl Component Through Script?
1
Answer
Can you shorten "GameObject.GetComponent(Script)" to a variable?
3
Answers
What's the difference between the two GetComponents?
1
Answer | https://answers.unity.com/questions/1172481/way-to-return-a-class.html | CC-MAIN-2019-35 | refinedweb | 677 | 65.01 |
None
0 Points
Apr 11, 2011 12:02 PM|jovenbarola|LINK
I also have the same problem in here .. I have 2 version of vstudio installed on my computer 2005 and 2010..
problem occur in vstudio 2010 when i created a report using crystal, it always include this code on my aspx header
this one:
<%@ Register assembly="CrystalDecisions.Web, Version=10.5.3700.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" namespace="CrystalDecisions.Web" tagprefix="CR" %>
but i know this assembly is for vstudio 2005, so i had same error description, occured when i try to compile my aspx page
i know the right assembly to be register is the 13.0.2000 version this one:
<%@ Register Assembly="CrystalDecisions.Web, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304"
Namespace="CrystalDecisions.Web" TagPrefix="CR" %>
ahh can anyone can give me some tips to remove this error, i just only want to remove the itchy old crystal on my page, by not uninstalling my vstudio 2005 ??
any help is highly appreciable
thanks in advance
Contributor
5231 Points
Apr 11, 2011 10:55 PM|necro_mancer|LINK
hi jovenbarola,
I believe some of the forum users have experienced this issue before. You are highly advised to remove any previous Crystal Report version in order to make way for CR 2010.
Please have it uninstall completely from your system, leaving only your CR 2010 installed. Please keep me posted of any issues. Thank you.
1 reply
Last post Apr 11, 2011 10:55 PM by necro_mancer | https://forums.asp.net/t/1671748.aspx?Help+please+regarding+in+Crystal+report+2010+issue+using+asp+net | CC-MAIN-2021-25 | refinedweb | 249 | 54.42 |
Re: Is this possable with exchange and no ISP
- From: "Brian Desmond [MVP]" <desmondb@xxxxxxxxxxxxxxxxxxxx>
- Date: Thu, 31 Mar 2005 17:03:40 -0600
Hi there,
This is perfectly doable.
What I would do is just setup email for the AD domain. However, you can
follow the directions below and instead setup DNS in a new primary zone (and
make a secondary on your remote network):
Create an MX record for the domain pointing to your Exchange server.
Edit the Exhcange recipient policy so that the default SMTP addres sis
*@yourdomain.com
Create a pair of routing groups for the two sites, and create an SMTP
connector between them. The SMTP connector should handle the
*@yourdomain.com namespace.
--
--Brian Desmond
Windows Server MVP
desmondb@xxxxxxxxxxxxxxxxxxxx
"sthompson" <sthompson@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote in message
news:C3C2F25B-15F4-4E4B-8CE0-3CA1FC3DB713@xxxxxxxxxxxxxxxx
> In class i am trying to setup 2 different exchages 2003 servers so i can
> send
> email between the 2. I have 2 machines on each network, one windows 2003
> domain controller and the other is windows 2003 with exchange 2003 on
> it.They
> are both on different networks and different domains. I have a router
> inbetween so the different networks can comunicate. All the computers can
> ping each other and i do a nslookup and everything is correct. On each of
> the
> dc i create pointers and mx records for the 2 computers on their network.
> And
> since this is just a test environment at class their is no isp to create
> an
> mx record, so what i do which i do not know if you can do is on each dc i
> create a new forward zone and a reverse zone of the other domain and i am
> not
> forsure if i can actually do this or not. And then in each of the new
> zones
> the i create on both of the dc i create pointers, host name and mx record
> i
> do this hopefully so i will act like the ISP's mx record.
>
> So my questions are
>
> 1. can you create and zone for a different domain on a different network
> 2. if you can create a new zone for the different domain controllers on
> differnet networks do you have to create an A records, mx records,
> pointers
> for the other email server that is on the other network.
>
>?
.
- References:
- Is this possable with exchange and no ISP
- From: sthompson
- Prev by Date: Open Ports required for RFC over HTTP
- Next by Date: Re: Moving from ISP Mail to Exchange
- Previous by thread: Is this possable with exchange and no ISP
- Next by thread: SMTP not delivering mail
- Index(es): | http://www.tech-archive.net/Archive/Exchange/microsoft.public.exchange.setup/2005-04/msg00014.html | crawl-002 | refinedweb | 443 | 64.34 |
NAME
fcntl - manipulate file descriptor
SYNOPSIS
#include <unistd.h> #include <fcntl.h> int fcntl(int fd, int cmd); int fcntl(int fd, int cmd, long arg); int fcntl(int fd, int cmd, struct flock *lock);
DESCRIPTION
fcntl() performs one of the operations described below on the open file descriptor fd. The operation is determined by cmd. Duplicating a file descriptor F_DUPFD (since Linux 2.6.24) As for a F_DUPFD, but additionally set the close-on-exec flag for the duplicate 0, the file descriptor will remain open across an execve(2), otherwise it will be closed. F_GETFD Read the file descriptor flags. F_SETFD Set the file descriptor flags to the value specified by Read the file status flags. F_SETFL only change the O_APPEND, O_ASYNC, O_DIRECT, O_NOATIME, and O_NONBLOCK flags. Advisory locking locking (Non-POSIX.) The above record locks may be either advisory or mandatory, and are advisory by default. or EWOULDBLOCK.. Managing signals F_GETOWN, F_SETOWN, F_GETSIG and F_SETSIG are used to manage I/O availability signals: F_GETOWN Get the process ID or process group currently receiving SIGIO and SIGURG signals for events on file descriptor fd. Process IDs are returned as positive values; process group IDs are returned as negative values (but see BUGS below). F_SETOWN Set the process ID or process group ID that will receive SIGIO and SIGURG signals for events on file descriptor fd. A process ID is specified as a positive value; a process group ID is specified as a negative value. Most commonly, the calling process specifies itself as the owner (that is, arg is specified as getpid(2)).. Note also. Additionally, passing a nonzero value to F_SETSIG changes the signal recipient from a whole process to a specific thread within a process. See the description of F_SETOWN only be placed. F_GETLEASE Indicates what type of lease is associated with the file descriptor fd by returning either F_RDLCK, F_WRLCK, or F_UNLCK, indicating, respectively, a read lease , a write lease, or no lease. (The third argument to fcntl() is omitted.)). File and directory change notification (dnotify) feature test macro must be defined.) Directory notifications are normally "one-shot", and the application must re-register consider using the inotify interface (available since kernel 2.6.13), which provides a superior interface for obtaining notifications of..
CONFORMING TO
SVr4, 4.3BSD, POSIX.1-2001. Only the operations F_DUPFD, F_GETFD, F_SETFD, F_GETFL, F_SETFL, F_GETLK, F_SETLK, F_SETLKW, F_GETOWN, and F_SETOWN are specified in POSIX.1-2001. F_GETSIG, F_SETSIG, F_NOTIFY, F_GETLEASE, and F_SETLEASE are Linux- specific. (Define the _GNU_SOURCE macro to obtain these definitions.)
NOTES
The errors returned by dup2(2) are different from those returned by F_DUPFD. Since kernel 2.0, there is no interaction between the types of lock placed by flock(2) and fcntl(). POSIX.1-2001 allows l_len to be negative. (And if it is, the interval described by the lock covers bytes l_start+l_len up to and including l_start-1.) This is supported by Linux since Linux 2.4.21 and 2.5.49. Several systems have more fields in struct flock such as, for example, l_sysid. Clearly, l_pid alone is not going to be very useful if the process holding the lock may live on a different machine.
BUGS) See also Documentation/locks.txt, Documentation/mandatory.txt, and Documentation/dnotify.txt in the kernel source.
COLOPHON
This page is part of release 2.77 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at. | http://manpages.ubuntu.com/manpages/hardy/en/man2/fcntl64.2.html | CC-MAIN-2014-10 | refinedweb | 580 | 58.48 |
Quick Links
RSS 2.0 Feeds
Lottery News
Event Calendar
Latest Forum Topics
Web Site Change Log
RSS info, more feeds
Topic closed. 10 replies. Last post 3 years ago by dk1421.
Hey All!
Just a few questions about AFTER I win the lottery.
First off, I'm planning on doing an LLC, if I can in NC. It used to say on the website you could, but now it doesn't say anything at all.
I'm hoping to give half my money away, mostly to family, some to charities. I know you can "give" someone up to $13,000 without having to pay taxes. I know both my spouse and I can give a gift to the same person (meaning a total of $26,000), but if we are doing an LLC, then I think we can only do $13,000 because it's one entity, correct?
I also always thought I could pay off their mortgages (and credit cards, bill, car payments, etc) as a way to get around the gift tax, but I've since heard that you can't. Can't as in, only they can make those payments. Is this correct too?
Is there any legal way to get around the gift tax? I want to help them out, but I don't want to spend $1M for them to get $500,000. I know some winners say they are buying a new car for their kids, but are they getting taxed too? As for homes, I do remember that a person must have however much they want to put down on the house for a few months in their savings account before they can buy it. I suppose that's to prevent people from avoiding the gift tax. I suppose maybe in both these scenarios, my name/LLC would be on the title too in order for it happen?
Then there's the Visa gift cards - I've wondered if I could put several thousands on it for them (yes, I know some have horrible charges, but they are changing the rules now).
What about opening a checking account for them with me putting in the money?
I've been wondering this stuff for a long time (as you can tell), so I appreciate some real answers.
Thanks!! You are all an awesome bunch!!!
"Don't be a schmuck, always take the cash." -Coin Toss
I've thought of two different things to be able to give family members money.
The first is having different family members be a part of the LLC/trust. I think it may work to where it's simply a dividing up of the lottery payout to different people, rather than the money simply being a gift. I believe it's essentially what the lottery groups do and they only pay the income tax percentage so I don't see why you can't just say that the certain family members were all part of a group, with you the leader and them haven't a set percentage they would receive.
I see this as the best option if you plan simply to give certain amounts to family/friends as a one time only thing. I would do this for my dad, as he would get a very large sum, and three older siblings who would receive a decent amount.
Another is what you mentioned with the checking account. It'd be possible to set up a checking account and set them up as joint owners, so they'd be able to deposit/withdraw cash and I believe have debit cards/checks and also be able to take care of any issues (like if they're using the card out of state and the bank puts a hold on the account). I would have that account as a second account at my main bank, so that I could easily transfer money over instantly whenever needed.
This is the one I have considered the most, especially since it would allow me to help my younger brother with, essentially, a nice monthly allowance. He would be graduating high school soon so he could use extra money in college for groceries, bills and other activities (or if he doesn't do college, then a little extra help a month for essentials). It would also allow me to monitor the usage of the money when he uses the debit card and also be able to cut back on his "allowance" if grades were dropping (or if he started using the money in non-approved ways).
This is also the method I would use to give money to my mom, simply because she doesn't have the best of health so she would have access to whatever money she needs and we wouldn't have to deal with the "death tax" if she took a sudden turn, as the account would be in my ownership.
As for buying things for other people, I want to say I've read somewhere that buying a car/house for someone would still require you to pay the gift tax, as well as the sales tax. It kind of makes sense since it's the equivalent of giving them tens or hundreds of thousands of dollars. You may be able to buy a car/house for someone and then simply keep it on your name for a year and then transfer it over. I don't know if there's anything the government can get you on with that, though. They may have some law that forces you to still pay some dumb extra tax on that.
If it were me I'd take cash withdrawals, what I do with my cash is my business.
There's only one
So much of what has been suggested in this thread won't work (IMHO). When you win, get a good Estate Attorney. He/She will be able to do everything right.
Annual gifts in excess of $13,000 are not subject to the gift tax if they are paid directly for the donee's tuition or medical expenses. Check with a Competent Tax Advisor. You may give any one person up to $13,000 in total gifts without filing a gift tax return (from 2009 �%.
A mind once stretched by a new idea never returns to its original dimensions!
I never cease to be amazed at how casually we discuss issues like this.
Issues about how much we owe the government if we want to give a gift to a family member.
I always wonder where the people were when our elected officials did these kinds of things to us.
Why did they let them get away with it and why do we continue to let them get away with it?
They talk about entitlements killing us (and it's true) while they are the biggest entity of entitlement the world has ever known. They are standing there with their hand out to take what we owe them out of any money we get or even any money we want to give to family. And then they piss it away on nonsense and steal our Social Security money on top of it and do the same with that.
I resent the fact that I would have to share any lottery jackpot winnings with those bloodsuckers and that I have to pay them off just to give my kids a gift.
And at this very minute the D party is fighting to keep the spending spree going. And they need our lottery jackpots and those gift taxes and thousands of other taxes to keep it going.
We're going 90 miles an hour down a dead end road with the President at the wheel with the pedal to the metal.
And he's smiling all the way, enjoying the ride and saying it's not his fault.
I never thought this could happen to our country.
The libs must be as happy as fat rats in a cheese house.
.
"The only thing necessary for evil to triumph is for good men to do nothing"
--Edmund Burke
Everyone should read the "Rise and fall of the Roman Empire" ,
Why wouldn't my two solutions work?
I know for a fact the first one that includes adding people to your LLC/trust works because it's exactly what large lottery groups use. There's nobody there that can say we weren't in a group and the percentages can be judged by how much per month someone put in. Now yea, it may not be the truth but they can't prove it isn't. All that would happen is the regular income tax (which I believe is the same if you do $5 million to 5 people as it would be just $25 million to one, so you wouldn't be losing any extra money due to taxes as you would the gift tax). If you don't want to lie to anyone about family/friends not being in a group with you, simply collect some money from each person that would correspond with the percentage you want to give them.
As for the joint/shared account, I knew frat guys in college whose parents did that thing for them, put them as a shared account holder so that they could get access to whever money they needed whenever. Granted they didn't use it to bypass a gift tax of any sort, but they were still both in complete control of the money... so I know the part about starting one with my younger brother works. I believe the only way extra taxes would be involved is if it's a savings account (or one that takes interest) in which that other person may have to pay taxes on whatever money earned. I've signed on to joint access to another family members account and even though they had much more than $13,000 in there there was no issue with it, no extra taxes and the government didn't come asking questions. The bank even said that technically we both owened that money in there, so essentially they just gifted me >$13,000 and there was no extra taxes added for that gift tax. And I know for absolute certain that what I mentioned with the joint account and my mother (in case her health turned for the worse) works as we did the same thing with my great grandmother a while back, in order to avoid the hassle of anything that would arise (going through forms in order to get control of the money she left behind). You sign up for the typical joint ownership but add the 'Rights of Survivorship' to it.
Yes, of course you would likely want to speak to someone professional about these things, but I've either had on hands experience with those solutions that I had mentioned or I've seen it done numerous times with the lottery groups. I know a guy here who specializes in these things and I would still go to him to discuss these plans before I actually tried to do them, but I believe that he would agree with them.
The easiest way to share a jackpot and avoid gift taxes is to form a club or LLC and include those people for whatever share you want to give them. A tax form 5754 is completed with each person's name and share amount. Shares do not have to be equal; you can take 90% and give 5 others 2% each, for example.
When you use this form, the IRS will not dispute it or try to call it a gift.
This method might help in another way, too: Tell each recipient: "This is IT. Use it wisely, as I will NOT be giving you any more." Recipients will be less likely to be constantly at your door asking for more.
Thanks, JusCurious!
I was planning on doing an LLC, but it's been a while since I've read about it and guess I missed that part - so thank you! That solves all the problems!
And yes, I was also planning on telling them this is it, money-wise. And that if they have any business ideas/etc, they have to get it approved through my board first. This is to prevent me from being the bad guy when they have bad business-2014 Speednet Group. All rights reserved. | http://www.lotterypost.com/thread/234589 | CC-MAIN-2014-35 | refinedweb | 2,085 | 74.73 |
- gui developing
- PDF Printing support from Python
- Overiding error message when using a python program
- c-extension crashes unexpected
- Jython - how much python is it supporting?
- Problem deriving a class from the built-in file object
- SSL Server Socket Support in Python?
- IDLE: How to point it to the Python executables I want it to see on Windows
- __init__.py question
- pylab strange error message
- Noobie Question: Using strings and paths in mkdir (os.mkdir("/test/"a))
- time.strftime in 2.4.1 claims data out of range when not
- Run Unix shell command $ parse command line arguments in python
- regarding system function
- Manipulating large blobs in Python
- How to prevent Tkinter frame resize?
- Smooth upgrade to New Version
- Ron Grossi: God is not a man
- Confusing: Canvas image working in function but not in class
- grouping subsequences with BIO tags
- Jython run scripts problem (2.2.0a0 on Mac OSX 10.3.8)
- Python CGI Select Multiple Returning all items in box
- New line
- Using Jython in Ant Build Process
- SSL via Proxy (URLLIB2) on Windows gives Unknown Protocol error?
- inner sublist positions ?
- Define Constants
- What's the difference between these 2 statements?
- pyGTK on Mouse over event ?
- Resolving 10060, 'Operation timed out'
- using locales
- Python Win32 Extensions and Excel 2003. OL 11.0 Supported?
- Faster os.walk()
- logging to two files
- random number between 0 and 20
- Redhat 9, Python 2.4.1, CGIHTTPServer problem
- exception handling
- building a small calculator
- trying to understand unicode
- Lex
- goto statement
- PyObject_New not running tp_new for iterators?
- Fwd: Memory leak in python
- long time we haven't spoken ;)
- Python instances
- Why Python does *SLICING* the way it does??
- How to run Python in Windows w/o popping a DOS box?
- How to Convert a makefile to Python Script
- Python Debugger with source code tracking ability
- Authentication
- Importing some functions from a py file
- Thanks
- Writing to stdout and a log file
- Entry Value won't get updated...Help please
- Python SSL Socket issue
- 1993 Van Rossum Python Web Robot
- Array of Chars to String
- poll: does name conventions in python matters?
- Python dtrace
- python
- Encoding Questions
- gc.DEBUG_LEAK and gc.garbage
- Using Paramiko
- Refactoring in Python.
- The value of the entry widget doesn't get updated
- Tkinter and Scrollbar
- XML-RPC -- send file
- Dr. Dobb's Python-URL! - weekly Python news and links (Apr 18)
- Extending base class methods
- New to Tkinter...
- Variables variable
- Update Label when Scale value changes
- modules and namespaces
- xmlrpclib and binary data as normal parameter strings
- MessageBox ONOK?
- Memory leak in python
- Name/ID of removable Media: how?
- Question about python 2.4 documentation
- module MySQLdb is missing in python 2.3.3
- uploading/streaming a file to a java servlet
- grammar for where/letting/with and suite expressions (thunks etc)
- Proposal: an unchanging URL for Python documentation
- Trouble Installing TTX/FontTools (asks for .NET Framework Packages)
- strange error in socket.py
- Dr. Dobb's Python-URL! - weekly Python news and links (Apr 18)
- Wrapping C++ Class Heirachy in Python
- Updating Windows File Summary Data
- Tkinter Event Types
- Tiny fonts in wxPython app
- Enumerating formatting strings
- Tkinter & Tkconstants
- def a((b,c,d),e):
- Twisted for online games
- Replaying multimedia data.
- packages
- EasyDialogs module problem with python 2.4.1
- (no subject)
- How to get a Function object from a Frame object
- SQLite Database Manager
- How standard is the standard library?
- Behaviour of str.split
- Working with method-wrapper objects
- Zope3 and Plone
- (PHP or Python) Developing something like
- accesing pages (or ranges of pages) via Reportlab
- Can't compile with --enable-shared on MacOSX
- trying to parse a file...
- fpectl
- compiling python 2.4.1 on Linux_X86_64 using PGI compiler fails
- Can a function be called within a function ?
- Removing dictionary-keys not in a set?
- Strings and Lists
- [PythonWin] MakePy and gencache.EnsureModule() do different things.
- distutils, PyBison and Mac OS X
- Parse command line options
- Canceling/interrupting raw_input
- Slight discrepancy with filecmp.cmp
- Apache mod_python
- trying to parse a file...
- terminal shutdown
- Finding name of running script
- python.exe on Mac OS X!?
- Accessing multidimensional lists with an index list
- Problem with unpack hex to decimal
- How to compile ScientificPython-2.4.9 under XP cygwin environment?
- How to compile ScientificPython-2.4.9 under XP cygwin environment?
- sscanf needed
- re module methods: flags(), pattern()
- module to parse "pseudo natural" language?
- Pattern Matching Given # of Characters and no String Input; use RegularExpressions?
- Decorator Syntax For Recursive Properties
- pydoc preference for triple double over triple single quotes -- anyreason?
- trouble to print array contents using slice operator
- XML parsing per record
- unicode "em space" in regex
- distutils question: different projects under same namespace
- need help in PySparse
- Problem when subclass instance changes base class instance variable
- Piping data into script under Win32
- Dr Dobbs "with" keyword
- pre-PEP: Suite-Based Keywords
- pre-PEP: Simple Thunks
- trouble using \ to escape %
- pexpect problem, spawn says I/O on closed file
- Glade for Windows and Python
- Pyrex colorizer please review
- Python 2.4.1 hang
- module placeholder
- module placeholder
- How to fix this error in the example in 6.1.4 Files and Directories
- py2exe - create one EXE
- mySQL values not updating after query
- Python's use in RAD
- http status response
- IOError 11 CGI module
- Get OS name
- Determine ip address
- key-logging capability using python ?
- eval function not working how i want it dag namn
- MS SQL Server/ODBC package for Python
- Python - interpreted vs compiled
- A testcase for a Queue like class.
- RE Engine error with sub()
- question about functions
- pythonic use of properties?
- Is Python appropriate for web applications?
- Rookie Question: Passing a nested list into a function?
- new to mac OS10
- Function to log exceptions and keep on truckin
- wxPython OGL: How make LineShape text b/g transparent?
- changing colors in python
- SimpleXMLRPCServer - disable output
- SimpleXMLRPCServer - turn of output
- Using python from a browser
- Socket Error
- distribute python script
- Python 2.3.5 make: *** [Parser/pgen] Error 1 Parser/grammar.o: I
- New-style classes, iter and PySequence_Check
- curses for different terminals
- py2exe + XML-RPC problem
- connection refused when uploading a package to pypi
- Nokia to speak at Python-UK next week
- MESSAGE COULD NOT BE DELIVERED
- EOF-file missing
- Get the entire file in a variable - error
- Converting a perl module to a python module would it be worth it?
- PIL pilfont.py
- Tk Listbox - Selected Item ?
- Supercomputer and encryption and compression @ rate of 96%
- how to solve [ 1144533 ] htmllib quote parse error within a <script>
- Printable version of Python tutorila
- Inelegant
- String manipulation
- Utah Python Users Group
- python guru... ViewCVS
- build flow? SCons? AAP? process creation?
- are DLLs needed to run glade interfaces in python with Windows?
- Simple Python + Tk text editor
- How to call a function in embeded python code in delphi?
- domain specific UI languages
- Using a python web client behind a proxy (urllib and twisted.web)
- unstatisfied symbols building Python 2.4.1 on HP-UX 10.20
- Kamaelia 0.1.2 Released
- Codig style: " or """
- A Question About Handling SIGINT With Threads
- Returned mail: see transcript for details
- Scanner Access in Python
- Is socket.shutdown(1) useless
- isbntools. (python script to download book informaiton)
- preallocate list
- terminate exectutioin in PythonWin
- Has Python 2.4.1 changed implementation for __init__.py???
- for line in file weirdness
- how to explain such codes, python's bug or mine?
- Compute pi to base 12 using Python?
- A command in a String ?
- Doubt regarding sorting of a list specific field
- Read the windows event log
- Global Variables
- os.path.walk
- permission
- sort of a beginner question about globals
- Image Module
- How to debug SOAP using TCpMon and Python?
- defining extern variables in pyrex
- Looking for a very specific type of embedded GUI kit
- A beginer question about SOAP and Python: <SOAPpy.Types.structType HashStringResponse at 23909440>: {}
- Web Application Client Module
- Whither python24.dll? {WinCvs 2.0 and Python}
- "The C++ part of the .. Has been deleted, wsTaskBarIcon
- ipv4 class
- ATTN : Georges ( gry@ll.mit.edu)
- Embedding threaded Python
- PyChart into web site error
- python/svn issues....
- Removing comments... tokenize error
- "The C++ part of the .. Has been deleted, wsTaskBarIcon
- problem with the logic of read files
- Please Hlp with msg:"The C++ part of the StaticText object has been deleted"
- smtplib STARTTLS problems
- Better access to database search results
- chaco and wx 2.5....
- Northampton, UK
- exporting imports to reduce exe size?
- Informixdb: New maintainer, new version
- Northampton, UK
- Python / Win32 extensions compatibility with Windows XP
- Extending an embeded Python
- printing with wxPython
- BayPIGgies REMINDER: April 14, 7:30pm (FIRST meeting at IronPort)
- os.open() i flaga lock
- Tkinter "withdraw" and "askstring" problem
- ./pyconfig.h?
- Cannot import mod_python modules
- [perl-python] Python documentation moronicities (continued)
- Overlapping matches in Regular Expressions
- Python license (2.3)
- How to minimize the window
- some sort of permutations...
- Problem with downloading from www
- HTTPSConnection script fails, but only on some servers (long)
- Module for handling Nested Tables in HTML
- Can't Stop Process On Windows
- Threads and variable assignment
- help: loading binary image data into memory
- Help! How to use Informix in Python?
- Missing Module when calling 'Import' _omnipy
- Dialogic bindings
- semicolons
- Returned mail: see transcript for details
- Dr. Dobb's Python-URL! - weekly Python news and links (Apr 11)
- Programming Language for Systems Administrator
- Correct Versions to execute Corba calls using omniORBpy and omniORB.
- The convenient database engine for a "Distributed" System
- The convenient compiler for Python Apps and Distribution of it
- NSInstaller Vs. Inno Setup
- Dr. Dobb's Python-URL! - weekly Python news and links (Apr 11)
- Problem with import "from omniORB import CORBA, PortableServer"
- Creating a new instance of a class by what is sent in?
- smtplib does not send to all recipients
- Automatic response to your mail (Error)
- Sockets (jepler@unpythonic.net)
- Sockets (Dan)
- Sockets (Dave Brueck)
- Ten days to go until Python-UK...
- Python 2.4 killing commercial Windows Python development ?
- singleton objects with decorators
- Checking for the status of a device (before connection)... -- (JohnMcCormick)
- zlib and zipfile module in Python2.4
- where is python.h? / NumPy installation
- variables exist
- How to pass a runtime license key to CreateControl()
- How to pass a runtime license key to CreateControl()
- IPython - problem with using US international keyboard input scheme on W2K
- unicode character '\N{ }'
- Avoiding DOS Window...
- PyWin32 COM mailing list / web forum?
- Message Delivery Failure - due to attachments
- Cleaning up after C module
- database in python ?
- web authoring tools
- non-ascii charater image gereration with PIL
- Doubt regarding sorting functions
- PIGIP Meeting -- Python Interest Group In Princeton
- NYZPUG: Does it still exist?
- help with wxPython and wxGrid
- Python 2.4.1 install broke RedHat 9 printconf-backend
- Dictonary persistance weirdness
- Behavioural identity - a short discussion
- Creating a Package
- hello
- Document exchange!
- Smart help again
- numarray.array can be VERY slow
- templating system
- Why does StringIO discard its initial value?
- UselessPython 2.0
- Problems with dparser grammar
- Help understanding code
- Signals and system
- Does Tk provide ComboBox ?
- serialize a tkinter thing
- very simple tkinter demo program
- visibility between modules
- python modules in home dir
- wsh and Python
- How to detect if file is a directory
- ntvdm problem on win2k
- Help with modem terminal
- SoCal Piggies meeting Tuesday 4/12
- Are circular dependencies possible in Python?
- workaround for generating gui tools
- change the date string into timestamp
- How to check whether a list have specific value exist or not?
- check instace already running...
- ideal rankings for python related search engine queries
- Python/wxPython Reducing memory usage.
- shelve and concurrency
- Unit tests in Leo
- Python Equivalent to Java Interfaces?
- BayPIGgies: April 14, 7:30pm (FIRST meeting at IronPort)
- Python extension performance
- Text & Unicode processing references on the web.
- Puzzling OO design problem
- makepy generates empty file
- Exception Handling
- Counting iterations
- Declaring variables from a list
- Registering File Extension?!?
- Https Form Page
- problem saving tif files with PIL
- Equivalent string.find method for a list of strings
- base64 interoperability
- sending signals to child process
- redirect stdout
- how can I extract all urls in a string by using re.findall() ?
- sorting a list and counting interchanges
- Sybase module 0.37 released
- Overwrite just one line? Am I a n00b or is this impossible? Both? :D
- I've broken PythonWin2.4 - Dialogs don't pop up!
- Python sleep doesn't work right in a loop?
- number conversion
- Compiling extensions
- richcmpfunc semantics
- Problem with access to shared memory(W2K) / ORIGINALLY (win32) speedfan api control
- Using weakrefs instead of __del__
- Resticted mode still active (error?)
- shebang in cross platform scripts
- Erroneous line number error in Py2.4.1 [Windows 2000+SP3]
- formatting file
- Harvestman install not working
- how to parse system functions output
- ignoring keywords on func. call
- Establishing connection SSH
- How to detect windows shutdown
- fastcgi
- Calling a Perl Module from Python
- Installing Python 2.4 on Linux
- optparse and negative numbers as positional arguments
- Add System Path?!?
- Add System Path?!?
- oracle interface
- ANN : Columbus OH Meetup Group
- Best editor?
- Testing threading
- Propagating poorly chosen idioms
- Reminder: Vanouver Python Meeting Tonight
- os.path query functions behavior incorrect?
- regexp weirdness (bug?)
- authentication in zope server & Python
- Python & MySQL
- cross platform printing
- "unknown protocol" error in httplib using HTTPS
- SSL and Proxy problem with urllib2 ?
- check interpreter version before running script
- Python IDE like NetBeans/Delphi IDE
- passing dictionary objects with soap
- Python Google Server
- Is it possible to distinguish between system environment variablesand the user ones?
- How to read a wxTreeCtrl
- Placing Toplevel over the parent ?
- EOL created by .write or .encode
- monitoring folder in python
- gvbyhqp
- copying a file in the python script
- Unexpected result when comparing method with variable
- hello
- raw sockets please
- hello
- hello
- Python modules for image / map manipulation?
- How to merge two binary files into one?
- Decorator Maker is working. What do you think?
- Web application toolkit recommendation?
- Eric3 under WinXP
- change extensions
- sparse sets of integers?
- Mail Delivery System
- Insert database rows from CSV file
- Gnuplot.py and, _by far_, the weirdest thing I've ever seen on my computer
- sys.stdout / sys.stderr, subprocess, redirection
- Decorator Base Class: Needs improvement.
- Changing TEXT color from python
- Status of Chaco?
- Eric3 under WinXP
- dynamic partial mirror, apt-get fails
- Symbol Referencing Error in Fortran 90
- Dr. Dobb's Python-URL! - weekly Python news and links (Apr 4)
- setup distributed computing for two computer only
- Dr. Dobb's Python-URL! - weekly Python news and links (Apr 4)
- Extracting Font Outline informations
- playing with pyGoogle - strange codec error
- adodbapi return value
- Problems compiling PIL under Cygwin
- Europython 2005 is now accepting talk submissions
- boolean -> DNF
- Text file to SDE
- Testing for EOF ?
- Sending keytrokes to Windows app
- What's up with the PyFX Project??? (ex PyCG nVidia CG implementation)
- import and scope inconsistency?
- Raise Error in a Module and Try/Except in a different Module
- Tkinter - pixel or widget color
- Question about Enthought python distribution
- GUI - Qt Designer
- distutils
- Makeing TopLevel Modal ?
- checkbook manager
- Question about the Python Cookbook: How much of this is new?
- Help me dig my way out of nested scoping
- can't link Python 2.4.1 against external libxml2 ...
- mini_httpd (ACME Labs) & Python 2.4.1 integration
- "specialdict" module
- re module non-greedy matches broken
- On slashdot
- Python Cookbook
- Newsgroup Programming
- text analysis in python
- the bugs that try men's souls
- threading.Event file descriptor
- Corectly convert from %PATH%=c:\\X;"c:\\a;b" TO ['c:\\X', 'c:\\a;b']
- testing -- what to do for testing code with behaviour dependant uponwhich files exist?
- Name of IDLE on Linux
- Example Code : Shared Memory with Mutex (pywin32 and ctypes)
- instance name
- Performance issue
- terminating an inactive process
- [EVALUATION] - E03 - jamLang Evaluation Case Applied to Python
- Docorator Disected
- How To Do It Faster?!?
- How to reload local namespace definitions in the python interpreter?
- Simple thread-safe counter?
- (win32) speedfan api control
- Installing Python on a Windows 2000 Server
- Module subprocess: How to "communicate" more than once?
- How To Do It Faster?!?
- How To Do It Faster?!?
- Help with splitting
- Attributes and built-in types
- pagecrawling websites with Python
- Creating Modules/Namespaces from C/C++ for better class/function encapsulation/cleanup
- string goes away
- how to close a gzip.GzipFile?
- Decorater inside a function? Is there a way?
- numeric module
- Shelve DBRunRecoveryError
- Looking for Benchmarklets to improve pyvm
- Unzipping Files
- Pseudocode in the wikipedia
- 3 weeks to go to Python-UK!
- Spider - path conflict [../test.htm,]
- Combining digit in a list to make an integer
- Showing errors explicitly in try... except
- Case-insensitive dict, non-destructive, fast, anyone?
- A ClientForm Question
- class attributes and inner classes in C extensions
- StopIteration in the if clause of a generator expression
- that is it is not it (logic in Python)
- Ternary Operator in Python
- Ternary Operator in Python
- Lambda: the Ultimate Design Flaw
- [python-perl] Translation review?
- what's the use of __repr__?when shall I use it?
- dictionary: sorting the values preserving the order
- 48-hour game programming competition only 14 days away
- New to programming question
- __init__ method and raising exceptions
- string goes away
- unittest vs py.test?
- Our Luxurious, Rubinesque, Python 2.4
- assignments - want a PEP
- System bell
- assignments - want a PEP
- mod_python and zope
- Controling the ALU
- Change between Python 2.3 and 2.4 under WinXP
- Stylistic question about inheritance
- How To Do It Faster?!?
- Printing Varable Names Tool.. Feedback requested.
- split an iteration
- Problem with national characters
- AttributeError: 'module' object has no attribute 'setdefaulttimeout'
- Recording Video with Python
- Generating RTF with Python
- hex string into binary format?
- Error
- How To Do It Faster?!?
- property and virtuality
- The value exceptions are raised with (odd behaviour?)
- Formated String in optparse
- Mac OS X Installer for Python 2.4.1 available
- Pari Python
- Making a DLL with python?
- UnicodeEncodeError in string conversion
- AAC extracton
- problem running the cgi module
- Python plug-in Frameworks like Eclipse RCP...
- Python 2.4.1 build (configure) ?
- returning a list: IndexError
- McMillan Installer vs. Python 2.4
- More decorator rumination
- pySerial- need help.
- initialize a dictionary
- AttributeError: ClassA instance has no attribute '__len__'
- CGI, FieldStorage and Filename
- checking if program is installing using python
- return the last item in a list
- Dr. Dobb's Python-URL! - weekly Python news and links (Mar 30) | https://bytes.com/sitemap/f-292-p-65.html | CC-MAIN-2019-43 | refinedweb | 3,023 | 57.06 |
(For more resources on Groovy DSL, see here.)
The Grails framework is an open source web application framework built for the Groovy language. Grails not only leverages Hibernate under the covers as its persistence layer, but also implements its own Object Relational Mapping layer for Groovy, known as GORM. With GORM, we can take a POGO class and decorate it with DSL-like settings in order to control how it is persisted.
Grails programmers use GORM classes as a mini language for describing the persistent objects in their application. In this section, we will do a whistle-stop tour of the features of Grails. This won't be a tutorial on building Grails applications, as the subject is too big to be covered here. Our main focus will be on how GORM implements its Object model in the domain classes.
Grails quick start
Before we proceed, we need to install Grails and get a basic app installation up and running. The Grails' download and installation instructions can be found at. Once it has been installed, and with the Grails binaries in your path, navigate to a workspace directory and issue the following command:
grails create-app GroovyDSL
This builds a Grails application tree called GroovyDSL under your current workspace directory. If we now navigate to this directory, we can launch the Grails app. By default, the app will display a welcome page at.
cd GroovyDSL
grails run-app
The grails-app directory
The GroovyDSL application that we built earlier has a grails-app subdirectory, which is where the application source files for our application will reside. We only need to concern ourselves with the grails-app/domain directory for this discussion, but it's worth understanding a little about some of the other important directories.
- grails-app/conf: This is where the Grails configuration files reside.
- grails-app/controllers: Grails uses a Model View Controller (MVC) architecture. The controller directory will contain the Groovy controller code for our UIs.
- grails-app/domain: This is where Grails stores the GORM model classes of the application.
- grails-app/view: This is where the Groovy Server Pages (GSPs), the Grails equivalent to JSPs are stored.
Grails has a number of shortcut commands that allow us to quickly build out the objects for our model. As we progress through this section, we will take a look back at these directories to see what files have been generated in these directories for us.
In this section, we will be taking a whistle-stop tour through GORM. You might like to dig deeper into both GORM and Grails yourself. You can find further online documentation for GORM at.
DataSource configuration
Out of the box, Grails is configured to use an embedded HSQL in-memory database. This is useful as a means of getting up and running quickly, and all of the example code will work perfectly well with the default configuration. Having an in-memory database is helpful for testing because we always start with a clean slate. However, for the purpose of this section, it's also useful for us to have a proper database instance to peek into, in order to see how GORM maps Groovy objects into tables. We will configure our Grails application to persist in a MySQL database instance.
Grails allows us to have separate configuration environments for development, testing, and production. We will configure our development environment to point to a MySQL instance, but we can leave the production and testing environments as they are.
First of all we need to create a database, by using the mysqladmin command. This command will create a database called groovydsl, which is owned by the MySQL root user.
mysqladmin -u root create groovydsl
Database configuration in Grails is done by editing the DataSource.groovy source file in grails-app/conf. We are interested in the environments section of this file.
environments {
development {
dataSource {
dbCreate = "create-drop"
url = "jdbc:mysql://localhost/groovydsl"
driverClassName = "com.mysql.jdbc.Driver"
username = "root"
}
}
test {
dataSource {
dbCreate = "create-drop"
url = "jdbc:hsqldb:mem:testDb"
}
}
production {
dataSource {
dbCreate = "update"
url = "jdbc:hsqldb:mem:testDb"
}
}
}
The first interesting thing to note is that this is a mini Groovy DSL for describing data sources. In the previous version, we have edited the development dataSource entry to point to the MySQL groovydsl database that we created.
In early versions of Grails, there were three separate DataSource files that need to be configured for each environment, for example, DevelopmentDataSource.groovy. The equivalent DevelopmentDataSource.groovy file would be as follows:
class DevelopmentDataSource {
boolean pooling = true
String dbCreate = "create-drop"
String url = " jdbc:mysql://localhost/groovydsl "
String driverClassName = "com.mysql.jdbc.Driver"
String username = "root"
String password = ""
}
The dbCreate field tells GORM what it should do with tables in the database, on startup. Setting this to create-drop will tell GORM to drop a table if it exists already, and create a new table, each time it runs. This will keep the database tables in sync with our GORM objects. You can also set dbCreate to update or create.
DataSource.groovy is a handy little DSL for configuring the GORM database connections. Grails uses a utility class—groovu.utl. ConfigSlurper—for this DSL. The ConfigSlurper class allows us to easily parse a structured configuration file and convert it into a java.util.Properties object if we wish. Alternatively, we can navigate the ConfigObject returned by using dot notation. We can use the ConfigSlurper to open and navigate DataSource.groovy as shown in the next code snippet. ConfigSlurper has a built-in ability to partition the configuration by environment. If we construct the ConfigSlurper for a particular environment, it will only load the settings appropriate to that environment.
def development =
new ConfigSlurper("development").parse(new
File('DataSource.groovy').toURL())
def production =
new ConfigSlurper("production").parse(new
File('DataSource.groovy').toURL())
assert development.dataSource.dbCreate == "create-drop"
assert production.dataSource.dbCreate == "update"
def props = development.toProperties()
assert props["dataSource.dbCreate"] == "create-drop"
(For more resources on Groovy DSL, see here.)
Building a GORM model
The grails command can be used as a shortcut to carve out GORM domain classes. We can create a domain class for Customer by issuing the following Grails command from the GroovyDSL application directory:
grails create-domain-class Customer
This will create a stub Customer.groovy file in the grails-app/domain directory, as follows:
class Customer {
static constraints = {
}
}
If we add some fields to this class, we can peek into the MySQL database to see how GORM automatically creates a table for this class.
class Customer {
String firstName
String lastName
static constraints = {
}
}
Now if we restart Grails by issuing the grails run-app command, we can inspect the resulting table in MySQL:
GORM has automatically created a customer table for us in the groovydsl database. The table has two fields by default, for the row id and the object version. The two fields we added to Customer have been mapped to the first_name and last_name of Type varchar(255) columns in the database.
Using domain classes
Now that we have a domain class, how do we go about trying it out? We could dive in and write controllers and a view in order to build UI pages for the Customer object, which would be the norm if we were building a full-blown Grails application. We don't want to do this as all we want to do is look at how the GORM model is constructed.
Fortunately, Grails has some ways to let us interact directly with model classes without building any UI superstructure. The simplest of these is to use the GroovyConsole. The grails command can be used to launch the console with the Grails environment running, so that model classes are immediately accessible.
$g rails console
A normal POGO class would only allow us to construct it and interact with its properties at this point. However, Grails has used the Groovy MOP to add some persistence methods to the Customer class. If we run the code shown in the previous example, we call the save method on a Customer object that causes it to be stored in the MySQL database. Using mysql we can confirm to our satisfaction that a row has actually been saved, by doing this:
mysql> select * from customer;
+----+---------+------------+------------+
| id | version | first_name | last_name |
+----+---------+------------+------------+
| 1 | 0 | Fred | Flintstone |
+----+---------+------------+------------+
1 row in set (0.00 sec)
mysql>
We also have methods to get( ) an object from the database by ID, update() the object, and list() available objects.
def barney = new Customer(firstName: "Barney", lastName: "Rubble")
barney.save()
def fred = Customer.get(1)
fred.firstName = "Fred"
fred.save()
def customers = Customer.list()
customers.each { println c.id + ": " + c.firstName + " , " +
c.lastName }
The above example saves a new customer "Barney" to the database, gets the customer object for "Fred", and updates the firstName field. The list method returns all customers as a regular list collection so that we can apply a closure to all members to print them.
1: Fred, Flintstone
2: Barney, Rubble
Let's take a second to look at what Grails has done to our class. The Customer class that we declared had no base class to inherit methods from, and it did not define these methods. Grails has used the Groovy MOP to add these methods. When we run our Grails app in development mode, Grails iterates of all the domain classes in grails-app/domain. As it does so, it adds these persistence methods to the MetaClass of each doma in class that it encounters. We have covered several different options as to how to add a method to a class on the fly. In this case, Grails has augmented the MetaClass for Customer with a combination of static and normal methods, as follows:
class Customer {
...
}
Customer.metaClass.static.get = { ... }
Customer.metaClass.static.list = { ... }
Customer.metaClass.save = { ... }
class Customer {
Summary
This article gave us an overview of the Grails Object Relational Mapping (GORM). We also saw the building of a GORM model using domain classes.
Further resources on this subject:
- Metaprogramming and the Groovy MOP [article]
- Modeling Relationships with GORM [article] | https://www.packtpub.com/books/content/grails-object-relational-mapping-gorm | CC-MAIN-2016-40 | refinedweb | 1,685 | 55.13 |
42930/how-to-convert-beautifulsoup-object-to-string
Hi. I am doing web scraping and I have extracted some data from website using findall. Now I want to do some string operations on it. How can I convert the BeautifulSoup object to string?
You can do this by directly type casting it. See the code below:
for points in soup.find_all('div',{"class":"user-level"}):
point = str(points.text)
print(point)
Use this :-
>>> datetime.datetime.strptime('24052010 ...READ MORE
mylist = [1, 2, 3]
‘’.join(map(str, mylist))
==> ...READ MORE
g1 here is a DataFrame. It has a hierarchical index, ...READ MORE
Here is an easy solution:
def numberToBase(n, b):
...READ MORE
Yes, you can use the headless mode. ...READ MORE
Hey. Refer to the following code:
driver.get("link")
html = ...READ MORE
Yes, you can do it by using ...READ MORE
You can specify the class you want ...READ MORE
you are passing the parsed datetime object to ...READ MORE
It can be done in the following ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/42930/how-to-convert-beautifulsoup-object-to-string | CC-MAIN-2020-16 | refinedweb | 177 | 71.71 |
- Explore
- Create
- Tracks
In my setup, on namenode, I have to do manual checkpointing everytime from the namenode terminal.
I am following this article for the same.
The checkpoint delay as shown in the attachment is 3600 seconds.
I keep getting alerts that checkpointing is not done. Clearly, it is not happening automatically.
Am I missing anything here? How do we autmate checkpointing?
Answer by Jay Kumar SenSharma ·
If you?
Normally ambari reports alerts when the underlying system is not healthy so better to check the namenode logs and heap usages/ GC Pauses ..etc
What is the heap size for your namenode is is according to the calculation listed here:
NameNode heap size depends on many factors, such as the number of files, the number of blocks, and the load on the system.
.
Do you see any warning / error while running the following commands manually on your own?
# su - hdfs # hdfs dfsadmin -safemode enter # hdfs dfsadmin -saveNamespace # hdfs dfsadmin -safemode leave
.
The above commands we can run as cron job , however it it better to check if you are getting any warning /error while running this command manually.
You can also try reducing the "dfs.namenode.checkpoint.txns" value to little lower value like 100000 and then check if it helps in fixing the alerts. The Secondary NameNode or CheckpointNode will create a checkpoint of the namespace every 'dfs.namenode.checkpoint.txns' transactions, regardless of whether 'dfs.namenode.checkpoint.period' has expired.
However such tuning depends on your usecase:
Answer by Utkarsh Jadhav ·
Thanks@Jay Kumar SenSharma
If?
==> No. I have been seeing this problem since day 1 of the setup (A few months so to say). And the system looks stable too.
I anyway checked for heap and the setup follows the standard mentioned in the link.
The problem is Ambari itself is not doing the checkpoint (Assuming Ambari to do it). I can do it with manual commands successfully.
Am I missing anything else here?
Answer by Jay Kumar SenSharma ·
Regarding your query: "The problem is Ambari itself is not doing the checkpoint (Assuming Ambari to do it)."
>>>> Ambari is not responsible for doing the HDFS check pointing (rather it can simply alert if checkpoint did not happen). The Alert that you are getting is simply checking the HDFS Checkpoint time and reporting the alert.
The "NameNode Last Checkpoint" can be triggered if Too much time elapsed since last NameNode checkpoint. We can see this alert if the last time that the NameNode performed a checkpoint was too long ago or if the number of uncommitted transactions is beyond a certain threshold.
Checkpoointing is controlled by the following properties of HDFS configs so if it is not happening in regular interval then we will have to look the NN logs / gc logs / settings.
You could go to the Namenode current folder and check when was the last fsimage. | https://community.hortonworks.com/questions/198380/how-to-automate-manual-checkpointing-on-namenode.html?sort=oldest | CC-MAIN-2019-35 | refinedweb | 480 | 65.01 |
ex::caution - Perl pragma for enabling or disabling strictures and warnings simultaneously
use ex::caution; no ex:caution;
ex:caution allows you to enable or disable warnings and strictures simultaneously with one command. Unlike either strict or warnings it does not support arguments. It is all or nothing.
use ex::caution;
is exactly equivalent to
use strict; use warnings;
and
no ex::caution;
is exactly equivalent to
no strict; no warnings;
Enables warnings and stricts in the lexical scope in which it is used.
This module is currently in the 'ex' namespace as this is the approved way to release experimental pragmata. If approved it will be renamed to simply 'caution';
Its probably a bug that we support
no caution;
but, well, not supporting it wouldn't be the Perl way.
Original idea and packaging by Yves Orton, <demerphq@>. The amazingly simple implementation was posted by Aaron Crane to the Perl5Porters mailing list in response to a mail by yves.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.8 or, at your option, any later version of Perl 5 you may have available. | http://search.cpan.org/dist/ex-caution/lib/ex/caution.pm | CC-MAIN-2017-26 | refinedweb | 200 | 52.19 |
How it works
This plugin checks for specific keywords in image/gif attachments, using gocr (an optical character recognition program).
This plugin can be used to detect spam that puts all the real spam content in an attached image. The mail itself only random text and random html, without any URL's or identifiable information.
Requirements
You will need convert (imagemagick) and gocr installed.
Installation
Save the two files below in your local configuration directory, adjusting the score in Ocr.cf as you like, and the wordlist (my @words =) in Ocr.pm according to the spam you are receiving. You might want to run gocr by hand on the image attachments to look for words that are correctly recognized.
Remarks
Note that this is my first SA plugin, so any feedback is welcome
The words checked for are specific for some spam I received a lot of recently.
gocr can take up quite a bit of resources, so be careful. But it is only executed for messages that contain gif attachments.
ToDo
Words are hardcoded. Should be a configuration parameter instead.
Instead of checking for specific words, it might be better to "check if the image contains a certain amount of text", since it is not very likely that people send legitimate mail with text in images.
-- Author: Maarten de Boer, mdeboer -at- iua -dot- upf -dot- edu
Changelog
Version 2:
Use convert instead of giftopnm, because I received some mails with .gif's that were actually .jpg's. convert handles that ok.
Some words added
Code
Ocr.cf
loadplugin Ocr Ocr.pm body OCR eval:check_ocr() describe OCR Check if text in attached images contains spam words score OCR 3.0
Ocr.pm
# Ocr plugin, version 2 package Ocr; use strict; use Mail::SpamAssassin; use Mail::SpamAssassin::Util; use Mail::SpamAssassin::Plugin; our @ISA = qw (Mail::SpamAssassin::Plugin); # constructor: register the eval rule sub new { my ( $class, $mailsa ) = @_; $class = ref($class) || $class; my $self = $class->SUPER::new($mailsa); bless( $self, $class ); $self->register_eval_rule("check_ocr"); return $self; } sub check_ocr { my ( $self, $pms ) = @_; my $cnt = 0; foreach my $p ( $pms->{msg}->find_parts("image") ) { my ( $ctype, $boundary, $charset, $name ) = Mail::SpamAssassin::Util::parse_content_type( $p->get_header('content-type') ); if ( $ctype eq "image/gif" ) { open OCR, "|/usr/bin/convert -flatten - pnm:-|/usr/bin/gocr -i - > /tmp/spamassassin.ocr.$$"; foreach $p ( $p->decode() ) { print OCR $p; } close OCR; open OCR, "/tmp/spamassassin.ocr.$$"; my @words = ( 'company', 'money', 'stock', 'million', 'thousand', 'buy', 'price', 'don\'t' ); while (<OCR>) { my $w; foreach $w (@words) { if (m/$w/i) { $cnt++; } } } unlink "/tmp/spamassassin.ocr.$$"; } } return ( $cnt > 1 ); } 1; | http://wiki.apache.org/spamassassin/OcrPlugin | crawl-002 | refinedweb | 431 | 55.34 |
We are about to switch to a new forum software. Until then we have removed the registration on this forum.
the following code performs a random scratch between two videos ( they should be of equal length: for testing purposes, use the same video under 2 different names). It will run for anywhere between a few hundred and a few thousand draw() cycles before it hangs. I believe that this is memory/gc related as the prog survives longer for smaller format movies but upping GUI memory to 750M ( on a Pi3) cannot ultimately save it. I cannot find any logs.
Down to the choice of library this code runs without issue on Mac OS with 336 I need this to run as a appliance hence my choice of RPI
import gohai.glvideo.*; class GLmovie_ext { GLMovie mov; float length; }; GLmovie_ext[] m = new GLmovie_ext[2]; int now_showing; boolean loaded = false; void setup() { //frameRate(50); size(500, 500, P2D); //fullScreen(P2D); //noCursor(); m[0] = new GLmovie_ext(); m[0].mov = new GLMovie(this, "clock_red.m4v", GLVideo.MUTE); m[1] = new GLmovie_ext(); m[1].mov = new GLMovie(this, "clock_green.m4v", GLVideo.MUTE); thread("loadMovies"); } void loadMovies() { m[0].mov.loop(); m[1].mov.loop(); m[0].mov.volume(0); m[1].mov.volume(0); while (! m[0].mov.playing() || ! m[1].mov.playing()) delay(10); m[0].length = m[0].mov.duration(); m[1].length = m[1].mov.duration(); while ( m[0].length < 32 || m[1].length < 32 || abs( m[0].length - m[1].length ) > 0.1 ) { m[0].length = max( m[0].length, m[0].mov.duration()); m[1].length = max( m[1].length, m[1].mov.duration()); } now_showing = 1; runTime = (m[0].length + m[1].length) / 2.0; loaded = true; } float cumulError = 0; int drawCnt = 0; float runTime; void draw () { background(0); clear(); if (!loaded) { textSize(10); fill(255); text("loading ...", width/2, height/2); } else { if (m[now_showing].mov.available()) m[now_showing].mov.read() ; image( m[now_showing].mov, (width-m[now_showing].mov.width)/2, (height-m[now_showing].mov.height)/2); int alternate = (now_showing+1) %2; if ( runTime < m[now_showing].mov.time() + m[alternate].mov.time() ) { float cutPoint = m[now_showing].mov.time(); alternate = now_showing; now_showing = (now_showing+1) %2; cutPoint = random(0.99)save+(runTime-save); // in the range from here to other's end point // now get alternate where we need it float distance = abs(cutPoint - save); float gap = runTime - 2distance; // -1 .. -ve --> overshoot +ve means time in hand .. +1 float correction = save + gap; while (correction > runTime) correction -= runTime; m[alternate].mov.jump( correction); } } stroke(color(#FF0000)); fill(color(#FF0000)); line(0, 10, width * (m[0].mov.time()/runTime), 10); if (now_showing == 0) { ellipse(0, 10, 10, 10); } stroke(color(#00FF00)); fill(color(#00FF00)); line(width * (1-m[1].mov.time()/runTime), 20, width, 20); if (now_showing == 1) { ellipse(width, 20, 10, 10); } drawCnt++; text(drawCnt, 40, 40); if (drawCnt % 1000 == 0) System.gc(); }
Answers
GO back edit your post
Select code
Hit ctrl-o
Empty line before and after the code
Would you expect that to do a multi-level pretty print ? (I am using a chromebook so am used to quirks of nature )
Ctrl-t in the pde editor will indent stuff nicely. Then paste it here, highlight it and hit Ctrl-o.
So I have indented and reposted... Watching this from top command, it appears to be running, burning the same amount of CPU and memory. Just not getting to draw() anything
The jump() always hang. I spent a lot of time with that, and I couldn't find any solution.
I haven't tried this fork yet
Maybe it solves the problem.
But don't use jump() with the current version of the library. Your program will always hang, it is just a matter of time.
@RaulF : thanks for joining in, will take a look at the fork
You are welcome. Let me know if it works.
prospect of being 140 commits behind is too daunting. I will have to park this project and hope @gohai can find time to think about this | https://forum.processing.org/two/discussion/26521/script-dies-quietly-no-logs-memory-gc | CC-MAIN-2020-40 | refinedweb | 674 | 68.47 |
eregi has been deprecated for quite some time. You could replace this
function validate_email($email) { return eregi("^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$", $email); }
With this
function validate_email( $email ){ return ( filter_var( $email,FILTER_VALIDATE_EMAIL ) && preg_match( '~\.[a-z][\w]+$~i',$email ) ); }
It is up-to-date, faster, and more accurate (the ereg pattern the script uses would give quite a few false negatives—it would reject several of my email addresses, for example).
You’ll notice that anything can be entered in the name and message sections and the form will be sent …What can be done to make this secure?
There is no possible way to know if the name or message the visitor provides is legitimate. Yes, you may get some spam messages. What this (any) form is trying to prevent is automated spam (which is the much more common kind).
Validating email addresses is a similar situation: you can check that a string looks like an email address. You could even try sending a test email to see if it is a real email address*. But there is no way to be sure that the email address belongs to the visitor until you send them an email, and they send you one back confirming that it is indeed theirs.
* (though this will not always work, and never works quickly. in practice, it is usually not worthwhile to bother with.)
In practice, this will stop a lot of potential spam. The form checks for:
As I mentioned earlier, the “honeypot” field would be much more effective if it changed every time the form was displayed. Unfortunately, this particular script would break (and would need to be completely rewritten) if we made that change.
One last item: do not allow file uploads with this script. That aspect is horribly insecure and could compromise your server. I would try changing this part of the
Validate function:
//file upload validations if(!empty($this->fileupload_fields)) { if(!$this->ValidateFileUploads()) { $ret = false; } }
To this:
//file upload validations //if(!empty($this->fileupload_fields)) //{ //if(!$this->ValidateFileUploads()) //{ // $ret = false; //} //} if(!empty($this->fileupload_fields)) { exit(1); }
From what I can tell, this shouldn’t affect the rest of the script unless someone tries to forge a file upload. Don’t make this change until the form is working properly, and then, make it separately from any other changes. If it causes problems, let me know what happens and we can troubleshoot it.
Greetings traq,
I replaced the function validate_email($email) in the fgcontactform.php file as you instructed, and after doing so and testing the form, I receive no email and the thank you page no longer shows. Instead the url indicates the page is the contact form page but the form is gone. I double checked to make sure I replaced only, and all of, the code you indicated and believe I did. I’m sure I’m missing something however.
Best Regards.
Greetings traq,
I’m sorry for the long delay in replying. I’ve been away for two weeks due to a family medical emergency and just returned Friday last.
After reviewing what we were doing and becoming acquainted again, here is a new pastebin of the fgcontactform.php file. I changed the
function validate_email($email) portion of the code, but not the
//file upload validations.
Best Regards.
Greetings traq,
Just curious if you discovered where I’m goofing this up?
Best Regards.
Greetings traq,
Just curious if I have upset you in some way? It certainly wasn’t intentional if so.
Best Regards.
Let me get caught up on this again. I’ll do some testing later today.
If there isn’t a solution to this I understand, but would appreciate knowing so I can move on with at least a direct link to email address, warts and all.
I asked for a contact form elsewhere and seems to be a dead end too as it’s fraught with problems and no example/demo.
Best Regards.
Here’s a new pastebin for the fgcontactform.php
Best Regards.
You must be logged in to reply to this topic.
*May or may not contain any actual "CSS" or "Tricks". | http://css-tricks.com/forums/topic/helpsuggestions-with-a-contact-form-please/page/3/ | CC-MAIN-2014-41 | refinedweb | 703 | 65.12 |
: Introductory
Roland Barcia (barcia@us.ibm.com), Software Services for WebSphere, IBM
15 Jul 2002
Application logging can involve documenting anything from system exceptions to application tracing to debugging. This article helps application architects and developers build an asynchronous logging application using log4j and JMS. It builds the logging application using WebSphere Studio Application Developer Version 4.0 and WebSphere MQ Version 5.2.
Introduction
As most of us know, logging in an application helps identify many problems that occur during a system lifetime. Application logging can involve documenting anything from system exceptions to application tracing to debugging. This article is about building an asynchronous logging application using log4j and JMS. We will build the logging application using WebSphere™Studio Application Developer and WebSphere MQ. The article will benefit application architects and developers.
Issues with logging in a distributed environment
In a distributed Web application, with the application crossing the machine barrier, centralized logging is a challenge. Architects have been forced to incorporate more sophisticated logging solutions into their design.
Logging in a distributed environment introduces many issues:
Creating a simple logging framework can solve most of these issues. In our sample application, we will configure Jakarta's log4j to work with JMS and WebSphere MQ. By using these technologies, we solve the issues stated above.
Benefits of using Jakarta log4j
By using log4j, developers make use of an open source easy-to-use interface. log4j lets developers use different message formats allowing for message structure, such as XML to be used. This makes the framework extensible. log4j also allows messages to contain different target outputs based on a configuration filter. This allows for some level of control and maintenance. Please see
more information about log4j
.
Combining log4J with JMS and WebSphere MQ lets
us expand our logging framework into the J2EE world and
the enterprise. Applications can write a message to a
MQ queue. Using JMS, the application can run under any
compliant J2EE Container. This makes the logging framework
reusable across different J2EE applications. More
important, the log messages are written asynchronously,
which means the application does not have to wait for a
response. It can write the message and continue, thus
allowing the logging solution not to hinder
performance.
WebSphere MQ (formerly MQSeries) is an industry-leading message-oriented-middleware solution. WebSphere MQ is available on multiple platforms. WebSphere MQ implements the JMS standard defined in the J2EE standard. Using WebSphere MQ, messages can go to a single centralized point. Moreover, you get all the benefits of a seasoned messaging server. WebSphere MQ can interact with monitoring tools that perform many administrative functions such as paging an administrator. You can also write programs to read messages from a queue and log it into a relational database, flat file, bit-bucket, or external systems. Furthermore, you can adopt certain filtering mechanisms to ignore certain messages and alert the proper administrator based on severity.
Once the technologies are chosen, you can use it to create a logging architecture as shown in Figure 1 below.
The details of the Logging Server and the Logging Application are separated from the application. Applications now write message logs and don't care where they go.
Sample technology
In our sample, we will configure log4j to work with JMS as shown in Figure 2 below.
The products used for the configuration described in this article are listed below. A familiarity with the basic operations of these products is assumed.
Building the sample application
In this section, we will walk through the steps needed to get our sample working. First, we configure and test the example in WebSphere Studio Application Developer.
Step 1. Importing an EAR file
We are going to create a simple Web application that logs to WebSphere MQ. The first step is to create a Web and an EAR project.
LOG4JDemoWeb.war
log4j.jar
Please see more information on
utility jar packaging
.
Step 2. JNDI and JMS caching classes
Next, we will use a few JNDI and JMS convenience classes for several reasons. You can
download the classes below
.
Since performance is a key consideration, caching JMS objects helps.
After examining the downloaded classes, we can see our caching mechanism uses Service Locator and Service Factory classes. These classes implement common J2EE design patterns (please see
Core J2EE Patterns
below). The classes are located under com.ibm.logdemo.servicelocator and com.ibm.logdemo.servicefactory.
Note
: These classes are for demo purposes; more design should be placed on these aspects of the architecture.
ServiceLocator class is located in the
com.ibm.logdemo.servicelocator
package. It is used to hide JNDI complexity. Classes needing to lookup JNDI Objects can call the lookupObject method. (Note, I lazy initialized the JNDIServiceLocator class to allow the class to be serialized.) Please see the
lookupObject method
.
com.ibm.logdemo.servicelocator
Under the
com.ibm.logdemo.servicefactory
package, there are a few classes that implement JNDI Object caching. All the factory classes extend the
ServiceFactory
class that implements common caching behavior. The
JMSServiceFactory
class caches JMS Connection Factories, Queues, and Topics. It also caches a hidden Session to enable WebSphere MQ Caching. Please examine the classes from the downloaded source.
com.ibm.logdemo.servicefactory
ServiceFactory
JMSServiceFactory
Step 3. log4j JMS Appender class
Next, we create a custom log4j Appender. An Appender class allows log4j to redirect the log to different outputs. There is an existing TOPIC based Appender; however, for this demo, we will make our own JMS Queue based Appender for simplicity. The log4j Appenders exist for download on the Jakarta site; please see
more information on log4j Appenders
.
In order to write an Appender, we need to extend log4j's
AppenderSkeleton
class. By doing this, your application can intercept the Logging Event and redirect it to your desired output. The
JMSQueueAppender
class is located under the
com.ibm.logdemo.appender
. Please see the
source code
that illustrates the key methods in the class.
AppenderSkeleton
JMSQueueAppender
com.ibm.logdemo.appender
This is the heart of the log4j and JMS interaction. Here we can take the event and use our JMS service classes to redirect our output. We also set the requiresLayout() method to true because the message will have custom layout (we will see this later).
If we want to extend this example further, rather than hard code the queue factory name and queue, you can have messages routed to different queues based message types, however, we can accomplish this better using a log4j configuration file (see the
Jakarta Web site
). The close method is there in your appender to open some output sources that need to be closed; for this example, we are not utilizing this.
Step 4. Simple XML Layout and Message classes
For this example, we will create a small custom XML type layout to demonstrate how log4j message formats may be customized. The intent here is not to show XML best practices, just log4j functionality.
In order to create our own layout, we need to extend the log4j Layout Class. This way, we can intercept the logging event and format it on our own. Before doing this, we will illustrate an interface and a value object class. The interface gives the Layout class a way to grab the XML message from the value object. The interface provides a convenient XML message similar to the toString() method of the Object class. The XMLMessage interface is listed below. It belongs in the
com.ibm.logdemo.message
package.
com.ibm.logdemo.message
package com.ibm.logdemo.message;
import java.io.Serializable;
/**
* Base interface for ValueObjects that need to be
* converted to XML
* Creation date: (1/15/2002 9:13:59 AM)
*/
public interface XMLMessage extends Serializable
{
public String toXML();
}
We now can extend the XMLMessage Interface and override the toXML() method, Please examine the class and look at the
overridden toXML() message
.
The valueobject contains a couple of sample fields for our log message. Now we will look at our Layout class. As stated above, we override the log4J Layout class to create our own Layout. We will use the XML interface to do this. All valueobjects that use this Layout must implement the XMLMessage interface. The Layout is located in the
com.ibm.logdemo.message
package. The key to the class is the format method listed below.
public String format(LoggingEvent event)
{
StringBuffer sbuf = new StringBuffer(2000);
sbuf.setLength(0);
XMLMessage message = (XMLMessage)event.getMessage();
sbuf.append( message.toXML() );
sbuf.append(LINE_SEP);
return sbuf.toString();
}
Some of the methods have been deprecated, but the main one isn't. The format() method is the key here. Since the valueobject will be the logged message, we can cast to an XMLMessage interface and grab the XML format. Then we just return it as a String. Now that we are finished writing a Layout class, we will see how the Appender gets associated with the Layout class under the log4j configuration section.
Step 5. Log Wrapper Class
Although the log4j API is easy to use, we will use a wrapper class to create a standard way of using the API on a project. Basically, this entails wrapping the log4J Category class to write messages. The Category class works with the configuration file to create the proper filtering level. log4j allows log messages to be filtered based on Java packages. This allows for the ability to write messages to different or multiple outputs based on where you are in your Java-packaging scheme. Furthermore, you can have different levels of logging. log4j defines 5:
Each level of logging is more severe than the next. For example, if I set my logging level for a particular package to WARN, only WARN, ERROR, and FATAL will be logged. log4j allows for this configuration to be done programmatically or configurable. We will not delve into advanced log4j filtering here. For more information, visit the
Jakarta Web site
.
For our sample, we will just filter at the root level. It is located in the
com.ibm.logdemo.appender
package. The main point of the class is to create an easy log interface and convert the log to our valueobject. We could have created different value objects for different logs, however for this demo we will use one. We could have made the Log class a Singleton Object.
Step 6. log4j configuration file
Finally, we will create a log4j configuration file. As stated above, the log4j configuration file can be designed to create a powerful filtering and output location. Its main purpose is to associate an Appender with a Layout. The file can go anywhere in the CLASSPATH. In our sample, I created a very simple configuration. I put it under the
/LOG4JdemoWeb/web applications/WEB-INF/classes/BasicConfig.lcf
. Here is how it looks:
/LOG4JdemoWeb/web applications/WEB-INF/classes/BasicConfig.lcf
#Sets the root level to DEBUG, which means every log
#message will be displayed
log4j.rootCategory=DEBUG,
The comments explain the links. The key here is with proper architecture, one can change the behavior of your logging without changing code. To learn more about this feature, see the
Jakarta Web site
.
Step 7. Test servlet and JSP to write to log
Next, we will look at a test servlet and JSP used to write messages to the LOG. The servlet will only use the wrapper class. The code for the LogServlet is located under the
com.ibm.logdemo.servlet
package. The JSP is under the web applications directory root. Basically, the LogServlet writes some test messages to a queue and forwards to a success page JSP. Please see the
goGet method
that writes to the log.
com.ibm.logdemo.servlet
Step 8. Create test servlet and JSP to read log for verification
Finally, we have also created a
ReadLogServlet and LogDisplay.jsp
to read the queue and display the messages. The servlet is located under
com.ibm.logdemo.servlet
and the JSP is under the web application folder.
ReadLogServlet and LogDisplay.jsp
The servlet simply browses a queue and displays the log on the screen. Since we are in a browser, Internet Explorer will not display the XML tags; however, when we view the source, we will see the XML syntax. The servlet and JSP code does not necessarily follow best practices, but we just want to test our results.
Creating the MQSeries Queue
We will now create a single queue for this sample. I am using MQSeries (WebSphere MQ) Version 5.2.1 and the latest MA88 package. We will use MQSeries Explorer to create the queue. Figure 4 below shows the the MQSeries Explorer Window for creating a local queue.
The Queue name is
LOG4JQUEUE
. My Queue Manager name is
QM_ibmroly2
. Your Queue Manager name will vary.
LOG4JQUEUE
QM_ibmroly2
Step 9. Run JMSAdmin Script for JNDI and JMS Objects
We need to configure JMS to the JNDI inside the Application Developer test environment. You can run the JMSAdmin located in your
MQ_INSTALL_PATH\Java\bin
. This can be done inside the Application Developer or at the command line. Since the Application Developer uses WebSphere Single Server, we need to use the Sun reference JNDI to register the objects and configure WebSphere Single Server point it. If this were WebSphere Advanced Full version, Sun reference implementation would not be necessary.
MQ_INSTALL_PATH\Java\bin
Before running JMSAdmin, we need to ensure we have the following entries set in our PATH.
PATH
MQ_INSTALL_PATH \bin
MQ_INSTALL_PATH \Java\bin
MQ_INSTALL_PATH \Java\lib
Also, the following jar files that are located in the
MQ_INSTALL_PATH\Java\lib
need to be in the
CLASSPATH
MQ_INSTALL_PATH\Java\lib
CLASSPATH
com.ibm.mq.jar
com.ibm.mqbind.jar
com.ibm.mqjms.jar
fscontext.jar
providerutil.jar
connector.jar
Next, use this code to configure the
JMSAdmin.configj
file to point to the correct JNDI.
JMSAdmin.configj
Notice PROVIDER_URL, we need to create a directory on our hard drive that matches the directory in the file above.
Note
: For the development environment, we will use the Sun Context to host our JNDI Bindings. The test environment in Application Developer does not support permanent bindings for JMS inside the JNDI. When we deploy to WebSphere 4.0 Advanced Edition, we will bind the JMSAdmin directly in the WebSphere 4.0 JNDI.
Next, we need to create a
JMSAdminScript.scp
file. The file contains the JNDI Bindings. The file is listed below
JMSAdminScript.scp
DEFINE CTX(jms)
CHANGE CTX(jms)
DEFINE QCF(LogConnectionFactory)
DEFINE Q(LogQueue) QUEUE(log4JQUEUE)
DISPLAY CTX
END
We do not need to list the Queue Manager here because we are using our default Queue Manager.
Finally, we can run the script as follows:
JMSAdmin < c:\ _\JMSAdminScript.scp
Step 10. Run the WebSphere test environment
To create a simple server project, right-click the
EAR Project
folder and choose
Run On Server
. (We can use an existing server project in our workspace). Next, we need to stop the server to alter our server configuration. Under the Server Perspective, in the Servers View, right-click your
Server Instance
and choose
Stop
.
Step 11. Run WebSphere administrative client to create external JMS and JNDI bindings
Now, let's update the server configuration and enable our administrative client.
We need to configure WebSphere MQ (MQSeries) as our JMS Provider as shown in Figure 5 below.
The Server ClassPath should contain the same JAR files we needed to run JMSAdmin. (The
connector.jar
is only necessary for Single Server). Furthermore, we need to put the same Initial Context and URL as the one we chose inside the
JMSAdmin.config
file. Next, we will create our QueueFactory and Queue Bindings and point them to the ones inside the Sun Context. Please see Figure 6 for the Connection Factory and Figure 7 for the Queue Binding.
connector.jar
JMSAdmin.config
Notice that for both, the JNDI name uses the forward slash and the external name uses the backslash. (This is only for the Sun implementation on the Windows platform, any UNIX-based system requires the forward slash for both.) Finally, we can save our configuration and exit the administrative client. There should be a link on the page prompting you to do so.
Step 12. Test the application
Now, we will run the LogServlet and write some messages. From any navigator view on any perspective, right-click our
Web Project
and choose
Run On Server
. Your web page should be displayed in Application Developer just like Figure 8.
Web Project
We have written some messages on the queue. If we check the MQSeries Explorer as in Figure 9, we will see five messages on the queue,one for each level of logging.
Now, we can click
Submit
and see our log messages. The page should look like Figure 10.
To see the XML format, we can do a view source on the Web page. We should see something like this:
<mylog4j:event>
<category>
DEBUG
</category>
<class-name>
com.ibm.logdemo.servlet.LogServlet
</class-name>
<date>
Tue Jun 04 15:27:03 EDT 2002
</date>
Debug Test
</mylog4j:event>
Next, we can change the level of logging by updating the BasicConfig.lcf. We will change the logging level to ERROR as follows by setting the rootCategory=ERROR
#Sets the root level to ERROR, which means every log message
#will be displayed
log4j.rootCategory=ERROR,
Now, go back and rerun the LogServlet and see the result. As you can see, only two additional messages were added. The Debug, INFO, and Warn messages are ignored. If we look at the queue, we should only have 7 messages as shown in Figure 11.
Deploying the application and creating a server group
Now, we can deploy the application to WebSphere 4 Advanced Edition and create a server group with two clones to show how-to processes that can write to a centralized location.
Step 1. Deploy the application to WebSphere 4.0 Advanced Edition
To deploy the application on to WebSphere 4.0 Advanced Edition, we will create two application server clones on the same machine. The purpose is to demonstrate two application servers writing to a central log.
First, right-click the
EAR file
and select
export ear
to export the EAR file from WebSphere Studio. (Alternatively, you can just use the EAR you imported to Application Developer.) I exported it directly to the installable apps directory of my WebSphere 4. 0 installation directory. Please refer to the
WebSphere 4. 0 Advanced Edition Handbook
for how to deploy applications to WebSphere. Next, we will bring up the WebSphere Admin Console and create an application server called
LogServer
. Right-click
Application Servers
under your node and click
New
. Please enter
LogServer
as the application server name as seen in Figure 12.
To install our EAR file onto the application server, click
Console
=>
Wizards
=>
Intall Enterprise Application
. Navigate to the
EAR file
in the
Installable Apps
directory and select the
EAR file
we exported as seen in Figure 13.
Go through the wizard leaving all the defaults, until you get to the selecting application servers screen as seen in Figure 14. Press
Select Server
and choose your application server. Click
and
Finish
.
Step 2. Create Server Group and clone
Next, we will create a Server Group and a clone to replicate our application server with the installed application. This will allow us to demonstrate our distributed log. First, we create the Server Group, which is a template for our application servers. We create the Server Group by using our existing application server. For more information on WebSphere 4.0 Cloning, please refer to the
WebSphere Advanced Edition 4.0 Handbook
or the
WebSphere 4.0 Advanced Edition Scalability and Availability
.
To create the Server Group, right-click
Log Server
and choose
Create Server Group
. We will call the Server Group, LogServerModel as seen in Figure 15. Leave all the other defaults and click
OK
.
Next, we will create a new clone from the Server Group.
Note
: The original LogServer now becomes a clone of the Server Group.
Right-click the
Server Group
and select
New
=>
Clone
.
We will call it LogServer2 and assign it to our machine. See Figure 16
Ensure that the regenerate plugin option is set to true for our demonstration purposes. This can be set to true under the custom tab of our Server Group. For clarity, we also assigned each clone a different Standard Out and Standard Error file to show both our application servers are writing to the application server (see Figure 17). We can do this by selecting each clone in under our machine (node), going to the file tab and putting in a unique name for each standard out and error.
Note
: Make sure to press
Apply
after each change is made to a configuration on our application server.
Step 3. Rerun JMSAdmin for WebSphere Advanced Edition and configure through the Admin Client
Now, we can set up our JMS configuration. We will assume that MQSeries is properly configured and a JMS Provider and that it is installed properly on our machine and node. Please see
related references
for instructions on how to configure MQSeries with WebSphere 4.0. First, we need to modify our JMSAdmin configuration file to point to WebSphere 4.0 as our JNDI Server. We can do this by commenting our fscontext InitialContextFactory and uncommenting our WebSphere one. We will do the same for our PROVIDER_URL. Please see the
source code
.
Next, we will rerun out JMSAdmin script as we did before.
JMSAdmin < c:\=\JMSAdminScript.scp
Let's go to back to our WebSphere Admin Console and configure our Connection Factory and Queue. Although we ran our JMSAdmin Script, we need to configure our JMS Provider to point to these bindings. WebSphere treats all JMS providers as external although the bindings are really internal. Under Resources and IBM MQSeries, you can create a Connection Factory and Queue Binding by right clicking Connection Factories or Queues. Figures 18 and 19 show the wizard for creating these bindings.
Step 4. Test the application
Now, we will start up our server group and test our application. We will rerun the LogServlet multiple times and then look at the stdout and stdout2 file to see that both application servers are writing to a centralized queue. (I cleared out the queue for the new test.)
To start up both clones, start up the ServerGroup, right-click your
Server Group
, and click
Start
. Also, ensure you start your HTTP Server.
Finally, we can run our application as we did before. Click
Refresh
a few times and then click the
ReadLog
button. This will ensure that both our clones receive requests to log.
We can then check our log files to see that two different application servers are logging to a central queue. Both stdout.txt and stdout2.txt should contain some statements.
Both logs should read as follows.
[6/4/02 15:27:03:861 EDT] 45ac3ad8 WebGroup I SRVE0091I: [Servlet LOG]: LogServlet: init
[6/4/02 15:27:03:891 EDT] 45ac3ad8 SystemOut U Entering Log Servlet
[6/4/02 15:27:03:991 EDT] 45ac3ad8 SystemOut U Entering append
[6/4/02 15:27:03:991 EDT] 45ac3ad8 SystemOut U Getting Factory
[6/4/02 15:27:04:281 EDT] 45ac3ad8 SystemOut U Getting queue connection
[6/4/02 15:27:04:281 EDT] 45ac3ad8 SystemOut U Getting session
[6/4/02 15:27:04:281 EDT] 45ac3ad8 SystemOut U Getting queue
[6/4/02 15:27:04:321 EDT] 45ac3ad8 SystemOut U Getting sender
[6/4/02 15:27:04:341 EDT] 45ac3ad8 SystemOut U Creating message
[6/4/02 15:27:04:341 EDT] 45ac3ad8 SystemOut U Setting test
[6/4/02 15:27:04:351 EDT] 45ac3ad8 SystemOut U Sending message
[6/4/02 15:27:04:401 EDT] 45ac3ad8 SystemOut U Message sent
[6/4/02 15:27:04:401 EDT] 45ac3ad8 SystemOut U Entering append
We have successfully implemented a centralized distributed log using JMS and log4j.
Conclusion
The sample above is only a stepping stone. Once we have the interface built, we can write a server side applications that can interpret the log and react. Perhaps we could use DB2 XML Extender to build a more formalized XML Schema for the database logs.
Application logging is a very important, and often overlooked, piece of the architectural process. By designing the logging architecture early on, we can come up with an optimal solution. Open Source and IBM's WebSphere, MQSeries, and DB2 Family give us the tools to do it.
Acknowledgements
David Salkeld, IBM Software Services for WebSphere
Related references
For more information on Jakarta log4j, MQSeries using Java, JMS, and J2EE patterns, see the following reference list:
Top of page
Download
About the author
Roland Barcia
is a senior software consultant for IBM Software Services for WebSphere in the New York/New Jersey Metro area. You can reach Roland Barcia at
barcia@us.ibm.com
.
Rate this page
Please take a moment to complete this form to help us better serve you.
Did the information help you to achieve your goal?
Please provide us with comments to help improve this page:
How useful is the information? | http://www.ibm.com/developerworks/websphere/library/techarticles/0207_barcia/barcia.html | crawl-002 | refinedweb | 4,187 | 57.47 |
Ink is a library for building and testing command-line applications using React components. Since it acts as a React renderer, you can use everything that React has to offer: hooks, class components, state, context, everything. Ink lets you build interactive and beautiful CLIs in no time. Here's basic implementation of Jest's UI (view source code):
I hope I had your curiosity, but now I need your attention. Let's step back a bit and check out the building blocks that Ink offers, which allow building such UIs as above. Here's how the most basic Ink app looks like:
import React from 'react'; import {render, Text} from 'ink'; const Hello = () => <Text>Hello World</Text>; render(<Hello/>);
Styling and colorizing output is essential for CLIs that want to look good. You can use Ink's built-in components such as
<Text> and
<Color>, which use everyone's beloved chalk library under the hood. It's as easy as this:
import {render, Color} from 'ink'; const Hello = () => <Color green>Hello World</Color>; render(<Hello/>);
Ink also implements Flexbox layout mechanism by leveraging Yoga Layout library from Facebook. You can finally forget about positioning elements in the output by using a bunch of spaces and
\n. With Ink, for the first time ever you can use properties like
flex,
flexDirection,
alignItems,
justifyContent,
margin,
padding and
width which you've only been able to use in the browser, until now. All
<Box>es in Ink are flexbox-enabled (think
<div style={{display: 'flex'}}/> by default). Here's an example layout to show you the power of Flexbox in CLIs:/>);
As I mentioned in the beginning, Ink supports all React features, such as state. If you know React, you know Ink already. In the following counter example, you can see that the only thing different here is
<Text> instead of
<span>:
import React, {useState, useEffect} from 'react'; import {render, Text} from 'ink'; const Counter = () => { const [count, setCount] = useState(0); useEffect(() => { const interval = setInterval(() => { setCount(count => count + 1); }, 100); return () => clearInterval(interval); }, []); return <Text>Count: {count}</Text>; }; render(<Counter/>);
React, Ink and Yoga combined provide a simple path towards creating beautiful, maintainable and testable command-line interfaces. Back in the day when we were working on AVA, I remember the fear of removing a space or a newline, which could mess up the output and fail tests. If we had Ink back then and embraced React components for generating output of our CLI, it would've been much easier to maintain and predict the consequences of the changes we were making. With Ink, you can test components individually or your app as a whole. You also don't need to think how to implement an interactive CLI output or how to properly accept input from the user. Ink took care of it for you, so you can deliver great CLIs faster than ever before.
It's really the future of writing interactive CLI tools.
I hope after trying out Ink you will think the same way Sindre does! Let me know on GitHub if you run into any issues or have some ideas on how to improve Ink!
On a personal note, it feels amazing to write this blog post, which concludes almost half a year of work, on and off. I want to thank Sindre for helping to shape Ink as it is today and providing extremely useful feedback and advice since day 0. Almost 2 years ago, we were only discussing what Ink could be on the remote Thai island at 1am with cocktails on the table!
I also want to thank Kat Marchán from npm team and Simen Bekkhus from Jest team for being early-adopters of Ink. Even if they don't end up using Ink in their projects, I'm still going to be happy that Ink was worth trying out! Kat's work and feedback helped stabilize Ink ahead of launch, which led to some important bug fixes and new features being introduced before the release.
Thank you! ❤️ | https://vadimdemedes.com/posts/building-rich-command-line-interfaces-with-ink-and-react | CC-MAIN-2019-22 | refinedweb | 671 | 56.79 |
On Wed, 2005-05-04 at 07:09 -0500, Josh Boyer wrote: > On Wed, May 04, 2005 at 01:32:57PM +0200, Michael Schwendt wrote: > > > > > >). > > I don't think what I'm proposing would change the spec file. If you have a > %{?dist} in your Release field, then it would evaluate to the correct value. > If a spec file didn't use %{dist} at all, then nothing happens anyway... The proposal I made (revision 240,764,842 or so) was the following: If you wanted to have "automagic" dist values set, you could (if implemented), pass a flag like "--usedist" to cvs-import.sh, or call something like "make tag-dist" where it is explicitly performing the magic, but not forcing it on those who don't give a red monkey's behind. In the interim, what I've been doing (because I am the law), is hardcoding dist tags into some of my packages to differentiate them. There are two branches now (FC-3 and devel), and in the worst forseeable case, we'll have four active branches, so thats a really minor one time spec file change to make. The primary reason I didn't want to hardcode the macros was to prevent people from abusing the priviledge like so: %define dist .FC3sucksandJoeWuzHereSoSuckIt But, in retrospect, I realized that we would hopefully catch most of these before they were built. So, here's how you can use dist tags, right now: If you want to use dist tags today, you have to hardcode the value in your spec. There is no buildsystem checking to enforce that you're doing it right, so I highly suggest that you checkin a spec for each branch without a dist tag, do a full cvs checkout, then make the changes, and cvs commit. In the spec, as the first two lines, you should put: %define dist .fc3 %define fedora 3 Where .fc3 is the appropriate value for the branch that the spec resides in. Currently, the only permitted values are: .fc3 .fc4 We're not building RHEL Extras (yet), so you shouldn't care about that or the RHL values (.el4 or .rhl8). (However, Sopwith and I wrote a shell script to do auto magic voodoo dist resolution, which should be in CVS for redhat-rpm-config already). In the same line, "fedora" is the only other var you should care about (rhl and rhel are the other correct values, but again, not used in FE). Once this is done, you can change your Release from: Release: 2 to Release: 2%{?dist} If you need to bump the release number, remember to change 2%{?dist} to 3%{?dist}. The second variable (%fedora) is there so that you can perform numeric conditionals like: # Do something for FC4 and beyond. %if "%fedora" >= "4" # ... %endif or distro conditionals like: # One-liners, here set a default switch. %{?fedora:%define _with_xfce --with-xfce} Now, here is the mini-FAQ: Q: Do I have to use dist tags? A: No. You don't. Q: Can I hardcode something other than .fc3 or .fc4 into %dist? A: No. Q: Does .fc3 have to be lowercase? A: Yes. This is for consistency. Q: Can't I just hardcode the .fc3 into the Release? A: No. Q: Can I put the actual release number after the %{?dist}? A: No. Q: I don't have any conditionals that use the %fedora macro, do I have to define it? A: Yes. Consistency (and it serves as a quick reminder that you've used the right value). Now, wrt to the automagic adding of dist, if there is enough interest in that, you can either wait until I've got the time to add these things to cvs-import.sh and the Makefile, or you can send me patches for review. Hopefully, that clears up dist tag usage (although, its just as likely to spawn another flame war). ~spot -- Tom "spot" Callaway: Red Hat Sales Engineer || GPG Fingerprint: 93054260 Fedora Extras Steering Committee Member (RPM Standards and Practices) Aurora Linux Project Leader: Lemurs, llamas, and sparcs, oh my! | http://www.redhat.com/archives/fedora-extras-list/2005-May/msg00076.html | CC-MAIN-2015-22 | refinedweb | 684 | 72.05 |
ActAsTextcaptcha
ActsAsTextcaptcha provides spam protection for your Rails models using logic questions from the excellent Text CAPTCHA web service (by Rob Tuley of Openknot). It is also possible to configure your own text captcha questions (instead, or as a fall back in the event of any remote API issues).
This gem is actively maintained, has good test coverage and is compatible with Rails >= 3.0.0 (including Rails 4). If you have any issues please report them here.
Logic questions from the web service are aimed at a child's age of 7, so they can be solved easily by even the most cognitively impaired users. As they involve human logic, questions cannot be solved by a robot. There are both advantages and disadvantages for using logic questions over image based captchas, find out more at Text CAPTCHA.
Demo
Try a working demo here!
Installing
NOTE: The steps to configure your app changed with the v4.0.* release. If you are having problems please carefully check the steps or upgrade instructions below.
First add the following to your Gemfile, then `bundle install`;
gem 'acts_as_textcaptcha'
Next grab an API key for your website, then add the following code to models you would like to protect;
class Comment < ActiveRecord::Base # (this is the simplest way to configure the gem, with an API key only) acts_as_textcaptcha :api_key => 'PASTE_YOUR_TEXTCAPTCHA_API_KEY_HERE' end
Next in your controller's new action you'll want to generate and assign the logic question for the new record, like so;
def new @comment = Comment.new @comment.textcaptcha end
Finally, in your form view add the textcaptcha question and answer fields using the textcaptcha_fields helper. Feel free to arrange the HTML within this block as you like;
<%= textcaptcha_fields(f) do %> <div class="field"> <%= f.label :textcaptcha_answer, @comment.textcaptcha_question %><br/> <%= f.text_field :textcaptcha_answer, :value => '' %> </div> <% end %>
NOTE: If you'd rather NOT use this helper and would prefer to write your own form view code, see the html produced from the textcaptcha_fields method in the source code.
Upgrading from 3.0.10
Due to a relatively large hole that could allow bots to by-pass textcaptcha's, it was nessecary to re-engineer the gem for the v4.0.* release. Thanks to Jeffrey Lim for spotting this and raising the issue. Upgrading is straightforward;
Rename `spam_question` to `textcaptcha_question`
Rename `spam_answer` to `textcaptcha_answer`
Any strong parameter calls should include the `textcaptcha_answer` and `textcaptcha_key` fields;
params.require(:comment).permit(:textcaptcha_answer, :textcaptcha_key, ... )
Toggling Textcaptcha
You can toggle textcaptcha on/off for your models by overriding the `perform_textcaptcha?` method. If it returns false, no questions will be fetched from the web service and textcaptcha validation is disabled.
This is useful for writing your own custom logic for toggling spam protection on/off e.g. for logged in users. By default the `perform_textcaptcha?` method checks if the form object is a new (unsaved) record.
So out of the box, spam protection is only enabled for creating new records (not updating). Here is a typical example showing how to overwrite the `perform_textcaptcha?` method, while maintaining the new record check.
class Comment < ActiveRecord::Base acts_as_textcaptcha :api_key => 'YOUR_TEXTCAPTCHA_API_KEY' def perform_textcaptcha? super && user.admin? end end
More configuration options
You can configure acts_as_textcaptcha with the following options;
api_key (required) - get a free key from textcaptcha.com/api
questions (optional) - array of question and answer hashes (see below) A random question from this array will be asked if the web service fails OR if no API key has been set. Multiple answers to the same question are comma separated (e.g. 2,two). So do not use commas in your answers!
cache_expiry_minutes (optional) - minutes for answers to persist in the cache (default 10 minutes), see below for details
http_read_timeout (optional) - Net::HTTP option, seconds to wait for one block to be read from the remote API
http_open_timeout (optional) - Net::HTTP option, seconds to wait for the connection to open to the remote API
For example;
class Comment < ActiveRecord::Base acts_as_textcaptcha :api_key => 'YOUR_TEXTCAPTCHA_API_KEY', :http_read_timeout => 60, :http_read_timeout => 10, :cache_expiry_minutes => 10, :questions => [{ 'question' => '1+1', 'answers' => '2,two' }, { 'question' => 'The green hat is what color?', 'answers' => 'green' }] end
YAML config
The gem can be configured for models individually (as shown above) or with a config/textcaptcha.yml file. The config file must have an api_key defined and optional array of questions. Options definied inline in model classes take preference over the configuration in textcaptcha.yml. The gem comes with a handy rake task to copy over a textcaptcha.yml template to your config directory;
rake textcaptcha:config
Confguring without the TextCAPTCHA web service
To use only your own logic questions, simply ommit the api_key from the configuration and define at least 1 logic question and answer (see above).
Translations
The gem uses the standard Rails I18n translation approach (with a fall-back to English). Unfortunately at present, the Text CAPTCHA web service only provides logic questions in English.
en: activerecord: errors: models: comment: attributes: textcaptcha_answer: incorrect: "is incorrect, try another question instead" expired: "was not submitted quickly enough, try another question instead" activemodel: attributes: comment: textcaptcha_answer: "Textcaptcha answer"
Without Rails or ActiveRecord
Although this gem has been built with Rails in mind, is entirely possible to use it without ActiveRecord, or Rails. As an example, take a look at the Contact model used in the test suite here.
Please note that the built-in TextcaptchaCache class directly wraps the Rails.cache. An alternative TextcaptchaCache implementation will be nessecary if Rails.cache is not available.
Testing and docs
In development you can run the tests and rdoc tasks like so;
rake test (all tests)
rake test:coverage (all tests with code coverage)
rake rdoc (generate docs)
What does the code do?
The gem contains two parts, a module for your ActiveRecord models, and a single view helper method. The ActiveRecord module makes use of two futher classes, TextcaptchaApi and TextcaptchaCache.
A call to @model.textcaptcha in your controller will query the Text CAPTCHA web service. A GET request is made with Net::HTTP and parsed using the default Rails ActiveSupport::XMLMini backend. A textcaptcha_question and a random cache key is assigned to the record. An array of possible answers is stored in the TextcaptchaCache with this random key. The cached answers have (by default) a 10 minute TTL in your cache. If your forms take more than 10 minutes to be completed you can adjust this value setting the `cache_expiry_minutes` option. Internally TextcaptchaCache wraps Rails.cache and all cache keys are namespaced.
On saving, validate_textcaptcha is called on @model.validate checking that the @model.textcaptcha_answer matches one of the possible answers (retrieved from the cache). By default, this validation is only carried out on new records, i.e. never on edit, only on create. All attempted answers are case-insensitive and have trailing/leading white-space removed.
Regardless of a correct, or incorrect answer the possible answers are cleared from the cache and a new random key is generated and assigned. An incorrect answer will cause a new question to be prompted. After one correct answer, the answer and a mutating key are sent on further form requests, and no question is presented in the form.
If an error or timeout occurs during API fetching, ActsAsTextcaptcha will fall back to choose a random logic question defined in your options (see above). If the web service fails or no API key is specified AND no alternate questions are configured, the @model will not require textcaptcha checking and will pass as valid.
For more details on the code please check the documentation. Tests are written with MiniTest. Pull requests and bug reports are welcome.
Requirements
What do you need?
Rails >= 3.0.0 (including Rails 4)
Rails.cache - some basic cache configuration is nessecary
Ruby >= 1.9.3 (also tested with 2.0.0, 2.1.1, 2.2.1) - 1.8.7 support ended at version 4.1.1
Text CAPTCHA API key (optional, since you can define your own logic questions)
MiniTest (optional if you want to run the tests, built into Ruby 1.9)
SimpleCov (optional if you want to run the tests with code coverage reporting)
Note: The built-in TextcaptchaCache class directly wraps the Rails.cache object.
Rails 2 support
Support for Rails 2 was dropped with the release of v4.1.0. If you would like to continue to use this gem with an older version of Rails (>= 2.3.8), please lock the version to `4.0.0`. Like so;
# in your Gemfile gem 'acts_as_textcaptcha', '=4.0.0' # or in environment.rb config.gem 'acts_as_textcaptcha', :version => '=4.0.0'
Links
Who's who?
ActsAsTextcaptcha and little robot drawing by Matthew Hutchinson
Text CAPTCHA API and service by Rob Tuley at Openknot
Usage
This gem is used in a number of production websites and apps. It was originally extracted from code developed for Bugle. If you're happily using acts_as_textcaptcha in production, let me know and I'll add you to this list! | http://www.rubydoc.info/github/matthutchinson/acts_as_textcaptcha/frames | CC-MAIN-2015-32 | refinedweb | 1,490 | 64.3 |
wsdl2h man page
wsdl2h — the gSOAP WSDL/WADL/XSD processor for C and C++
Synopsis
wsdl2h [Options] SOURCE ...
Description
Please see /usr/share/doc/gsoap-doc/soapdoc2.html for details.
Converts a WSDL or XSD input file, or from an HTTP address, SOURCE to a declaration file that can be parsed by soapcpp2(1). If no SOURCE argument is specified, read from standard input.
Options
- -a
Generate indexed struct names for local elements with anonymous types.
- -b
Bi-directional operations (duplex ops) added to serve one-way responses.
- -c
Generate C source code.
- -c++
Generate C++ source code (default).
- -c++11
Generate C++11 source code.
- -d
Use DOM to populate xs:any, xs:anyType and xs:anyAttribute.
- -e
Do not qualify enum names.
- -f
Generate flat C++ class hierarchy.
- -g
Generate global top-level element declarations.
- -h
Display help info.
- -Ipath
Use path to find files.
- -i
Do not import (advanced option).
- -j
Do not generate SOAP_ENV__Header and SOAP_ENV__Detail definitions.
- -k
Do not generate SOAP_ENV__Header mustUnderstand qualifiers.
- -l
Display license information.
- -m
Use xsd.h module to import primitive types.
- -M
Suppress error "must understand element with wsdl:required='true'".
- -Nname
Use name for service prefixes to produce a service for each binding.
- -nname
Use name as the base namespace prefix instead of ns.
- -ofile
Output to file file.
- -P
Do not create polymorphic types inherited from xsd__anyType.
- -p
Create polymorphic types inherited from base xsd__anyType.
- -qname
Use name for the C++ namespace of all declarations.
- -R
Generate REST operations for REST bindings specified in the WSDL.
- -rhost[:port[:uid:pwd]]
Connect via proxy host, port and proxy credentials.
- -r:uid:pwd
Connect with authentication credentials (digest auth requires SSL).
- -s
Do not generate STL code (no std::string and no std::vector).
- -tfile
Use type map file file instead of the default file typemap.dat.
- -U
Allow UTF8-encoded Unicode C/C++ identifiers when mapping XML tag names.
- -u
Do not generate unions.
- -V
Display the current version and exit.
- -v
Verbose output.
- -W
Suppress warnings.
- -w
Always wrap response parameters in a response struct (<=1.1.4 behaviour).
- -x
Do not generate _XML any/anyAttribute extensibility elements.
- -y
Generate typedef synonyms for structs and enums.
- -z1
Compatibility with 2.7.6e: Generate pointer-based arrays.
- -z2
Compatibility with 2.7.7 to 2.7.15: Qualify element/attribute references.
- -z3
Compatibility with 2.7.16 to 2.8.7: Qualify element/attribute references.
- -z4
Compatibility up to 2.8.11: Do not generate union structs in std::vector.
- -z5
Compatibility up to 2.8.15.
- -z6
Compatibility up to 2.8.17.
- -_
Do not generate _USCORE (replace with UNICODE _x005f).
See Also
soapcpp2(1).
Author
This manual page was written by Thomas Wana <greuff@debian.org>, for the Debian project (but may be used by others).
Referenced By
soapcpp2(1). | https://www.mankier.com/1/wsdl2h | CC-MAIN-2017-47 | refinedweb | 474 | 55.81 |
trying?
I'm not 100% sure I understand what you want, but my guess is you want something like this:
# A toy class.
class AClass(object):
def __init__(self, astring):
self.astring = astring
def __repr__(self):
return "%s(%r)" % (self.__class__.__name__, self.astring)
# And some variations.
class BClass(AClass):
pass
class CClass(AClass):
pass
# Build a dispatch table, mapping the class name to the class itself.
TABLE = {}
for cls in (AClass, BClass, CClass):
TABLE[cls.__name__] = cls
# Get the name of the class, and an argument, from the command line.
# Or from the user. Any source of two strings will do.
# Data validation is left as an exercise.
import sys
argv = sys.argv[1:]
if not argv:
name = raw_input("Name of the class to use? ")
arg = raw_input("And the argument to use? ")
argv = [name, arg]
# Instantiate.
instance = TABLE[argv[0]](argv[1])
print instance | https://www.queryhome.com/tech/1797/polymoprhism-question-in-python | CC-MAIN-2021-10 | refinedweb | 145 | 79.97 |
Greetings! My name is Jon Sturgeon; I’m a developer in the Forefront team here at Microsoft. I’m happy to be able to contribute to the Visual C++ Team Blog as a “guest blogger”.
One of my passions when writing C++ code has always been to use as many techniques as possible to find bugs earlier and earlier in the development process; obviously the earlier that bugs are found the easier and cheaper they generally are to fix. And if they can be found and corrected before the code is even built, everybody wins.
I’m assuming that everybody is familiar with the compiler warning level in the Visual C++ compiler. It is exposed through the /W command-line switch and through the “Warning Level” item in the C/C++ projects’ properties page in the IDE:
The relevant part of the property page shown above is for a brand-new C++ project created in Visual Studio 2010. As you can see, the warning level is set to /W3 by default. However, I recommend you compile all your code at warning level 4 instead, since the increase in warning “noise” can be fairly minimal and there are some useful warnings that are only active with /W4 enabled. It is best-practice in many teams to ensure that all code compiles cleanly with /W4 enabled and the related option to treat all warnings as errors (/WX) is often also specified to ensure that code cannot be submitted without first addressing all the warnings identified by the compiler.
One warning option that isn’t so well-known is /Wall, shown in the IDE below:
This option (obviously) enables all warnings in the compiler. This of course leads to the question of what warnings are not enabled when /W4 is specified? The answer can be found on this page on MSDN which lists all the warnings that are “off by default” in the compiler. I’m not going to walk through each and every warning in this list, but you can see that many of them are very trivial and “noisy” warnings that you indeed are unlikely to want enabled on any realistic codebase. For instance, C4061 (“enumerator in switch statement is not explicitly handled by a case label”) is unlikely to identify any actual bugs and you’d probably end up quickly disabling it if it was not off by default.
However, as you scan through the list, you can see that some of the warnings might identify potentially serious problems. A couple of my favorites relate to virtual functions: C4263 (member function does not override any base class virtual member function) and C4264 (no override available for virtual member function; function is hidden). In both of these cases, I want to know when my code triggers the warning, since there is quite likely to be an underlying bug that at the very least needs to be investigated.
Since just enabling the /Wall switch on a real-world codebase is going to be unrealistic due to all the noise from the trivial warnings, is there a way to gain the benefits of some of these more useful warnings without suffering the pain of the less useful ones? Yes there is, and here’s the way I’ve approached this in the past:
Alternatively, you can use the same technique to selectively enable individual off-by-default compiler warnings and rebuild without adding the /Wall switch. However, I prefer the first approach, since that way I’m making explicit choices about which warnings I want disabled. Additionally, any future warnings that the compiler team adds in future releases will then be automatically enabled when the compiler is updated, at which time I can decide if it makes sense to keep them enabled.
One thing that you are likely to find when trying to build your codebase with many of these off-by-default warnings enabled is that some of the compiler/SDK-supplied header files do not compile cleanly. I know that the Visual C++ & Windows SDK teams are very good at ensuring all the standard headers will compile cleanly at warning level 4, but there are no such guarantees when enabling /Wall. Because of this, if you want to gain the benefits of building with some of these warnings enabled, you’ll need a solution to this problem. Unfortunately the best option I’ve found so far is to wrap the offending header file an a header of your own which temporarily disables the offending warnings and arrange for your code to #include that instead. For instance, if your code uses ATL, you may need to use a header similar to this:
#pragma warning(push)
#pragma warning(disable:4265)
#pragma warning(disable:4625)
#pragma warning(disable:4626)
#include <atlbase.h>
#pragma warning(pop)!--
code>
This header file temporarily disables three of the off-by-default warnings that atlbase.h can generate, includes the header, then re-enables the warnings so that they are active again for your code. If you can arrange for this small header file to be found in your codebase’s include path before any of the system headers, you can name it atlbase.h so you won’t have to modify any of your actual source code’s #include directives.
There are always false-positive scenarios with compiler warnings and the case is no different for the off-by-default warnings either. You’ll have to use your judgment for each warning that you want to enable to see if the number of false positives that are generated in your codebase outweigh the potential for catching a real bug. One example where I think it can be worth suffering a few false-positives is C4265 - class has virtual functions, but destructor is not virtual. This warning, when enabled, is triggered by code like this:
class Animal
{
public:
Animal();
~Animal(); //not virtual
virtual void MakeNoise();
};!--
code>
As you can see, the class has a virtual function, but the destructor is not declared virtual. This can be a real bug that can lead to memory leaks if objects that implement the Animal base class are expected to be created on the heap and later deleted through a pointer of Animal * type. Or this can be a false-positive (i.e. not a problem) if these objects have an alternative destruction mechanism, such as the virtual IUnknown::Release() method that all COM interfaces employ. Consequently, if you choose to build your code with this warning enabled, you’ll have false-positive warnings in any code that implements COM interfaces. At this point you’ll have to make a decision about whether the warning is likely to catch real bugs in your code; if you want to keep the warning enabled, you’ll have to temporarily disable it around the false-positive locations, using the #pragma warning method shown in the atlbase.h example above.
To sum up, here’s my recommendations:
As a starting point, I’d consider enabling these off-by-default warnings:
If you enable these warnings on your code and they help you to find real bugs, I’d love to hear about them in the comments.
Finally, I’d like to thank the Visual C++ team for allowing me to guest on their blog. Thanks!
I don't like the /FI approach.
I rather alter the command line options in the project properties and here's what i'm using:
/wd4986
Is there any way to add a warning for "member variable 'foo' is not initialised in constructor of class bar" for POD types? I've fixed many many bugs because someone forgot to initialize a bool or other POD (anything without a default constructor) in a constructor. Surely this doesn't require a static analyzer to figure out does it?
This is all dandy, but if you could fix/remove the warnings in your own header files it would make our lives easier.
Max.
When I ask people about this they say "Well we tried using /W4 here, but reverted the change when we started getting tons of warnings from Microsoft's own header files..." and "it'd be nice if you could tell VC to disable warnings when generated from files in the standard include path. Though, I guess that may be problematic for templates."
when i want debug program istream and iostream do not known by c++
please helpe me
@Max, Jonathan: Amen to that
I use more than one compiler. One of them is absolutely free, comes with complete source code, and compiles on and for every operating system I've ever used. It also has a -Wall option, and never complains about system header files. Amazing, isn't it?
Jon, I don't mean to beat up on you; you at least provided a workaround. But, seriously, instead of revamping the GUI every few years, breaking the Help system, and dithering with the command-line tools, why doesn't Microsoft undertake the basic engineering of patrolling its own header files to make them warning-free? It's got to be in the interest of both Microsoft and its customers: Either the warnings produce useful information that can be used to fix the header files, or they don't and are a disservice to everyone who would use them. Both the warning system and the header files are bound to be improved by the effort.
[James K. Lowden]
> It also has a -Wall option
VC's /Wall and GCC's -Wall are completely different. VC's /Wall literally means "all warnings". GCC's -Wall means "some useful warnings". GCC also has -Wextra, which means "more useful warnings". Even combined, -Wall -Wextra leaves out several useful warnings (e.g. -Wshadow). See gcc.gnu.org/.../Warning-Options.html for more info.
> why doesn't Microsoft undertake the basic engineering of patrolling its own header files to make them warning-free?
I can speak for our C++ Standard Library implementation. We aim to compile cleanly at /W4 /analyze, which contains very many useful warnings and very few obnoxious warnings. We don't attempt to compile cleanly at /Wall, because it contains pure noise warnings like "function not inlined" and "struct contains padding". (The idea behind those warnings is that they can be enabled for individual compilations of individual translation units, so developers can figure out what's getting inlined, etc., not that they should be enabled for regular builds. Our /Wall enables them because it does exactly what it says on the box.)
In the long run, I agree that we should identify /Wall's useful warnings, document them and probably bundle them in a switch like /W5, and make our headers compile cleanly at that level. While that would be valuable, we currently have more important things to do with our limited time. (Namely, correctness, performance, and C++0x features. Dinkumware and I are library developers, and we don't work on stuff like the IDE.)
I thought I asked this, but it seems like it got swallowed somewhere along the way.
Is it a bug that C4265 doesn't warn when the destructor isn't explicitly declared? There has been a couple of times that that has bit me in the past.
What approach is better for classes that implement COM interfaces:
1) use pragma around the class to disable C4265
2) make the destructor virtual but protected
What do you think? | http://blogs.msdn.com/b/vcblog/archive/2010/12/14/off-by-default-compiler-warnings-in-visual-c.aspx?Redirected=true&title=%E2%80%9COff%20By%20Default%E2%80%9D%20Compiler%20Warnings%20in%20Visual%20C++&summary=&source=Microsoft&armin=armin | CC-MAIN-2015-48 | refinedweb | 1,908 | 57.2 |
Is there a way to mute all sound coming from my program?
Even when I can't control the part of the program that creates that sound.
Thank you.
Printable View
Is there a way to mute all sound coming from my program?
Even when I can't control the part of the program that creates that sound.
Thank you.
I'm guessing that you are refering to the beeps that windows makes in certain circumstances, like when you press enter in an edit box. You can make these sounds stop on a case by case basis, but there is no general API which can silence your application.
As an example, to stop the beep that is given when enter is pressed, handle the WM_CHAR message, and return 0 when wParam is equal to VK_RETURN instead of calling the default procedure.
How about PlaySound() allong with SND_PURGE in the case WM_TIMER every 1 second.
Turn off your speakers or mute your sytem's sound in the control pannel.
*duhh*
I believe the only way to mute all sound is to turn off the speakers. Unless you can figure out how to mute the sound generated by the following ditty:
Code:
#include <stdio.h>
int main(void)
{
printf("%c", '\a');
return 0;
}
Here's how I would do it:
Devil Panther >> You need to go into more detail regarding what you are looking for here.Devil Panther >> You need to go into more detail regarding what you are looking for here.Code:
#include <stdio.h>
int main(void)
{
//printf("%c", '\a');
return 0;
}
The only way to turn off the speakers programaticly is to disable them by giving them a bad driver. (I think.)
Well here is the full story, I've used the cwebpage.dll described at this article:
The the dll allows me to display a webpage inside my program, using an object.
The application I'm writing displays a web based video camera inside my program's window.
There is also a microphone connected to the same camera so I can hear just by displaying the camera with the dll.
But since the program is meant to run in the background, the sound gets very annoying so I'm looking for a way to mute it on command, when every copy of the program is on it's own; In other words it has to be done locally.
If there is no way to control the sound of my application, can I mute the system, just like I can mute using the "sound control" at the system tray? | http://cboard.cprogramming.com/windows-programming/75269-mute-application-printable-thread.html | CC-MAIN-2015-35 | refinedweb | 430 | 76.96 |
CatalystX::CRUD::YUI::Controller - base controller
package MyApp::Controller::Foo; use strict; # ISA order is important use base qw( CatalystX::CRUD::YUI::Controller CatalystX::CRUD::Controller::RHTMLO ); __PACKAGE__->config( autocomplete_columns => [qw( foo bar )], autocomplete_method => 'foo', hide_pk_columns => 1, fuzzy_search => 0, default_view => 'YUI', fmt_to_view_map => { 'html' => 'YUI', 'json' => 'YUI', 'xls' => 'Excel', }, ); 1;
This is a base controller class for use with CatalystX::CRUD::YUI applications. It implements URI and internal methods that the accompanying .tt and .js files rely upon.
NOTE: As of version 0.008 this class drops support for the YUI datatable feature and instead supports the ExtJS LiveGrid feature.
See SYNOPSIS for config options specific to this class.
See the autocomplete_columns() method. Value should be an array ref.
See the autocomplete_method() method. Value should be a method name.
Used in the LiveGrid class. Boolean setting indicating whether the primary key column(s) should appear in the YUI LiveGrid listings or not. Default is true.
If true, the
cxc-fuzzy param will be appended to all search queries via the .tt files. See CatalystX::CRUD::Model::Utils for more documentation about the
cxc-fuzzy param.
The name of the View to use if
cxc-fmt is not specified. This should be the name of a View that inherits from CatalystX::CRUD::YUI::View. The default is 'YUI'.
Hash ref of
cxc-fmt types to View names. Used in end() to determine which View to set.
Only new or overridden method are documented here.
Overrides base method just to call next::method and ensures config() gets merged correctly.
Returns JSON MIME type. Default is 'application/json; charset=utf-8'.
Redirects to URI for 'count' in same namespace.
Public URI method. Returns JSON for ExtJS LiveGrid feature.
Returns plain HTML form without wrapper for use with LiveGrid relationship manager.
Lke livegrid_create_form but returns form initialized for record represented by oid. Chained to fetch().
Public URI method. Returns JSON for ExtJS LiveGrid feature.
Sets up stash() to mimic the foreign controller represented by relationship_name.
Overrides superclass method to set the content response to 'Ok' on success, or a generic error string on failure.
CAUTION: This URI is for ManyToMany only. Using it on OneToMany or ManyToOne rel_name values will delete the related row altogether.
Overrides superclass method to return the new record as JSON on success, or a generic error string on failure.
Overrides the base CRUD method to catch errors if the expected return format is JSON.
Overrides base method to re-read object from db.
Should return arrayref of fields to search when the autocomplete() URI method is requested.
Set this value in config(). Default is a no-op.
Which method should be called on each search result to create the response list.
Default is the first item in autocomplete_columns().
Set this value in config(). Default is a no-op.
Public URI method. Supports the Rose::HTMLx::Form::Field::Autocomplete API.
Uses the RenderView ActionClass.
Prior to passing to view, sets
current_view if it is not set, based on the
cxc-fmt request parameter, defaulting to 'YUI'.
NOTE:This assumes you have a View class called
YUI that inherits from CatalystX::CRUD::YUI::View.. | http://search.cpan.org/~karman/CatalystX-CRUD-YUI-0.031/lib/CatalystX/CRUD/YUI/Controller.pm | CC-MAIN-2017-47 | refinedweb | 522 | 61.93 |
source code
Bio.SearchIO parser for BLAT output formats.
This module adds support for parsing BLAT outputs. BLAT (BLAST-Like Alignment Tool) is a sequence similarity search program initially built for annotating the human genome.
Bio.SearchIO.BlastIO was tested using standalone BLAT version 34, psLayout version 3. It should be able to parse psLayout version 4 without problems.
More information on BLAT is available from these sites:
- Publication:
- User guide:
- Source download:
- Executable download:
- Blat score calculation:
BlatIO supports parsing, indexing, and writing for both PSL and PSLX output formats, with or without header. To parse, index, or write PSLX files, use the 'pslx' keyword argument and set it to True.
# blat-psl defaults to PSL files >>> from Bio import SearchIO >>>>> qresult = SearchIO.read(psl, 'blat-psl') >>> qresult QueryResult(id='hg19_dna', 10 hits)
# set the pslx flag to parse PSLX files >>>>> qresult = SearchIO.read(pslx, 'blat-psl', pslx=True) >>> qresult QueryResult(id='hg19_dna', 10 hits)
For parsing and indexing, you do not need to specify whether the file has a header or not. For writing, if you want to write a header, you can set the 'header' keyword argument to True. This will write a 'psLayout version 3' header to your output file.
from Bio import SearchIO qresult = SearchIO.read(psl, 'blat-psl') SearchIO.write(qresult, 'header.psl', header=True) <stdout> (1, 10, 19, 23)
Note that the number of HSPFragments written may exceed the number of HSP objects. This is because in PSL files, it is possible to have single matches consisting of noncontiguous sequence fragments. This is where the HSPFragment object comes into play. These fragments are grouped into a single HSP because they share the same statistics (e.g. match numbers, BLAT score, etc.). However, they do not share the same sequence attributes, such as the start and end coordinates, making them distinct objects.
In addition to parsing PSL(X) files, BlatIO also computes the percent identities and scores of your search results. This is done using the calculation formula posted here:. It mimics the score and percent identity calculation done by UCSC's web BLAT service.
Since BlatIO parses the file in a single pass, it expects all results from the same query to be in consecutive rows. If the results from one query are spread in nonconsecutive rows, BlatIO will consider them to be separate QueryResult objects.
In most cases, the PSL(X) format uses the same coordinate system as Python (zero-based, half open). These coordinates are anchored on the plus strand. However, if the query aligns on the minus strand, BLAT will anchor the qStarts coordinates on the minus strand instead. BlatIO is aware of this, and will re-anchor the qStarts coordinates to the plus strand whenever it sees a minus strand query match. Conversely, when you write out to a PSL(X) file, BlatIO will reanchor qStarts to the minus strand again.
BlatIO provides the following attribute-column mapping:
In addition to the column mappings above, BlatIO also provides the following object attributes:
Finally, the default HSP and HSPFragment properties are also provided. See the HSP and HSPFragment documentation for more details on these properties. | http://biopython.org/DIST/docs/api/Bio.SearchIO.BlatIO-module.html | CC-MAIN-2014-52 | refinedweb | 525 | 56.25 |
This article has been originally posted on my blog. If you are interested in receiving my latest articles, please sign up to my newsletter.
I love mentoring.
It requires a huge quantity of humility, and if you possess it, it will bring you tremendous benefits on a human as well as on a technical level.
A few weeks ago, I met with one of my mentees who told me that she finally started to work on interesting tasks. In the team, they have been doing pair programming, but they don't always have the time to go into deeper explanations. I asked Cathy if she faced some issues she would like to discuss and she came up with private inheritance that they tried to use with more-or-less success.
We talked a little bit about it, but I had to tell the truth that I had never used it since school probably, so I didn't remember exactly how it works.
Have you ever had teachers who returned questions as homework when he didn't know the answer?
I wanted to play. We opened up my laptop, connected to an online IDE/Compiler and started to have some fun.
Experimenting with non-public inheritance
We started to with a simple example of the usual public inheritance which worked as expected.
#include <iostream> class Base { public: Base() = default; virtual ~Base() = default; virtual int x() { std::cout << "Base::x()\n"; return 41; } protected: virtual int y() { std::cout << "Base::y()\n"; return 42; } }; class Derived : public Base { public: int x() override { std::cout << "Derived::x()\n"; return Base::y(); } }; int main() { Base* p = new Derived(); std::cout << p->x() << std::endl; }
In this very example we take advantage of being able to access Derived::x(), through a pointer to
Base. We call
Base::y() from
Derived::x() just to make a call from a function that is public in both
Base and
Derived to a protected function in Base.
Then we decided to take the experimental way combining with the methodology of Compiler Driven Development. We changed the public keyword in the inheritance to protected and recompiled waiting for the compilation errors.
This line didn't compile anymore.
Base* p = new Derived(); // main.cpp:25:27: error: 'Base' is an inaccessible base of 'Derived' // 25 | Base* p = new Derived();
Seemed reasonable, no big surprise at first sight. So I just changed that line and it compiled.
Derived* p = new Derived();
As the next step, we changed the inheritance to private and clicked on the compile button. It expected the compilation to fail, I expected that
Base::y() would be handled as private to
Derived and as such in
Derived::x() would fail to compile. But. It. Compiled.
This meant that something about non-public inheritance we didn't remember well or got completely misunderstood.
Let's stop for a second. Is this embarrassing?
It is.
I could start enumerating some excuses. But who cares? Nobody. And those excuses wouldn't matter anyway. What is important is that I realized I didn't know something well and I used the situation to learn something.
It was high time to open up some pages about non-public inheritance and re-read them carefully.
The access specifier of the inheritance doesn't affect the inheritance of the implementation. The implementation is always inherited based on the function's access level. The inheritance's access specifier only affects the accessibility of the class interface.
This means that all the public and protected variables and functions will be useable from the derived class even when you use private inheritance.
On the other hand, those public and protected elements of the base class will not be accessible from the outside through the derived class.
When does this matter?
It counts when the next generation is born.
A grandchild of a base class, if its parent inherited privately from the base (the grandparent...), it won't have any access to the base's members and functions. Not even if they were originally protected or even public.
Just to make the point here is another example. You can play with it on coliru.
#include <iostream> class Base { public: Base() = default; virtual ~Base() = default; virtual int x() { std::cout << "Base::x()\n"; return 41; } protected: virtual int y() { std::cout << "Base::y()\n"; return 42; } }; class Derived : private Base { public: int x() override { std::cout << "Derived::x()\n"; return Base::y(); } }; class SoDerived : public Derived { public: int x() override { std::cout << "SoDerived::x()\n"; return Base::y(); } }; int main() { SoDerived* p = new SoDerived(); std::cout << p->x() << std::endl; }
What is private inheritance for?
We probably all learnt that inheritance is there for expressing is-a relationships, right?
If there is
Car class inheriting from
Vehicle, we can all say that a
Car is a
Vehicle. Then
Roadster class inherits from
Car, it's still a
Vehicle having access to all
Vehicle member( function)s.
But what if that inheritance between
Vehicle and
Car was private? Then that little shiny red
Roadster will not have access to the interface of
Vehicle, even if it publicly inherits from
Car in the middle.
We simply cannot call it an is-a relationship anymore.
It's a has-a relationship.
Derived class, in this specific example
Car, will have access to the
Base(=>
Vehicle) and exposes it based on the access level, protected or private. Well, this latter means that it's not exposed. It serves as a private member.
In the case of protected, you might argue that well,
Roadster still have access to
Vehicle, that is true.
But you cannot create a
Roadster as a
Vehicle, in case of non-public inheritance this line will not compile.
Vehicle* p = new Roadster();
Just to repeat it, non-public inheritance in C++ expresses a has-a relationship.
Just like composition. So if we want to keep the analogy of cars, we can say that a
Car can privately inherit from the hypothetical
Engine class - while it still publicly inherits from
Vehicle. And with this small latter addition of multiple inheritance, you probably got the point, why composition is easier to maintain than private inheritance.
But even if you have no intention of introducing an inheritance tree, I think private inheritance is not intuitive and it's so different from most of the other languages that it's simply disturbing to use it. It's not evil at all, it'll be just more expensive to maintain.
That's exactly what you can find on the ISO C++ page.
Use composition when you can, private inheritance when you have to.
But when do you have to use private inheritance?
According to the above reference ISO C++ page, you have a valid use-case when the following conditions apply:
- The derived class has to make calls to (non-virtual) functions of the base
- The base has to invoke (usually pure-virtual) functions from the derived
Conclusion
Today, I made the point that if the humble and more difficult road is taken, mentoring will pay off with great benefits to both parties. Recently, that's how I (re)discovered non-public inheritance in C++.
Non-public inheritance is - to me - a syntactically more complicated way to express a has-a relationship compared to composition. Even though from time to time you might encounter use-cases, when it provides some benefits, most often it just results in code that is more difficult to understand and maintain.
Hence, do as the C++ Standard FAQ says: Use composition when you can, private inheritance when you have to.
Happy coding!
Discussion (4)
You have explained it beautifully, and it was a pleasure to read. Your article refreshed old memories, not to mention old C++ wounds. 😃
How do you explain to your students the need for abstract classes and virtual methods or even inheritance? I have seen that most teachers can explain the concepts, but they cannot teach or explain when and why to apply these constructs.
I asked you because I am mentoring some students. I would love to pick your brains on mentoring tips.
I didn't want to tear up wounds, sorry for that! :D
Thanks for your kind words!
I'll think about it. I'm mentoring junior developers who already know the concepts, we have to go through on the forgotten details.
I'll get back to you soon.
Amen! I learn so much from mentoring and pair-programming with interns. And I learned something new today about inheritance in C++! Thanks ever so much.
Thanks for your kind words, Jason! I'm glad you liked it! | https://practicaldev-herokuapp-com.global.ssl.fastly.net/sandordargo/the-quest-of-private-inheritance-in-c-50nh | CC-MAIN-2021-49 | refinedweb | 1,441 | 63.8 |
An Attachment Walked Into A Bar. Was That U, Fu?August 22nd, 2007 by
I recently spent some time working on a Rails application that needed to have various kinds of attachments, such as PDFs and images, for various types of resources, such as Programs and Questions. The app in question lets you create programs and questionnaires for the purpose of granting continuing medical education (CME) credits to doctors — so they’re apprised of the bleeding edge techniques for sawing off your arm or tying your tooth to a doorknob. Not that this matters for the piece, but context — like sugar or salt — makes things go down easier.
If you can picture an office of harried administrators dealing with ever-changing AMA requirements — “This brochure needs to go with this program!”, “This xray picture needs to go with Question 7″, “This program needs to sing ‘Missing You’ while showing you diagrams of a root canal”.. (OK, maybe not the second item), you’ll see why I wanted to build a system that could expand easily. I did not want to find myself in the position of trying to look tough while shamefacedly muttering, “I’m sorry, PDFs can only go with *Programs*, as you initially specified” and watching these not-so-gentle administrative souls stare at me with fully warranted incredulity. Blaming the client is like [fill-in-the-blank]: weirdly fun for about 10 minutes before the hangover sets in.
This project turned into a tour of attachment_fu, single table inheritance, polymorphism and functional testing of uploads. Thanks to input from friends, blogs and the usual Internet suspects, I got it up and running in its first form and decided to write it up. Hopefully what I’ve learned can help someone else. “Link-outs”, the reclusive programmer’s form of the “Shout Out” (aka a list of great resources), can be found at the bottom of the article.
Goal
To implement a system that would allow for many types of files to be uploaded and attached to many types of resources.
Requirements
- Many types of assets (image, pdf, etc.)
- Assets belong to many types of resources (program, question, etc)
- Assets upload to the file system
- Assets validate in the context of their parent resource [you upload the pdf in the program form; the image in the question form, etc]
- All functional tests pass for uploads
Design
Rather than have database tables for each attachment type (PDFs and images, then eventually MP3s) I made one table called Assets. Listening to my requirements, a friend suggested setting up my Assets model using polymorphism and single table inheritance and that I look into attachment_fu for the uploads. For this exercise I will only be focusing on the PDF upload. Readers can extrapolate from there for image or other media types. This article does not address image resizing, or anything related to uploading images. There are some great links at the bottom that deal with these topics in depth.
Modeling the domain:
Assets (the table) has a field called type that is be [PDF, Image (etc)]; a field called resource_type which is the name of the class it belongs to, [Program, Question, etc.] and resource_id which is the id of the resource it belongs to.
The Asset class will inherit from ActiveRecord. PDF and Image (and any future file types we add to the system) inherit from Asset. Line items from Assets (the table) will look like this (leaving out the other fields for now)
type | resource_type | resource_id Pdf | Program | 82 Image | Question | 79
For my assets, I created the following models:
asset.rb, image.rb and pdf.rb. The latter two inherit from Asset.
# [Asset.rb] class Asset < ActiveRecord::Base belongs_to :resource, :polymorphic=>true end # [Pdf.rb] class Pdf < Asset belongs_to :program has_attachment :content_type=>‘application/pdf’, :storage=>:file_system, :path_prefix=>’public/uploads/pdfs/’, :size => 1.megabyte..3.megabytes validates_presence_of :content_type, :filename def validate if filename && /pdf$/.match(filename).nil? errors.add(:filename, “must be a PDF “) end end end
Because I am using attachment_fu, I need to have a set of basic fields in my table that will handle image and file uploads. The migration I created looks like this:
t.column :parent_id, :integer # for the thumbnails of resized images, required for plugin t.column :type, :string # for STI on this table (curent types are image, PDF) t.column :resource_type, :string # for polymorphism on this table (current types are Program, Question) t.column :resource_id, :integer # for polymorphism, (program_id, question_id, etc) t.column :content_type, :string # Fields here [content_type] and below all attachment_fu requirements t.column :filename, :string t.column :thumbnail, :string t.column :size, :integer t.column :width, :integer t.column :height, :integer
To create the relationship for my parent models (question and program) I set up the polymorphic relationship like so:
# [program.rb] class Program < ActiveRecord::Base has_many :pdfs, :as=>:resource, :dependent => :destroy end # [question.rb] class Question < ActiveRecord::Base has_many :images, :as=>:resource, :dependent => :destroy end
Note the difference between delete and destroy. Destroy will remove the entry from the database and the file from the filesystem. Delete will only delete the database entry.
Once this is set up, you can test it in the console and see the magic of Rails at work. Through the column names and relationships we’ve built, entries in Assets are automatically created. It’s one of the things that’s great about Rails. It doesn’t simply describe different modeling patterns: it implements them if you set up your code correctly. It’s a beautiful thing.
Uploading
Without moving files to the server, the system is not complete. So, onto attachment_fu. The attachment_fu tutorials I found online all made the assumption that the attachment you are uploading is an entity of its own, in its own form: a mugshot, for instance. My case was different: I needed to embed the attachment in the forms for their parent resources (pdf in the program form; image in the question form, etc) rather than independently. So I needed to validate a form for more than one model. In my _form.rhtml partial for program I have the pdf field like so:
# [views/program/_form.rhtml] < labelNotes label >
<%= f.text_area :notes %> # … more fields … < labelAdd Brochure? [PDF Files only]< /label > <%= file_field("pdf", "uploaded_data") %>
This means that both a pdf object and a program object are being passed back to the program controller. Since we know that a program has_many pdfs, we can use program.pdfs.build in order to create — then validate and ultimately save — pdf objects.
Validating in context of parent resource:
I needed to check for errors with my program fields and my pdf field. This snippet is what I ended up with. The second line, validate_and_build_pdf is just a result of refactoring: it allows the validation methods to be run if you select a file through the upload file field (so if you try to upload a gif, the validation in Pdf.rb will squak) — but not if you just leave that field empty.
#[programs_controller.rb] def create @program = Program.new(params[:program]) validate_and_build_pdf(params[:pdf],params[:pdf][:uploaded_data]) if @program.save flash[:notice] = ‘Program was successfully created.’ redirect_to :action => ‘list’ and return else render :action => ‘new’ end end # this method stops program from saving the asset if the field is blank, # and returns type-errors if relevant (files not PDF) def validate_and_build_pdf(fileParams,file) if Asset.is_valid_file?(file) @pdf = @program.pdfs.build(fileParams) end end
The reason for the Asset.is_valid_file? method was the same: if no file was uploaded an entry was still being made in the assets table due to the polymorphic relationship. So I had to make sure I was dealing with an actual fileobject, not an empty field. Since this would be used across the application for all types of file uploads, I made this a class method of Asset.
[Asset.rb] # Checks that the object is one of the following types before running validation on it def self.is_valid_file?(fileObj) if fileObj.is_a?(Tempfile)|| fileObj.is_a?(StringIO) || (defined?(ActionController::TestUploadedFile) && fileObj.instance_of?(ActionController::TestUploadedFile)) true else false end end
You may be wondering what’s up with the ActionController::TestUploadedFile condition — it’s because when you run functional tests of uploaded assets, that is what they are — they are not instances of fileObj.
Once it’s determined that you’re dealing with a valid file and you hit custom validation methods (such as informing the user that the file needs to be a pdf), you can include them with your program error messages so you only get one messages box at the top of your form, not two:
<%= error_messages_for :program, :pdf %>
Pass Functional Tests
This part is where you test all your uploads from your functional tests. To test uploaded files, you need to put files in your fixtures/files directory then build your tests.
# [programs_controller_test.rb] def test_create_with_pdf fdata = fixture_file_upload(’/files/semi.pdf’, ‘application/pdf’) num_programs = Program.count post :create, :multipart => true, :pdf=>{”uploaded_data”=>fdata}, :program => {:name=>”Newest Created Program”, :is_ongoing=>1, :status=>”Edit”} assert_response :redirect assert_redirected_to :action => ‘list’ assert_equal num_programs + 1, Program.count end
I had a gotcha here — I realized that I has to have the pdf array separate from the program array (since in the form it’s field_for pdf). I fixed it by submitting two objects, program and pdf, to the controller, seen above.
Finally, running the functional testing leaves files on the file system and they should be deleted at the end of all tests. So I added a destroy method in the teardown, which removes them.
def teardown Pdf.find(:all).each { |p| p.destroy } end
Failing Upload Tests
Just to check that only Pdfs can be uploaded for programs, I added a handful of other file types to my directory and created an array of invalid file types in my setup:
# [programs_controller_test.rb] def setup # other stuff…. @invalid_files = [['lipsum.doc',"application/doc"],['lipsum.rtf',"application/rtf"], ['lipsum.txt',"text/plain"],['squiggle.gif','image/gif' ], ['squiggle.jpg','image/jpg' ], ['squiggle.png','image/png' ], ['squiggle.psd',"image/x-photoshop"],['squiggle.zip', 'application/zip'] ] end
and created a test to check these uploads will fail:
def test_create_with_invalid_file_types @invalid_files.each do |name, type| fdata = fixture_file_upload('/files/' + name, type) post :create, :multipart => true, :pdf=>{"uploaded_data"=>fdata}, :program => {:name=>"Newerest Created Program", :is_ongoing=>1, :status=>"Edit", :start_date=>Time.now.tomorrow, :end_date=>''} assert_response 200 end end
This gave me peace of mind that my files are being uploaded, only the right types are accepted, and all is good in the land of PDFs and Programs. And voila, we are done and on to the next task.
Link Outs
Here’s a listing of various online resources on the topics covered in this post. This should be enough for a good start. Happy Uploading!
- Attachment Fu itself
- Significant Bits fu tutorial:
- Almost Effortless’ Fu-tutorial
- Mike Clark’s tutorial
- Changing upload location tutorial
- Testing file uploads: A broad overview (not using fu)
- Jonathan Leighton (who created the fixture_file_upload patch)
- More functional testing of attachment-fu
- An overview of Single Table Inheritance
October 1st, 2007 at 4:00 am
Thanks, great post! I was having trouble with testing attachment_fu.
November 15th, 2007 at 8:40 am
Thanks for the post.
Has anyone tried using Attachment Fu with Oracle? It turns out that “size” is a reserved word.
January 21st, 2008 at 11:54 am
You had me with the title.
Thx
February 19th, 2008 at 12:34 am
I have a nearly identical setup, but i’ve not been able to figure out how to create my views forms yet.
I’m using validates_associated on my parent model … so ideally i want to pass my images from my create form to my controller with a name that says it should ‘build’ those images into my model automatically. so that when i later say @model.save … the validation checks are done.
absolutely not working so far … can you see anything obvious?
March 3rd, 2008 at 12:45 pm
Hey,
Why don’t you release this as a plugin for “assets” uploading?
Cheers, Sazima
April 25th, 2008 at 12:16 am
Hi,
How can we modify the file uploaded?? I mean, I have a gallery to which an image is uploaded (using attachment fu). What if the user wants to change the image uploaded to the gallery? | http://www.devchix.com/2007/08/22/an-attachment-walked-into-a-bar-was-that-u-fu/ | crawl-001 | refinedweb | 2,056 | 54.83 |
Parsing the Linux kernel with Haskell: experience with Language.C
At Galois, Aaron Tomb has been experimenting with the new Haskell Language.C libraries recently (a Summer of Code project by Benedikt Huber, mentored by a Galois engineer, Iavor Diatchki), and he’s been impressed by what it can do. Here are his thoughts on parsing the Linux kernel with Haskell, with an eye to future static analysis work:My interest in the library is for use in static analysis of very large bodies of legacy C code, which means two issues matter a lot to me: 1) rock-solid support for all of GCC’s numerous extensions, and 2) speed. I have used CIL, and tools based on CIL in the past, but have been disappointed with its speed.As a simple scalability and robustness experiment, I decided to see how well Language.C would do on the Linux source tree. It doesn’t yet have an integrated preprocessor (depending on GCC’s for now), but I happened to have an already-preprocessed set of sources for Linux 2.6.24.3 sitting around (configured with defconfig).Could Language.C handle the Linux kernel?I wrote a little wrapper around the C parser to essentially just syntax-check all of the code.
import Language.Cimport Language.C.System.GCCimport System.Environmentprocess :: String -> IO ()process file = do putStr filestream <- readInputStream fileputStr (take (20 - length file) $ repeat ' ')either print(const $ putStrLn "Pass")(parseC stream nopos)main :: IO ()main = dofiles <- getArgsmapM_ process files
It prints the filename followed by “Pass” if the parse succeeds, or details about a syntax error if the parse fails. When I ran this on the Linux code mentioned above, I was amazed to find that it processed it all successfully! All 18 million lines of pre-processed source without a hitch.Since I also care about speed, I wanted to compare it with GCC. GCC has a handy flag, -fsyntax-only, which tells it to just check the syntax of the input file and quit. I ran both the Language.C wrapper(compiled with GHC 6.8.3 and the -O2 option) and GCC on all that code, on a 2.2GHz/4GB MacBook Pro. The result: Language.C parsed all of the code in about 6 minutes, while GCC managed it in a little over 2. GCC is still faster, but I’m happy to take a 3x speed hit for the benefit of being able to write all the subsequent analysis in Haskell.The following table shows the precise time and memory statistics for Langugage.C and GCC, both on the entire source collection and on the single largest file in the tree, bnx2.i, the driver for the Broadcom NetXtreme II network adapter. For the Language.C tests, I compared the performance when the garbage collector used 2 generations (the default) to 4 generations (specified with the +RTS -G4 option). Increasing the number of generations helped slightly. | https://galois.com/blog/page/17/ | CC-MAIN-2020-50 | refinedweb | 493 | 64.1 |
CONTENTS
Preface
Introduction
Kentung
Hsipaw
Hsenwi
Taungpeng
Mongmit, South Hsenwi & the Rest of the North
The Central and True Shan States
Mognai and the Southeast
Three River Valleys...and Nine States
Yawnghwe
The Myelat Area
These series of articles on the Shan States of Burma appeared as a serial in the newspaper Nation in the early 1950's. It was a unique time in the history of the Shan States --- Burma had just gained independence, and in the process the Shans, represented by their various chiefs, or Sawbwas, had willingly formed a union with the rest of Burma. However, unlike the rest of democratic Burma, the Shan States were still ruled by the Sawbwas just as in the days of British rule, and even before that, as in the days of the Burmese Kings. But this was just a brief period, for by 1958, the Sawbwas had relinquished their powers.
The author, Mi Mi Khaing, was born in the Tharawaddy District of Burma in 1916. She went to St. John's convent, Rangoon and then to University College from which she graduated in 1937 with First Class Honours in English. She then went to England with a State Scholarship to study at King's College, London. After working briefly as a lecturer at the University of Rangoon, and as a researcher for the British Ministry of Information in wartime India, she was married to Sao Saimong, son of the chief of Kengtung, the largest of the Shan States. Soon afterward she took up residence in Taunggyi, in the "most beautiful part of Burma". In 1951, she opened Kanbawsa College, a coeducational school for children, for which she was the principal.
Her best known work is Burmese Family which relates the details of her childhood and giving a view of everyday life in Burma.
Do the Shan States appear to readers of The Nation too much familiar ground, too near home, to merit a series or articles? If they do I ask forbearance. To me it seems that these regions of ours which now form the borders of trouble spots in Asia, actual and potential, have not been given an objective description since the turn of the century. Writing in English on the one hand, Maurice Collis was so thrilled at returning to a country and a people he loved after years of English climate and conventions, that he carried us along on his beautiful prose into an Arcady of Shan princesses sporting with visiting Englishmen in the intoxicating air of glades and laughing waters. Our own Burmese press on the other hand, usually, confines its efforts to arousing horror at the conditons of feudal oppressiveness and misery under a Sawbwa's rule.
In trying to paint a more comprehensive picture than either, I intend, after this first introductory article, to deal with State after State, dwelling on fact and legend, shortly or at length, purely according to my fancy and not according to the importance of the State. If therefore, in giving sidelights on what appears to me the most diverting aspects, I fail to spotlight what others consider more newsworthy features, I ask their pardon. This is not an official record.
A few inescapable physical facts to begin with. Nowhere more than in the Shan States has the course of historical and cultural development followed so inexorably along the bounds laid down by geographical features. The Shan States cover about one-fifth to a quarter of the area of Burma and contain not quite an eighth of its total population. The fact that this area, in contrast to the main portion of Burma proper, is a hill region, is due to the failure of the great Shan river the Salween, to carve out a broad bosom for the Shans to thrive upon, in the way that the Irrawaddy and Sittang have done. One of the long rivers of the world, and longer than the Irrawaddy, the Salween slithers along its whole course in a deep coiling valley, swift and treacherous as a snake, and attracting no sunny rice civilisation to its banks as even some of its own tributaries have done.
The core of the Shan country is a plateau averaging about 3000 feet above sea-level immediately to the west of this great river. To north, East and West of the plateau runs ranges in a north to south direction, some lofty and sharp-peaked, other broad and rolling. The ranges east of the Salween are massed together, high and jumbled, containing few valleys worth the name. To the north they still attain considerable heights, of about 6-7000 feet, but they are more spread out and the valleys between are broader and more numerous; while west of the plateau, Nature, becoming more gentle, lowers the mountains and rolls them out gradually on to broad plains. There is, therefore, for the traveller, much grandeur of scenery in the mountainous trans-Salween region and parts of the north, a sylvan beauty in the valleys both narrow and broad, enclosed by the ranges everywhere, and the most pleasant motoring country in the rolling downs of the central plateau and the western borders between Burma plains and the Shan country.
The true Shans live only in the valleys being in fact more of a valley people like the Burmese than they are hill-dwellers. In all these valley settlements, basing their economy on rice cultivations and the bamboo, holding five-day bazaars for their food crops and their traditional wares of iron, silver, cotton, silk and bamboo, including in their diet whatever else be omitted, the universal pebok, mohnyin-chin and to-hpu, centering their religious, social and political life around the rule of a sawbwa, which follows the traditional Buddhist pattern of royal administration, the Shans lead a life distinct from the other peoples around them who are more fittingly called hill peoples. These peoples, occupying the slopes above the valleys and descending only on bazaar days and feast days into the valley settlements, are of diverse races found in small pockets everywhere owing to migration and subsequent isolation, but found also to be predominating, each race in its own area. Thus the Taungthus in the southwest, the Palaungs in the ranges of the northwest corner, the Kachins in the far north, the Kaws and Lahus in the extreme northeast and east, the Was in the ranges of the northeast, the Padaungs in a certain corner of the southwest.
The anthropologist and census taker will tell you that among all these peoples the Shans form a little less than 50 percent of the total population of what are called the Shan States. Nevertheless it is Shan that we most call this territory, as indisputably as Burma is called after the Burmese. Historical events have decided it so. The Shans, migrating southwards from China in successive waves from centuries before Christ to the 13th century A.D., increased in numbers and won supremacy of the valleys which are the true ricefields, the slopes producing only limited quantities of rice and a diversity of less essential crops. As everywhere else in Asia, rice spelled mastery. The administrative authority of each Shan power was set up in the rice valley to extend over a territory of surrounding hills, the limits of which were set by conquest, negotiation or the decision of the suzerain Burmese king. It was in the stage of development that the British arrived and froze the whole system "in status quo", in order to administer the territory by an "indirect rule."
Thus we have the Shan States as they are today. The towns, most of them villages by other standards, built in the main valleys large and small, rich and poor, form the residing capital of Sawbwa or Myosa and give the name to the State which may or may not include within its territory other subsidiary valley towns separated from the capital by ranges. Of such states there are 33, seventeen ruled by Sawbwas, twelve by Myosas and four by Ngwekhunhmus.
The destinction in these titles dates from the days of the Burmese monarchy although the same states have not continued to hold the same titles for their chiefs during the centuries --- changes took place according to royal favour, results of battles and later, the decisions of the British authorities. But a distinction there certainly was, for in those days all privileges and titles were so much a matter of royal ordinance that every one of a Sawbwa's symbols of power was laid down in a special book of dispensations granted by the higher court. His regalia and clothes, the guilding and jewel decoration of betel boxes, spittoons, fly-whisks and such articles of use, the dress of ministers, the umbrellas, spears and horses in procession, the caparisoning of the royal elephant, the instruments for processional music, the gateways and the style of residence, all were rigidly prescribed to ensure that the dignity kept up accordance with the status of a royal chieftain, yet did not encroach on the special privileges reserved for the court of Ava itself. The British, whose success in administration was largely bound up with observance, of precedence in a hierarchy, listed states also as Sawbaships, Myosaships and Ngwegunhmuships, but in the general atmosphere of equality, fraternity, and shall we say, above all, "informality" prevailing in these days of our Independence, it has become customary to address all chiefs as Saophalong.
This title, meaning Great (Long) owner and Lord (Sao) of the Heavens (Hpa), so extraordinarly difficult to render in Burmese writing, so embarrassing for Burmese tongues to pronounce in any but the most inelegant tones, was decided upon for official use even when writing in Burmese, in place of the old and to Burmese ears more dignified title of "Sawbwagyi", in what might be called a fit of pan-Shanism engendered by interested parties in those hectic days immediately before the 2nd Panglong, and before Bogyoke Aung San arrived to work the miracle of unity which has made that camp of bamboo huts in the fields outside Loilem a great and historic landmark. Till this day it remains a miracle to those of us present, how from fervid Shan, Kachin and Chin discussions of old resentments, fears and defensive safeguards a metamorphosis took place overnight into a feeling of brotherhood which swept everyone off his feet.
There is a precedence of States still observed in Council. This is not necessarily according to size or wealth. Kengtung, the largest, does come first, but it is by no means the richest. Hsipaw is second and after this the remaining 31 follow in a set order. Two main administrative units, north and south, divide the states. Under North are the big states of Hsenwi, Hsipaw, Taungpeng, Mongmit, South Hsenwi, the Wa state of Manglun and the rich Myosaship of Kokang. Under South are Kengtung which takes up all the eastern part, the states of Kehsi Mansum, Mongkung, Laikha, Mongnawng and Monghsu in the north-centre and Mongnai, Mongpan and Mawkmai in the south-center. West of these are a string of little states running north to south (Mongpawn, Hopong, Namkhok, Wanyin, Hsatung) separated by the big state of Yawnghwe and the state of Mongpai in the extreme south-west from another packet of small states in and around the region bordering Burma proper known as the Myelat. These small states are Samkha, Sakoi, Hsamongkham, Pwela, Pindaya, Yengnan, Pinhmi, and, holding the place of honour as the smallest, Kyone (24 square miles). Bordering these little states are the larger ones of Loilong on the south, Lawksawk on the north and Maw on the west. Ironically enough, this mincing up of the administration takes place in the most accessible parts of the Shan States where communications are many, whereas in mountainous Kengtung where nature cuts up the country so cruelly and uncompromisingly, 12,000 square miles are united under one authority.
Besides these states there are the "notified areas", true hill stations built up by the British as purely administrative centres, outside the jursidiction of the Sawbwa in whose state they are situated geographically. These, better known to the outside world than the State towns are Taunggyi, centre for Central, and capital of the whole Shan State, Loilem centre for Southeast and Northeast, Kalaw, Centre for West, Loimwe, centre for trans-Salween, Lashio centre for the north generally, and Kutkai centre for the northern part of North Hsenwi State.
The status of these towns is the key to the dual system of government set up by the British, a form peculiar to "indirect rule". There was a water-tight state administration, that is, each state functioned as a self-sufficient unit, only giving a percentage of its revenues to a Federal Fund which was started when the states were amalgamated into a Federation in 1922. This fund paid for public works, education, medical and police services in the notified areas, and for roads connecting the states to one another, that is, for the expenses, generally speaking, of asoya, the other system in the dual set-up --- the channel for all interstate communications, running through the persons of the Assistance Superintendents, (postwar term being Assistant Residents) of the Burma Frontier Service. In theory the Sawbwa did all the ruling: the civil, criminal and revenue administration of the state was vested in him by the Burma Laws Act of 1898, subject to restrictions specified in the particular sanad or order of appointment granted him. Except for certain enactments which were extended from Burma proper, the law in each state was the customary law of the state "so far as it is in accordance with justice, equity and good conscience and is not opposed to the spirit of the law in force in the rest of British India." This administration of the Sawbwa helped by his ministers was done largely through Circle Headmen who were directly responsible to him. In certain States these Headmen had always been elected by the people; in others they are appointed by the Sawbwa.
Thus each state, no matter how small had its own ministers, police force, education, medical services and public works to look after from its own budget, no matter how meagre. All this though ostensibly under the Sawbwa and state authorities, was closely checked by the officers of the Frontier Service --- a system referred to by the people as the keeping of a little book in which the Assistant Resident marked down the delinquencies of the Sawbwa. Almost all the officers were British or Anglo-Burman (there was a few Burmans and no Shans until the admission just before the Japanese war, of Sao Kyaw An of Yawnghwe State) and as the officers came young to their posts, this writing in a little book was gall and wormwood to many Shans. The degree of rancour it engendered could be gauged by the fact that when in 1946, contrary to all precedent, a member of the Kengtung ruling family (Sao Saimong) was not only recruited but posted to his own home state as Assistant Resident, the sceptical, discounting the generous gesture, swore that now it was the "Sawbwa" writing in a little book about the Assistant Resident, Kengtung then being temporarily under a British Administrator.
In fact, looking back, a clue may be found here to the surprising unanimity of the Shan Leaders at Panglong to join Bogyoke. The humiliations they felt at this set-up were aggravated by the inferior quality of postwar recruitment to the Frontier Service, and culminated in the Frontier Area Regulation which set out, with incredible tactlessness, a hierarchy of administration as 1, Director or Administrator for Frontier Areas; 2, Deputy Director; 3, Assistant Administrators (i.e. the young A.R.'s most just recruited from England); 4, Sawbwas and 5, Headmen ...
Besides personal resentment, however, the system meant that no Shan Chief or "commoner" had much hope of playing a role in the overall administration of the Shan States. The Council of Chiefs resided over by the Commissioner, though it discussed the budget and was consulted in connection with the extension of Acts to the Shan States, was without legislative powers. Since independence of course, a great deal has been changed. The dual system is still kept up for convenience, (although certain notified area towns have been handed back to state administrations), with Shan officers largely from non-ruling families, to act as Post Offices between states and central authorities from Rangoon. Up to date, no service has been established to provide these officers, appointments being made from whatever personnel seems suitable to the authorities. The Shan Council, composed now of equal numbers of Chiefs and elected commoners, have full legislative powers. The Head of the Shan States, a ruling chief, has five of these commoner council members as Ministers who are expected to set the policy of the State. The Special Commissioner, holding a position in which decisive action in emergencies has been the main need during the past year of disturbances, has been chosen from among the natural leaders for the extent of his awza and the influence wielded by this personality.
These changes have made it possible for a representative section of the people of the Shan State to manage thier own affairs, and apart from the appointment of a few senior specialists from the Burma services, there has been no flooding of the administration by Burmans as the Shans had been led to fear would happen. Meanwhile, the old water-tight state administrations have been broken down to the extent that education, medical services and public works for every area (Kengtung excepted by reason of her own unwillingness to pool resources) has been centralized. This represents a considerable concession on the part of the Sawbwas, for it means that appointments, disbursements of pay and terms of service for the personnel in these departments are taken out of their hands and made uniform for every state. It also means that the big Sawbwas and their people agree to share with the poorer ones, some of whom cannot muster enough money for a decent school or dispensary in even the capital town. When this centralization extends further, the citizens of the Shan State will be under a rule no more feudal than that in Burma proper, differing only in that the symbols and offices of their administration fit their Buddhist social and cultural pattern more fully. "When ..." that is the burning question. It is true on the one hand to say that the Sawbwas are still securely and willingly enthroned by a belief in karma on the part of a majority of their people. It is also true that a section of people, especially those living in the nofified areas outside of any Sawbwa's authority shout "Down with them!" from time to time. But it is a Never Never land where a whole class of human beings with human desires and weaknesses will be seen to surrender of their own accord the houses, lands or privileges they inherit from their fathers under the existing laws of the world in which they live. Certain favourite items they will cherish feel they have done enough by giving away a part.
Much could be written to romanticise Kengtung, to describe it in terms of the escapist's paradise. But there is little tempatation to do that at present. During the past ten months uninvited guests from across the border have been raising panic and commotion there and even now have not been altogether disposed of. The very factors which gave Kengtung its romantic quality, its remoteness from any other big centre of civilisation and its situation as a courtyard into which the backdoors of four different countries open out, have made it a critical point of Burma's defences. Like Tibet, this other backyard of Asia must wake up now from the dreaming slumbers of legend to the harsh jangles of politics and martial clashes.
The fact is that Kengtung is the largest, most mountainous, most easterly, and culturally the farthest from the Burmese, of all the Shan States. Geography makes approach to it from the rest of Burma difficult for it lies not only beyond the Salween across which no bridge has been built and whose eastern tributaries have cut no easy routes through the serried north-south ranges, but nearer again to the Mekhong than to the Salween. Thus, the Salween being as we have seen a barren river, Kengtung has drawn its cultural inspirations from the bosom of the Mekhong, far from our own great mother, the Irrawaddy. And thus also, while from Taunggyi one must travel 300 miles, driving for two long days (sometimes four or five days) over a zigzagging route, the road to Siam is but 100 miles through comparatively open terrain. Kengtung as part of Burma is, in reality, a political anomaly, the result of astuteness on the part of Chiefs in the past, who elected to ramain under the suzerainty of distant Mandalay, to which yearly gifts of gold and silver flowers were all that were required, rather than under the yoke of Ayuthia and Cheingmai so much better placed for effective interference. From Cheingmai it is indeed, that the ruling dynasty and race of Kengtung has sprung.
This migration of the Cheingmai dynasty, made in the 13th century with the idea of founding a new kingdom, has resulted in Kengtung having a different type of Tai population from the rest the Shan State. The Tai here call themselves Khuns; their speech contains many variations from the western Shan, and their script is entirely different. The dress is also distinctive, in that the htamein of horizontal stripes is topped by a jacket with a crossover front and a side-tie like a kimono, and in that the hair style, which sweeps the hair up to the crown of the head with a sideways swirl, ends in a pointed chignon instead of a broad and rounded sadone. These echoes of a Japanese garb are not just interesting coincidences. According to Kengtung history, they are the result of actual Japanese descent from a bank of seafarers, (noblemen, they say, the editor of the present Kengtung newspaper naively referring the the leader as Captain Samurai) shipwrecked on the coast of Siam, held by the King of Aynthia, and then presented to the Cheingmai family whose Kengtung scions were finding difficulty in making the new kingdom prosper. Whether this tale be fact or legend, it is still possible for the imaginative to read in the features of certain members of the ruling family and other official Khun families a Japanese cast. The Japs themselves, missing no opportunity for establishing goodwill of a sort, claimed relationship with the Kengtung people during their recent four-year visit, often referring to the ruling family as their own lords.
These Khuns form about 25% of the population of Kengtung State. Before they came, the Was were in possession, and till today the crowning ceremony of the Sawbwa starts with the pantomine of driving two Was off the throne seat. The Khuns, like all Tai, live in the valleys. The home valley of Kengtung is about 12 miles by 7, and carries the legend, not uncommon amoung such completely encircled valleys, of having once been an inland sea. This is said to have been successfully drained by one of three hermit brothers, the sons of an Emperor of Chinese regions who had hundreds of other sons, and the islands of that old sea are still prominent in the town as sites commanding good views of the valley.
In this valley are the capital city and ten circles of villages, connected by extensive paddy fields and a few orange groves. Besides this valley are other big valleys in which the subsidiary towns of the State are situated. Of these the four largest are Mongping to the west, passed on the Taunggyi road 68 miles before you reach Kengtung; Monglin about 80 miles to the south-east, an hour's journey from the Siamese border; Mongyang to the north, near the Chinese border, also about 80 miles away; and Mongyawng to the east, another 80 odd miles away and near to the Indochina border. Kengtung town itself is thus roughly 100 miles equidistant from these three borders. The four subsidiary towns are all thriving, well laid out and withal very pleasant settlements --- one could cheerfully hide in them from the destructive blasts of an atomic age. They have rice-fields, palm trees, a river, shops, monasteries, and craftsmen.
These, then, are the the main centres of the Khuns. The western type of Shans live in the more westerly valleys of the state. For the rest, Kengtung is a great number of small villages tucked high or low among inaccessible ranges of hills. A diverse population is distributed among them. There are Was, of course; more of them when we come to Manglun, to the northwest, a predominantly Wa state. The hill-tribe most peculiar to and most numerous in Kengtung -- is the Kaw. These Kaws look quite different from the Shans. They are darker-skinned, though this is said to be due more to their dislike of baths than to a natural hue, shorter, with more pronounced noses and rounder eyes. They almost always wear a stolid, honest and somewhat stupid expression. The men also wear small pigtails. The women are the visiting photographer's delight. They bare their midriffs to a very large extent in the bitterest winter winds of their hill-tops, wear short kneelength kilts, smoke pipes, and indulge in the most riotus decoration of their blue garments. All hill women do this to a certain extent but not to that practiced by the Kaw. Shells, seeds, beads, coins and tassels. Nothing comes amiss to her, all are arranged in festoons, panels and circlets, with silver studs and bosses all over the skull cap of cloth or bamboo bands. In the former British bill-station of Loimwe, where the wind carries, and scatters the seeds from deserted English gardens of past days and covers all the hill sides with dahlias, gladioli, cosmos, cornflowers and poppies in their seasons, the Ekaw crowns herself still further into flowery fantasies which rival the most extravagant efforts of European milliners.
To the Shans down in the valley, the Kaws are distinguished not only by the exposed navels and knees of their women but also by their dog-eating propensities. Though several other peoples, among them the civilised Chinese, breed and eat dogs of a particular strain, the Kaws eat any kind. The Roman Catholic missionaries who have made them cover their navels have not rid them of this preference in meat. On a dog-shooting day in 1946, when sixty dogs were shot in an effort to rid Kengtung town, in which there is a large Roman Catholic Kaw settlement, of its pariah menace, all sixty corpses were removed before a clearance unit could be organised. But fastidiousness about animal foods is all a matter of habit. The Anglo-Americans squirm at our maggoty and aromatic ngapi, our crickets and snails, and we shudder at the bloodiness and meatiness of their chunks of beef, as suggestive of their own pink flesh. Those of us who, too fond of our stomachs, rate a civilisation by the development of its culinary art, put the Chinese with the glories of their food supplies, ranging from the ocean-deep octopus and slug to the saliva-lined nest of the swift in its airy bowers, above all other peoples, but the Hindu, brought up on plain living and high thinking, and exalted into the fine air of mystical theology by his bloodless vegetarian diet, recoils with physical revulsion at such filthy food habits ...
The other important hill tribe in Kengtung is the Lahu, sometimes called Muhso. Ignoring ethnological possibilities, one is tempted to render this as the Burmese mokso --- the Lahu is so often seen with his crossbow for shooting poisoned darts at small and large animals. He also appears very Burmese, and speaks a language very similar indeed in tone to Burmese. One of the Lahu histories relates that they originally came from the banks of the Irrawaddy, having accompanied King Anawrahta on his march to the borders of China in quest of the sacred Tooth, that having settled near the Chinese country they multiplied and moved further and further south and east with successive migrations; and that crossing the Salween they asked for more and more villages from the Shan Sawbwa who granted all their requests. Present day Lahus are specially proselytised by the American Baptist Mission, and though forming but 10% of the population of the Kengtung State, have become so conscious of their entity as a distinct race that, apparently following the example of their ancestors of the legend in "asking for more" they feel they might ask for an autonomous Lahu area.
Then there are the Shan-Chinese, negligible as regards actual proportion to the total State population, but an important factor because of their concentration in the capital town --- 4,000 of them in a population of about 20,000. These Shan-Chinese, though settled here for centuries still remain distinct from the Khuns, living by the butchering of meat, by trade and raising of garden produce. Like all colonies of Chinese in Southeast Asia, they provide an example of communal cooperation, industry and thrift, by which neither the Khuns here nor the other Southeast Asiatics elsewhere will profit or imitate. Perhaps here more than anywhere else the reason for the contrast in habits is obvious; the Chinese came from the most inhospitable regions of the Yunan where the life-struggle was hard, the Khuns have grazed on their most fertile valley so long. The wonder is that the Shan-Chinese do not get corrupted after generations into lazier native ways. Continuing their lives of quiet industry, they have even accepted, in the past, the position of inferiority to which the Khuns relegated them. Now times are changing; if truth be told the solid block of Shan-Tayoks is felt very much indeed as a presence whose true nature is unknown. The uncertainty of this became of burning import with the inrush of Kuomintang Chinese troops into the State. Were the Shan-Tayoks going to be Shan or Tayok? Luckily the Union forces pushed the invaders away from the capital before a decision was necessary. A large number of Chinese citizens were arrested, no doubt, for possession of arms and uniforms, but these were pure Chinese of recent settlement, not part of the ancient community.
There has always been a purely Chinese population in Kengtung, but during past centuries this has been migratory. The poor starving ones came across every dry season for building and road making. Even the modern British Government, and the still more progressive-minded Independent Government continues to use human labour on these roads when machines would do the job, and how much more quickly and efficiently! It is the commonest sight on the Kengtung road, to seek sickly blue-clad Chinese shovelling infinitesimal amounts of earth a few feet at a time from the mountainous pile that waits to be moved. More well-to-do Chinese come in to supervise poppy growing or in charge of mule-trains of goods for exchange. During the past decades more of them have settled firmly in the capital. Kengtung town is such easy prey for adventurers. Till very recently, passports, visas, tariffs, citizenship --- all these concomitants of the modern idea of a nation were unknown. Thus at one time you might have found the Kengtung hospital more than half filled by "alien" traders who got ill during a trip in. Or 200 Chinese in uniforms might march along to ask an interview of the Premier during his visit there. It was all in the day's news.
The mountainous character of Kengtung has left a very small proportion of arable land, compared to other Shan States. The rice in the valleys is barely sufficient for their surrounding areas. Though the soil has some quality in it which makes its oranges, its sapodillas, its crab-apples and even its tamarinds particularly sweet, no fruits are produced in quantity. A large amount of cotton is grown and it is the commonest sight to see the Kaw women walking around spinning the cotton by a twirl of a little spindle on a lifted thigh. Despite forested areas the only noteworthy timber is a small amount of teak near the Mekhong, and around Mongpulong on the Salween.
The wealth of the State from time immemorial has been drawn partly from the sale of opium which grows so beautifully in fields of dancing white, high on the slopes in the clear air of a fine Shan winter's day, and partly from the situation of Kengtung Bazaar as an entrepot for the trade of four countries. The opium is grown largely by Kaws and Lahus. The entrepot still exists. The mule-trains still tinkle in beside their trudging escorts from China and the Laos country; salt, camphor and ironwares, dried milk, nuts and even fruit from China are still exchanged here for cotton, opium, and manufactured European goods from Burma and Siam. But the roads west and south are now traversed by fast buses more than mules trains. And the stigma carried in modern times by the opium traffic, together with modern conceptions of tariffs and customs regulations have given the peculiar economy on which Kengtung has always subsisted a specially dubious character. There is a suggestion of sky-high profits, quick money exchanges, camouflaged cargoes of matches, petrol and American textiles pervading the air, and rapidly vitiating the race of traders. There is something faintly demoralising about a middle-man's trade, perhaps, in contrast to the agriculturists and craftsman's. In the race for riches, both agriculture and the crafts which had attained a high standard in lacquer, silver, and weaving are being given the go-by.
The visitor to Kengtung town will be struck by the air of progress compared to all other Shan capitals. Partly owing to Chinese influence, a great proportion of the buildings are brick. Owing partly to Siamese influence on the other hand, and to the Sawbwa and other ruling relatives being young, and progressive according to their own lights, a great desire for modernisation is to be noticed. A brick hospital and donated maternity home stand in trim gardens and are maintained in great cleanliness with the help of Roman Catholic nuns, true missionaries who are willing to serve under state authorities, with no quasi-political connections. The State School, a large and new brick building with cottages for teachers, beds of violets and children in Burmese uniform, is run by one of the Sawbwa's aunts in a manner which draws praise from all visitors. The bazaar is a model one, of roofed sheds and brick platforms, the shops, till the recent closing of the border owing to military situation, were always full to bursting. The monasteries, Kengtung's chief glory reflecting Burmese, Chinese and Siamese influence in an indefinable mixture, are freshly gilded, painted, walled and attended by their congregations, showing no neglect or dilapidations. The big Haw which is a rare composition of Buddhist pyathats and Islamic domes, of lime plaster and teak, the result of a visit by the last great Sawbwa to Moghul India, now forms the State Offices mounted by a guard who rushes out with commendable zeal to challenge all comers. The half-dozen houses of the ruling family in their large grounds are visited by streams of the common people every day, making it clear that the Khuns at any rate desire no change in their social and political life. In fact there is no mistaking the prosperity of the town and the generosity of the budget devoted to its upkeep.
Yet judgment made on this score that Kengtung is far in advance of other Shan States with their undeveloped capitals would be superficial. Outside the town, the villages even in the home valley, are sunk in their immemorial mud-bound poverty. Until very recently, with the training of villagers in a rough and ready scheme of the present Chief Education Officer, whose treks through elephant grass from village to village in these very areas drove him to start the project, until the return of these trainees, encouraged by the young Sawbwa also to set up one-teacher schools in their home villages, there was not one lay school among all these circles. In contrast to Hsenwi and Yawnghwe states which could boast 56 and 48 schools respectively.
The lack of communications in Kengtung was no handicap in the days of the old Sawbwa who used a horse and elephant even when he had several cars in his garage. Ruling for forty years he saw all parts of his State even at this processional pace. But the bogs are an insurmountable obstacle in a motor-conscious age.
Yet why do I dwell on these aspects of Kengtung? Mine would rather be a pen of fond reminiscence, of effusions even, than of a cantankerous criticism. The truth is that I love Kengtung and could write a volume on her charms. Somerset Maugham spoke of a meeting at sea with a man who spoke of Kengtung as one might speak of a bride. Was that man, so strangely withdrawn from the shipboard company, Theophilas? And wherein lies this charm which Kengtung exercised on those who have known her? Is it in looking down from one of the islands of the old hermit's sea, on the town spread out with its lake, palm trees, monasteries and deep-sloping roofs, and hearing from it the muffled hum of an ancient trading centre thriving all by itself, hundreds of miles away from anywhere and surrounded only by mountains? Is it in the contrast of the blue-clad mule-trains from China which still patter into town past the great banyan, with the same cargoes of camphor for the south of Siam or tea for far off Tibet, at the same pace as they have done for centuries, while one looks down from the "Club" with all its appurtenances in a flashy modern Thai style, of wicker, fizzy drinks, and shark-skin clothing? Is it partly, too in the paradoxical clinging of the Khuns to the old shikkho-ing ways and the entirety of their religious celebrations while they embrace without reserve the gadgets, the admiration for neon lighting, crinkled short hair and plastic goods filtered from the USA through Siam, to an extent undreamed of in any Burmese town? Is it in the massive gateways, the crumbling red machicolated walls, which threw back so many Siamese invasions, the red roads running at unexpected angles, into which the red sun-baked brick buildings merge with no dividing line? Is it in the diverse hill tribes who come into town once in five days with cross-bows, pipes and gala-dress, and stand withdrawn in silent groups, bringing echoes of pine forests and mountain winds from beyond the encircling ranges? Is it in the monasteries whose dim interiors of lofty trunks, suggestive as nowhere else in Burma, of the nave and aisles of Christian cathedrals, provide such strange background for yellow robed monks? Is it in the magical transformation of these interiors of cold Sabbath mornings when, with candles lit and the big drums beaten and the offerings before them of coloured cakes, all the people sit in their appointed places exchanging gossip softly, till the monks begin the chanting which, starting as such strange music to Burmese ears, soon gathers up thought and the distraction of all five senses and resolves them into one swaying concentration? or is it, after all, in the sentimentality of one's own associations with Kengtung and her people ...?
From Kengtung to Hsipaw takes one but a step in the order of precedence, but in geographical situation and cultural affinity, one moves right across the breadth of the Shan States and across the whole possible range of differences between eastern and western Tai. As Kengtung occupies the eastern most boundary, so the boundaries of Hsipaw adjoin Mandalay District and its environs of the west. As Kengtung has been influenced to an extraordinary degree by Siam, so Hsipaw is known to be the Shan State most Burmese in character. It is no mere whimsicality on this account to write of them in succession, however, for across these geographical and cultural distances, the two Chiefs who took succession soon after the establishment of British rule stretched their hands in friendship and family ties. Using their very differences as the reason for a cooperation which would supplement each other's strength, they appear to us looking back now, to have fostered just the kind of unity which everyone talks about so much nowadays.
Kengtung was the seat of a Yun-Tai culture and religion which drew inspiration from Ayuthia --- it should enrich and be enriched by the culture which Hsipaw inherited from its proximity to Mandalay. Kengtung had its vast area, its pride and prestige in a kingdom which had been virtually independent and a dynasty which had been continuously enthroned for centuries. Hsipaw which lacked a long history either as an independent unit, or a continuous dynasty, had the greatest wealth of all the Shan States and was eager to give with princely generosity to Kengtung. Kengtung had its greatest treasure in the elder sons of the old Sawbwa --- half a dozen handsome princes (of whom alas, the fairest two are now dead) of a discipline of character remarkable among the sons of indulgent chieftains. Hsipaw, singularly barren in male progeny, had its jewels on the other hand, in its royal ladies, famous among the Shans for their wit, their cultural accomplishments, and their readiness to grapple with any situation on life. So the long road of 400 miles laid by the Public Works Department of the newly established British authorities became a shwe-lan ngwe-lan across which traveled monks and musicians, sons, daughters and nieces, later grandchildren even, for adoption, marriage and education.
Hsipaw State, 4591 square miles in area consists of four sub-states which were amalgamated under one ruler only after British annexation. The main state of Hsipaw occupies about half this total area. To west of it the sub-state of Monglong (Burmese Mainglone) and Hsum Hsai (Burmese Thonze) are situated north and south respectively, while southeast of it lies the sub-state of Mong Tung (Burmese Maingtone). Each of these sub-states is ruled by a Myosa, and after amalgamation, the Myosaship of one or other served as training post for the heir or nephews of the Hsipaw chief. These four states are known in the chronicles as On Baung Hsipaw, from the older capital of On Baung, situated not far north of Hsipaw.
The whole area lies in a geographical fault which stretches from the Irrawaddy-Salween watershed westwards, creating a comparatively low-lying region which lies immediately north of the central Shan plateau, and which consists of one big valley and several smaller valleys among a mass of low spurs ill-defined and crossing each other all over. The big valley is that of the Namtu, which rising on the Irrawaddy-Salween divide and continuing westward as the Myitnge, flows into the Irrawaddy. Hsipaw is thus properly in the Irrawaddy basin and hence an approach to it from Mandalay via Maymyo takes one almost imperceptibly from Burma proper into the Shan States, In fact Hsipaw town is not unlike a town in the Burma plains, it has the hottest summer weather in all the states, and the Namtu at this point is a placid and swollen river, having just received two feeders. Further westwards however, in Hsum Hsai, the river cuts deep gorges of 2000 feet or more and offers as picturesque a hill scenery as anywhere else in the States.
Although you will hear Burmese spoken in all the towns of Hsipaw State and though there are a number of pure Burmese settlers, especially in Monglong sub-state, the Shans still form the majority race among the population of about 150,000. There are a good number of Palaungs in the hill-regions to the northwest, also a few Kachins and Taungthus, the latter here reaching the northernmost point of their migration.
Rice is grown extensively in all the valleys of the State, and the upland rice of the lower slopes is also of a high quality. The Palaungs grow tea on their hills but it is of a type inferior to the Taungpeng tea, perhaps because of lower altitudes here. The oranges of Hsipaw, among the sweetest in the Shan States, find a large market in Mandalay. There is some thanatpet, chiefly from Hsum Hsai, some teak forest, and, dating from the 30's, tung plantations which one passes on the road leading north from the central states. Notable are those of the East Asiatic, a Danish Company. The tung oil fever swept across the Shan States at the time, plantations being started in Kengtung, Mongkung, Karenni and other areas, but only in Hsipaw and in foreign hands has any prosperous fruition resulted. Out of the romance of tung emerged a colourful Shan State figure. One of the adventurer types which Britain sends out now and again, full of resource, eager for gain, and ruthless, but with a capacity to feel so at home with native ways and friends as to disarm most of their critics. Tung Oil Forbes, as he came to be known, ended his eventful life most dramatically on a tung estate. He was killed 1947 in a terrorist attack on his plantation, a most ugly and regretful episode; poor Mrs. Forbes who had never taken part in the hard tussles of his commercial transactions and who had just come out, was murdered along with him by enemies made in Tung.
The wealth of Hsipaw state lies not only in its diversity of produce, but also in its situation on trade routes. The old cart tracks saw an interesting and profitable succession of exchanges. The carters would take rice from the valleys to the hill Palaungs, bring down their tea, and turning westwards to Mandalay, would sell it there to Chinese brokers, bringing back cloth and miscellaneous imported goods by a more southerly route across the Namtu to the valley towns, in the bazaars of which they found a ready sale for Mandalay goods and were able to buy rice to start the round all over again. Today, also, Kyaukme, standing on the railway line from Mandalay to Lashio, at the crossing point of routes to Taungpeng as well as Mogok, is a great economic asset to Hsipaw State. Hsipaw is one of the few Shan States to be traversed by a railway. The famous Gokteik viaduct spanning the deep gorge which the Nam Hpa Se tunnels after its disappearance underground, is at the 83rd mile on this line. For the visiting motorist also, Hsipaw is a good centre. it adjoins Mongmit, North Hsenwi, South Hsenwi, Taungpeng, Kehsi Mansam and Mongkung, all within easy reach by roads which, except in the case of Taungpeng and Mongmit, take one over smooth surfaces and easy gradients.
Six miles west of Hsipaw town is Baw Gyo, centre of one of the big pwes of the Shan States. These Shan pwes, centered round a pagoda as in Burma, are not very different in pattern from a Burmese payabwe. the main difference is that they still form the focal point for economic, administrative and social activity of a very large surrounding area. Thus there are shops and camps of traders, there is the paying of respects by outlying officials to the Sawbwa and official business going on during the 7--10 days of pwe, and there is the actual zatpwe or anyein every night on the one hand and gambling every day and every night on the other. This is the general pattern of all pwes; the size and success of it depends on how central the situation is, how well served by roads, and how productive the surrounding area, of the economic function of providing an extra big market for exchange of goods is as important if not more so, than the social. The times for these pwes are the festivals of Tagu, Thadingyut, Tazaungdaing and Tabaung, but different centres concentrate each on a different one of these occasions, some busier centres on two of them.
PWES IN BAWGYO
At Bawgyo the main pwe, held at Tabaung full moon, enjoys a large patronage by virtue of its situation on the trunk road from Mandalay to Lashio. This position made it profitable for traders even in the old days to come right from the south of the States, for here they could meet Burmese and Chinese traders and exchange their wares of iron, cotton and bamboo for goods from China, Burma and the Kachin country. Formerly too, the splendour of the Hispaw Sawbwa's camp was a draw. To this pwe ground covering many acres for ten days and nights, the old Sawbwa Sir Sao Khe came in full formal procession of ahmudans and nebaings preceeding him on horseback in a V-formation, at the apex of which he rode on his elephant with all the trappings of umbrellas and giltwork. His son Sao On Kya came with a water cavalcade of equal magnificence. With the music and drama of a high quality, fireworks displays initiated by the Sawbwa himself the distribution of largesse to winning circles of villagers, and the prosperity of potential gamblers from every direction, it was no wonder that the gambling contract at Bawgyo always netted a magnificent sum.
The administrative function of these pwes is easily understood in the light of the poor communications which exist between the capital of each State and its outlying circles of villages, sometimes across steep mountain ranges. The handing in of the revenue by circle heads, the reporting and petitioning by them and other villagers of any business to the Sawbwa, and the issuing of instructions by the central authority are best done during a pwe, the other attractions of which make it a pleasure instead of a burden for the people to come such long distances by cart or even by foot in some cases. It is amusing to read the account, by a British officer in the earlier days, of administrative business thus disposed of by the Hsipaw Sawbwa at these festivals. "At the October festival," he relates, "the nebaings present an installment of the revenue collected, and at the March festival they are expected to pay in the balance. After having gambled with the nebaings and headman who generally lose heavily, the Sawbwa, before dismissing them, delivers a harangue on their duty, exhorts them to behave well and not oppress the poor, and then, after exhibition of the phonograph, they return to their homes." So simple is the administration of a personal rule, it is no wonder that it often runs more smoothly than the highly geared wheels of a complex bureaucracy.
Hsipaw town, as the capital even of the Hsipaw State alone, is comparatively recent. State chronicles of past times show a great deal of Burmese influence in the tales and Burmese association in the events, as is to be expected. They take us back right to the time of Abiyaza and Tagaung, From Tagaung, they say a descendant of Abiyaza came to found the old kingdom of Mong Mao, further north, which was the original Kambawza of the Shans. From here stemmed four sons taking rule over various North Burma capitals, one of them being Mongmit and On Baung combined. By this time the chronicle has reached 58 BC, and records thereafter a succession of rulers who spent their winters in Mongmit and summers in On Baung, and who had relations with Mong Mao, Prome and later on Ava. Thus the records bring us to the early 16th century when, during chaotic days in Burma following the end of the Pagan dynasty and establishment of a Shan supremacy in Upper Burma, the On Baung ruler, Sao Khun Mong, was invited to become King of Ava. Taking care to establish his brothers and sons over various Shan States, Sao Khun Mong accepted and went to Ava as King. His dynasty lasted only two generations however. He was succeeded by his son from Mongpai who before long was put to flight by an uprising. Mongpai went to King Bayinnaung of Pegu for refuge and found himself made prisoner instead. So he fled again, this time to his uncle of On Baung. This brought Bayinnaung with a large force to the boundaries of Hsipaw. On Baung greeted him with a submission which included that of all the other Shan chiefs behind him. Thus they all became tributary again to a Burmese king and boundaries were fixed which gave the King of Burma the Ruby Mines Tract and the gem city of Mogok. In return (so the Hsipaw chronicle has it) the Shan States were all placed under Hsipaw.
Thus the descendants of On Baung dynasty continued their rule till 1714 when they shifted capital to Hsipaw. From now on they had close marital connections with the Alaungpaya dynasty in Burma. In King Thibaw's time, however, Sao Khun Saing, 18th Chief since the surrender to Bayinnaung, decided he could take no more of exactions levied from Mandalay and fled south. He went to Siam, then Rangoon, did a jeweler's trade, got imprisoned and then expelled by the British, fled to Karenni, and there mustering a force returned to Hsipaw. He found it in chaos and took possession then went to Mandalay and submitted to the British as Sawbwa of Hsipaw, the first Shan Chief to do so. For this early submission he was given rule over the four amalgamated states --- and was later on presented to Queen Victoria.
The ability which this early submission gave to Hsipaw State, the social patronage of the British, and the wealth accruing from the enlarged territory combined to make the Sawbwa of Hsipaw, already influenced by his closeness to Mandalay, the natural inheritor of the Burmese court tradition which the capture of Mandalay had brought to such an abrupt and compromising end. Stories are still current in both Shan and Burmese circles of the glories of the old Haw whose throne room, modeled on Mandalay, was destroyed only during the Japanese war, of the modern comforts of Sakantha Haw, of the grandeur of the royal ceremonies true to all our old traditions, of the numerous wives of Sir Sao Khe and the princely generosity of both him and his son, Sao On Kya.
The lavishness reached its highest and most recent display in the marriage of Sao Khun Mong, one of the elder sons of Kengtung to Sao Ohn Nyunt, sister of the Mahadevi and cousin to Sao On Kya in 1934, when the programme of religious, social and charity giving festivities lasted for a month of days and nights. And when, a last backwash from the Society of the early 20th century in Burma whose ladies first learned the piano as an accomplishment, welcomed the Prince of Wales, wore shoes and stockings, ordered teas from the Vienna Cafe, and regarded the English title of "Lady" as the highest social distinction, when, as a last echo of these days, the solemn procession of caparisoned elephant and moving strains of sidaw were followed next day by a long drive past lake and camp of wedding guests, in a carriage and four, with liveried Indian footmen and coachmen. What fine days those must have been, the fine Shan weather untroubled by war clouds; how exquisitely beautiful the bride looked, how handsome the groom and his two attendant younger brothers. Alas, though the bride of that day has remained a sweet and lovely being all years, time tarnishes everything. Age writes wrinkles in all our faces, and the bloom of youth flies away to be forever an unmaterial thing.
But the Burmese court tradition was carried on in other respects besides lavish celebrations. The arts were all given patronage, above all others, music and drama. Did not Sir Sao Khe often give instructions that when he died, Mya Gun, one of his Mandalay wives, and her harp should be included in his coffin? And was not everyone so impressed with this passion for music that poor Mya Gun went trembling all the days of the short life which remained to her after the Sawbwa died, in case his spirit really could not rest without her music.
Sao May Aye Kyi, the music mistress of the BBS is another relic of those days, a high favourite of the Sawbwa's when her voice was at its most beautiful. In the angry moods of the Sawbwa the court knew but one method to bring back the royal good humour. All who dared would have fled from the throne room where he sat glowering, frantic searchings for young Mya Aye Kyi, protesting she was, pushed through the door and deposited in the ominous presence with instructions to sing: " Chit-tha-mya-go ...The extent to which I love", and though quavering internally the young voice would begin a strong and true declaration of love. As it soared along on "go-oh", the Sawbwa, his anger already taken along on the music to the ends of the four islands of the universe, would with his face still stern, chime in "{|it Myin-mo}" -- the highest Mount Meru to which the lover's imagination can soar. But this was the signal: back came the courtiers and sidled into place. Sao Mya Aye Kyi's voice continued binding the royal imagination with oaths of never-ending love, taking him linked with his beloved one, across fragrant oceans to the end of time and space, while one by one the musicians joined in and accompanied him. When he came back to earth good humour reigned again.
One is tempted to go on with such anecdotes of Hsipaw court life. But this is a newspaper column, not a cosy circle of friends, so exercising great self-restraint, one must desist.
Hsenwi, (the Burmese Thenni), bears a name which carries in its sound all suggestions of grandeur, mystery and romance. Most northerly of the Shan States it takes us, like Kengtung, to Burma's borders, but beyond these borders in every direction lie nothing but the mountains of Yunan. There they lie with impenetrable faces as you look from Kyukok eastwards and northwards, beckoning to the imagination as all undeveloped and unknown vastnesses do. To the Shans, however, they beckon for a stronger reason. Across these ranges one enters the routes into the cradle of the Tai race, the Szechwan Valley which bore the Tais long before China developed as a distinct power in history. Here one is carried as far back into the movements of these elder brothers of the Chinese, as the Tai have been called, as when history faces into nebulous probabilities, for it was across the territory now known as Hsenwi that successive migrations of Tai moved south and east to become known as the Shans of Burma.
The romantic associations of Hsenwi are also bound up with the personality of the Sawbwa, one of the few Chiefs remaining from the earlier decades of the century. Assassinations and deaths, timely and untimely, have removed one by one, the leading figures among the Shan Chiefs, till, with the death of Mongnai Sawbwa in 1949, only three big chiefs of the older generation, Yawnghwe, Taungpeng, and Hsenwi, remain. The rest are all young or of recent succession. Hsenwi Sawbwa is the most colourful of the leaders who remain --- a Shan Sawbwa with a solid body of Kachins among his subjects, forming in his personality a bridge between past days and the present, autocratic in the days of autocracy, magnanimous and conceding in these days of change, always positive, astute and daring.
The present state of Hsenwi comprises an area of 6442 square miles. It is bounded on the north by various Chinese Shan States, that is to say, states of Shans under the suzerainty of China; on the east by the Burmese Chinese State of Kokang, in which a population of Chinese have been feudatory to the Shan Sawbwa of Hsenwi for centuries back; and on the south and west by the State of Hsipaw, Mongmit and South Hsenwi. These present boundaries enclose what is more correctly called the North Hsenwi, because just before British annexation the term Hsenwi covered a far larger area, though in fact there was such chaos that the rule was merely nominal.
The southern portion of this old state covered in theory, the present states of Kehsi Mansam, Mongnawng, Monghsu, Mongkung, and Laikha, its central part the present Mongyai or South Hsenwi, and its eastern part the state of Kokang. In the general chaos, however, the titular Sawbwa had taken refuge in the Mong Sit valley northeast of his capital. A commoner with a strong arm, Khun Sang Tone Hung, took possession of the main valley, while other interlopers set up in the Mongyai area. Eventually the son of the Sawbwa, Sao Mong, who had been held prisoner in Mandalay escaped and raised his standard. He had some successes but was no match for Khun Sang Tone Hung who now marched south and occupied Mong Yai as well. Then with the advent of the British, he returned to the capital and submitted as Chief of Hsenwi. After a conference held at Mongyai with the British, Khun Sang Tone Hung, Sao Mong and Circle representatives present, it was decided to divide Hsenwi into North and South. The southern part, with its capital at Mongyai was given to Sao Mong (i.e., the original dynasty of Hsenwi) while Khun Sang Tone Hung was confirmed Sawbwa of North Hsenwi. The present Chief Sao Hom Hpa is his son.
Hsenwi falls very discernibly into three geographical units north to south. In the south and centre are the valley of Namtu and smaller valleys of its tributaries, interspersed by ranges, some of them with high peaks, but offering on the whole a great deal of flat land which is responsible for the main wealth of the State. North of this, rising sheer from the main valley is a table-land averaging 4000 feet above sea-level, consisting for the most part, of bare hills. North of the table-land again is the beautiful winding valley of Nam Mao or Shweli, which runs in a crescent of fertile rice lands along the very border of China and Burma.
The population of Hsenwi State is a little over 240,000, the highest of any Shan State. The majority are Shans who, unlike the Khuns of Kengtung are hardly different from the rest of the Shans of Burma, despite proximity to China. It is one of the great anthropological wonders how a teeming and absorbent race like the Chinese, living in such propinquity with the Tai everywhere in these border regions of Southeast Asia, have not succeeded in assimilating them nor even in changing their speech, dress or customs in any appreciable extent. The Tai in China, Laos, Burma, and Siam (18 million of them when grouped together by race from under the wings of four countries) are all more like each other than they are like the Chinese. Western missionaries from Siam who have traveled across jungle routes to Yunan have been surprised to find communication in Siamese possible to a certain extent with these Tai, left 1000 miles behind by their migrating brethren about 1000 years ago.
There are in Hsenwi also a large number of Shan-Chinese, but the
plateau to the north of the Namtu valley is primarily a Kachin
Stronghold. Among all these slopes the Shan population has almost
disappeared (though coming out again in the Namkham valley) and
disappeared within living memory, illustrating most dramatically the
Shan preference for valley settlements, and the Kachin character as a
hill people, for these Kachins have come via the Namkham valley from
the area now known as the Kachin State to find here slopes to their
liking. Racially, the Kachins are quite distinct from the Tai. They
belong to the same group as the Burmese, Chins, and Nagas. Even to
the laymen's eye and ear their appearance and language are similar to
the Burmese --- it is only their hill life which has caused such
differences as exist. Certainly the invigorating air of the bare
Hsenwi slopes has given a vitality to the Kachin population living on
them. Visiting their schools and their villages, one is struck by a
great deal at self-help and cooperative effort. Considering the
unscrupulous way which agitators thirsting for the role of leader
have been misleading gullible "minorities" everywhere into
a hysteria about separate states and minority safeguards, it speaks
well for these Kachins who have found a home from home in what was
indisputably Shan territory, that there is not more of a cry for a
Kachin autonomy. A certain amount there will always be as long as
disgruntled agitators are at work --- but it is worth nothing that
when the Naw Seng Kachins captured the Chief last year, it was
another band of Kachins who rescued him.
Within this area is Lashio, the railhead for the Burma Road, notified area center of Northern Shan State administration, and the seat of the Special Commissioner who is the Hsenwi Sawbwa himself, the state being administered at present by his brother and heir, Sao Man Hpa. Although the railway has been restored, the growth of Lashio which sprang up like the proverbial mushroom during the feverish supply days of the Burma Road, has, like the mushroom, lasted no longer than its day. Few traces remain now. Penetration of the communist victory to the southern parts of China has put a stop, temporarily at least, to any motor trade from the border. Lashio has lapsed into the quiet demeanour of a British civil station. Its bazaar and khaukswe shops emitting only the subdued hum of an ancient trade which has crossed China on the mule-pack. But the hum is in a Chinese strain, despite a few Shan overtones imposed by present political control.
Driving northwards from Lashio along a good metalled highway, the Burma Road takes one 32 miles further into the valley of the Namtu and the capital town of the State. The valley is three to four miles broad, enclosed by lofty hills all around. Viewed from a central prominence on which the old Haw was built, its pretty rurality contrasts charmingly against the sombre encircling peaks. There is very little left of the town owing to Allied bombing. Even the Sawbwa, whose family lost a dozen houses, lives in a bamboo Haw; and the president's son got married here in 1948 to the niece of the Sawbwa in all the magnificence of bamboo architecture.
One thing about bamboo, you can do what you like with it --- make vast halls, arches and platforms, cut doorways and windows here you will, lift the roofs to lofty proportions, and with a week's work; there can be no cramping of the style as might be imposed by permanent structures. With carpets covering the bamboo floors, with silver utensils everywhere and gold and diamonds covering the bosoms of the lady guests, with the armfuls of gladioli brought in from all surrounding gardens to mingle with the coloured paper and tinsel decorations, with the arrival of the President from his immuration in the red brick pile in Rangoon to be again a Sawbwa among his brothers and sisters for a short respite, with conches blowing and with the demure winsomeness of the bride in the very center of the square hall to give everyone a view, the wedding guests from all over the Shan States did not feel unrewarded for their long journey. Of course, the carte blanche order given to an army of Chinese cooks helped, yet it is amusing to recall that after three days and nights of such banquet fare there were few among the august company who did not join the search for pebok and chilli.
From this valley northward, one climbs without much ado, steadily for 2000 feet, till the top of the table-land is reached. Kutkai, 16 miles from Hsenwi and a notified area station for civil and military, offers a typical sample of the scenery of the region. High and bleak, the slopes roll away treeless, as far as the eye can reach. These hills follow the car northward right along to the border. Mongyu, at 105th mile from Lashio, is the customs post with bamboo gates at a junction which leads one eastward into China and westwards into Namkham valley.
The branch east is now only 12 miles of maintained road. Journey's end is Kyukok across the imaginary line, a collection of huts lining a street which becomes a bog with the slightest shower. Beyond is only mule-train tracks now. Immemorial China is in the complete indifference of the Kyukok inhabitants to mud which they make more muddy with floods of washing water just as they do in Rangoon Chinatown, perched all the while on wooden clogs as outsize as the great square knives they chop their pork with. Until the end of 1948, however, the prospect of bales of white silk of a washable and wearing quality at Rs. 25/-- for twenty-four yards made it worthwhile to plough through the mud. There was always excellent food in the little restaurants as further reward, and an assortment of American bedspreads, sheets, toilet and sundry, and other articles at cut prices. It is remarkable how the present-day value of dollars and tariff regulations have caused an outcrop in these remote corners, of incongruous American goods beside genuine bargains of the regions such as hand embroidered satins, great cast-iron cooking pans, Chinese bowls and plates.
Turning westward from the diversion at Mongyu gate for a few miles brings one to Muse airfield, and just before reaching it, a fleeting glimpse of the Namkham valley. The contrast with mudbound Kyukok is startling. The forbidding mountains have receded into the far distance till they appear as airy towers and legendary fastnesses. In the foreground lies a promised land whose approaches are verdant mounds of a bright green, among which the river winds, to emerge a shining silver, tree-lined in the sunlight. On either side of the river lie rice-fields, wearing, in their segmented patterns and their even growth of young shoots, the unmistakable signs of a loving human care through centuries. Everything beckons with a gentle lushness, as it once did to the Tais coming through the barren mountain passes.
Coming down into the valley itself one is not disappointed. The magic quality which distance lent it has disappeared, but a rustic charm pervades the whole valley. On the right as one bumps along the corrugated road, are the rivers, the paddy and the dreaming mountains; on the left are gentle slopes with clumps of bamboo rising fanwise, brick wells with upward tilting covers, and groups of huts to form villages, all set at intervals with the most perfect balance and placing.
Namkham town is famous for two things. One is the American Medical Center, the hospital where Doctor Seagrave trained nurses for the hill areas. Renouncing his connections with the American Baptist Mission, perhaps in order to reassure the Sawbwas and people of his disinterestedness in promoting medical service without the corresponding proselytization for Baptists Christianity, Dr. Seagrave had trainees sent to him from every Shan State, from Karreni and even a few from the Chin Hills. The Center occupies a hill overlooking the town, with a fine hospital Nurses' quarters, a small chapel, Dr. Seagrave's house, quarters of other doctors and a post-primary school for those trainees who, owing to the general low standard of education prevailing in the hill regions, needed more schooling during their training. Patients were drawn from all over the Shan States and surrounding hill regions, where the Doctor's reputation was so great that processions of surgical cases waited for months in all the areas to which he paid his periodic visits; finances from the Shan States stipends for nurses, from Dr. Seagrave's personal efforts to raise money from U.S.A. and from the Fulbright foundation. With such self-sufficiency, set in this beautiful valley right on the borders of Burma, backed by mountains and facing only the mountains of China, it was no wonder that Dr. Seagrave and his helpers operated in a world of their own, as it were. While much of the training was unorthodox according to the conventions of the British Medical Association, most of it was peculiarly suited to the needs of the hill areas.
Alas, despite Dr. Seagrave's disavowal of those very influences so suspect by the Buddhist majority in this country of encouraging minority disaffections, circumstances have developed so that the Shan State trainees have all been withdrawn from there for various reasons, and Dr. Seagrave himself arrested.
Namkham's more ancient claim to fame rests on its bazaar, second only to Kengtung in size. This is because of its situation on a meeting point of trade routes,. Three miles from here a bridge spans the Shweli River. From here the motor road runs 70 miles to Bhamo and thence northward to Myitkyina.
Thus the motor follows in the steps of ancient migrations. According to local chronicles these migrations started in centuries before Christ. There is no certainty about such ancient records. What is fairly certain, is that a Tai Kingdom was existing in Nanchao (southwestern Yunan) in the 7th century AD., and that there were great migrations in the same century. The Shweli and adjacent areas became the chief political centres of the first sizable Shan kingdoms. This early Shan power, known in various records as Kawsumpi (turned into Ko Shan Pyi by the Burmese) or the Mong Mao kingdom is claimed by the Hsenwi chronicle to have had its seat in the present Hsenwi valley, by others in an abandoned site near modern Se-lan 14 miles east of Namkham. Whatever the truth, there is no doubt that the Mong Mao power was centered somewhere in the present Hsenwi State.
From there the Shans spread southeast over the present Shan States, northwards into Khamti region north of Myitkyina, and west of the Irrawaddy into the country between the Irrawaddy, Chindwin and Assam. (Centuries later, Assam too was conquered -- hence the Ahom Shans there of present day). By Anawrahta's death the Mong Mao power was still independent, till the 13th century we hear of its extensions southwards till Moulmein and eastwards beyond Kengtung, westwards to the over-running of Arakan and the invasion of Manipur, Assam being subjugated in 1229. As if in punishment of such aggressiveness, the army of Kublai Khan came down in 1253 and after hanging about the frontier for some thirty years, Chinese forces swept down on Pagan. When the last of King Anawrahta's dynasty died, however, the Shans were still going strong and divided Burma between them, holding sway for over 2 centuries. But soon after this power waned, and from King Bayinnaung's time till the turn of the 19th century, the Shans have steadily spent themselves fighting, valley against valley, principality against principality, ...
Adjoining Hsenwi on the west is the state of Taungpeng. Hsipaw and Mongmit bound it on the southwest and northwest, enclosing thus an area of 938 square miles. Taungpeng has the distinction of being a "Shan" State inhabited by a majority of Palaungs and ruled by a Palaung dynasty. Its geographical formation has determined this as we shall see.
The Palaungs are of a different stock from the Shans. They belong to the Mon-Khmer family which settled in Burma much earlier than the Tai migrations. Their brothers in this family are the Was, who, as we have seen, preceded the Khuns in Kengtung and are now concentrated in their own territory further east, and the Padaungs of Mongpai and Karenni far down south, whose women traveling across the world in Bertram Mills Circus, and penned into an enclosure at the Glasgow Exhibition, have interpreted to a gullible section of the western world the beauty of Burmese women as a whole.
The Palaungs have also contributed to this type of advertisement for Burma, but in a much more obscure corner. One edition of the Encyclopedia Britannica (which despite the name is an American production) contains, the section on Burma, an illustration of the Burmese woman's dress. This shows, rather vaguely outlined, a figure in long draperies, the chief of which is a hood reaching from the head down to the knees. Perhaps this was inspired by the Palaung woman's costume of which the most distinctive feature is also a long hood. But the Palaung dress in real life is a most elaborate and gay, even gaudy affair. There is a dark-blue jacket, and apron over a skirt, and leggings under and lower again than the skirt; and on these garments are panels of bright blue, scarlet and white. On the head is set a small red velvet hat decorated with shells, and over this hat is thrown the long hood, consisting of the patchwork of blue, scarlet and black velvet bordered with white. On the wrists are varnished bamboo hoops decorated with girdles, bangles and a general profusion of silver complete the picture. There are many different clans of Palaungs with minor differences of dress, but to the outsider, they all appear the same.
Actually the Palaungs will tell you that the reason why they wear such a large hood as part of their dress is because of their descent from a naga Princess. This princess, Thusandi, who was sporting in a tank on the Mogok hills three centuries before the time of Buddha, fell in love with the Sun prince, and having an affair with him, was in time delivered of three eggs by him (the semi-divine confinement of those days being always after this convenient and sanitary fashion). Before the eggs could hatch out, however, the father was summoned back to his home. On arrival there he sent Thusandi, by two parrots messengers, a loving letter in which was enclosed a precious stone. The two parrots loitered on the way with other parrots, and during one of their dalliances, a Taungthu and his son removed the jewel and enclosed some bird's droppings instead.
When Thusandi received the present she was so angry that she took the eggs and threw two into the river and one at Kyatpyin, near Mogok, on a rock. This third one broke, and scattering its contents around Mogok, produced gems of all kinds to this day. One of the ones thrown into the river floated down to Pagan where it was saved and in time hatched to produce Minrama, a King of Pagan. But the other one floated miraculously upstream to Bhamo, where it was nursed in a golden casket. It hatched a male child who grew up and married the daughter of the Shan Chief of Se-lan. He had two sons; the elder became the Emperor of China and started the Burmese name of Udibwa (Born of an Egg) for all the emperors of China in the chronicles dating from those days. The younger son had a kind of leprosy which improved only by contact with cold mountain air. Hence he founded Taungpeng on the crest of a hill, and to this day his descendants, the Palaungs, wear a patched cloak in memory of his grandmother's scaly skin.
It is because the Palaungs are hill-dwellers that they have dominated this State. Taungpeng is watered by the Nam Tu as it continues westward from Hsenwi State but its north-south course throughout the state lies only ten miles from the eastern border. This ten-mile strip contains valleys and undulating hills, but all the country to the west of the river is excessively hilly. Except in the southwest corner where some valleys exist, the lowlands in between the ranges are mere gorges offering no rice fields or hospitable habitation to the true Tai.
The position of the capital, Namhsan, in this hilly mass is interesting geographically. There is a main ridge running roughly along the centre of the state northwards from Hsipaw valley, increasing in height as it goes, till it reaches about 6000 feet near the middle point of Taungpeng. There it bifurcates and sends two arms down southwest and southeast, while spreading northwards into a mass of hills (as high as 7000 feet) and gorges (as deep as 3000 feet). Standing between this northern mass and the southern bifurcations which enclose valleys, at a point which has always been known as Hpak Tu Mong, the gate of the country, is the capital of Namhsan.
The town was founded in 1865 by one of the rulers. It is built on a ridge and follows the narrow, confined pattern dictated by its site. Here, as in Hsenwi, allied bombing during the last was has wrought great havoc. The Sawbwa, who lost his Haw and valuable property by bombing in other towns, also lost one beloved son in a Liberator bomber flying over these very parts. Sao Khun U will be long remembered by us for all of his companionable qualities and his record in the RAF; if not for having had to change his name, on request by Oxford authorities, to U Khun Sao, on the grounds that the signature of his original name, producing S.K.U., was often mistaken for casual initialing where initialing was out of place --- a change which Sao Khun U made most obligingly but which, I remember produced the most violent rage in his English foster-mother Mrs. MacCallam, wife of a Commissioner of the Shan States, who ran the Cheam Ethical Society, sponsor of all sorts of causes, and who demanded to know where was the intellectual comprehensiveness of Oxford that it could not take a Shan name in its stride ...
It is interesting to remember that the Haw at Taungpeng was designed in a long rectangle to conform to the ridge and the town, and incidentally to provide a long long verandah along which exercise could be taken when, as during the monsoon, Taungpeng is shrouded in mist and rain clouds, and the perambulators of the Sawbwa's numerous progeny could be wheeled within the shelter of its roof. For the Taungpeng Sawbwa is blessed with many, many children, all rosy looking Palaungs, and despite these hostages to fortune in a world so uncertain of the future he remains himself, the most cheerful-looking man in the whole of the Shan State. To see him is to love him.
From Namhsan on a clear day it is possible to see evidences of the oldness of the Palaung race in Burma as a civilized Buddhist people. Villages and monasteries dot the horizon in all directions. The administrative circle in which Namhsan stands is about the richest in the state. Here, as with all the Palaungs, the economic life is centered around tea cultivation. It is the staple crop for this hilly state and its importance in the life of the people can be gauged by the linking of it with a semi-divine origin. The legend says that when King Alaungsithu of Pagan was on a tour of the Shan States he sailed down the Nam Tu and stopped at Taungpeng to build a pagoda, the Taungme Zedi. Having completed this he camped a little to the east of Taungme where another pagoda the Loi Sawng was, and kept up a festival of seven days and seven nights. During this pwe he brought out certain seeds which he had obtained from a bird which had miraculously preserved them in its throat, and, sending for two of the hillmen, he handed them over to be planted between two images of birds which stood to the northwest of the pagoda. The seeds sprouted and became the first tea-plants in Taungpeng, providing it with such riches that it came to be called, frequently natthiywet or the leaf of fruit given by the nats. But at the time of bequest the two receiving Palaungs, being unpolished and democratic hillmen, held out only one hand to receive the seeds instead of cupping both hands reverently. Hence the more common name of lapet (for let-ta-pet, one hand), and hence more important still, the Palaungs have as punishment, never repeated the full prosperity out of the cultivation, it being carried to Mandalay by profiteering middlemen.
Tea cultivation is easy compared to rice cultivation, especially the way the Palaungs engage in it. The plants are left to grow with only a few weedings at the beginning and end of the rains. When after ten or eleven years, the plants weaken and the crops become poor, the garden may be cut down and burnt; then fresh shoots will spring from the stumps and in three year's time the Palaung has a new tea garden. He picks the leaves four times a year. Kason to Nayon, Waso to Wagaung, Tawthalin to Thadingyut, and Tasaugmon, and after steaming and rolling them, makes of them lapetso as well as dry tea, by either pressing them in baskets or drying in the sun. In picking and curing he needs experience and skill which he possesses in superior degree to cultivators of other reaches.
These other races in the state are chiefly Shans in the valley in the east and southwest, and Kachins who are steadily pushing down from the north.
The big hills of Taungpeng hold far greater riches than tea, however. Bawdwin, the great "silver pit" of Burma contain lead, silver, zinc concentrate, copper matte, nickel speiss, gold and antimony lead in quantity. This rich storehouse lies to the northeast of Namhsan and is approached through the town of Namtu, 40 odd miles from Lashio. Nam Tu lies in a very pleasant little hollow --- one looks down from the Inspection Bungalow on gentle undulating contours carrying trim houses and tree-lined roads. It is the living quarters and the marketing town of the Burma Corporation Ltd. which works Bawdwin and has been much in the news lately in allegations and counter allegations.
The truth is that all mining seems, to an unprogressive and unstriving temperament like mine, an ugly way of getting the riches out of Nature, necessary though it be. It is going against the face of Nature so to speak. Where the cultivator tends the earth gently and waits for the seasons to enrich the seed in her womb until she gives forth fruit with a smile of achievement, the miner must hack and burrow and sweat to wrest what he wants from its lodging place. The story of Bawdwin which a Thakin labour leader told over the wireless is not merely one of exploitation of a brown proletariat by white capitalists. It is a story similar to that witnessed in the slag heaps which disfigure the beautiful gold of autumn leaves in the Welsh countryside, the weeping women crowding round a pithead in the Ruhr, the ugly propped up houses against the steep hillsides of Mawchi, the corpse of a British assistant brought in from there to Taunggyi, not long ago, in search of a Christian burial far from his home. The mine once set up, is master --- of the sweating workers diseased or fatigued, and of their superintending officers too, who live in well-appointed bungalows and drink whisky or gin at sun-down for there is an idleness of the spirit, matching the poverty of the workers in a mining town, set as it usually is in a surrounding with the economic life of which it bears no relationship. The sahibs are engrossed in technical problems only, human contacts are confined to a small company of colleagues, they have not the administrator's pride in bearing the white man's burden to compensate them.
Bawdwin itself is 19 miles from Namtu and reached by the Company's rail trolley. Bare hills, deep ravines whose sides the railway must perfore hug tenaciously, the Nam Tu rushing swiftly downwards, with its waters a foamy yellow from the washings of ores, and latrines for workers built at intervals of this flushing waters, are my most vivid impressions of that ride. Tiger Camp is passed on the way; it is a row of lodging and bazaar sheds shut in cruelly by the impinging hillsides, an aspect which was no doubt responsible in part for the damning description given of it by a visiting labour leader. Yet a little further on, a swimming pool and parking place for the communal car of the Sahibs, carved out of a slight rounding of the V's formed everywhere between the ranges, though eloquent enough of the difference in amenities provided for superintending staff and workers, was even more strongly suggestive of the common bondage imposed on all by the clefts in which the search for metals forces them to live. When there are, in the beautiful Shan countryside, all the glorious stretches of upland down and sylvan valleys to wander on, the men serving the mine must remain cooped under the shadow of the overhanging hillsides. The "silver pit" town itself is no exception. The barracks of the workers are echoed by the row of sahibs's houses side by side. The railway runs along the bottom of the left, and at the far end of it is the whir of the mine night and day. We had Shan tea with the schoolmaster and a citizen of the town, prominent among those voicing the grievances of labour, and then coffee and cakes with a minute and golden-hearted memsahib in one of the houses. Her father had worked all his life in the mine before she herself married into it, and she had lost her two brothers also in the mine where the whirring went on as she spoke to us, just as it had done on the days when her brothers' bodies were brought home.
One of the features of our independence is the way Shan Sawbwas have emerged from their seclusion to take part in the offices of either the Shan State or the Union as a whole. There is the President, Sawbwa of Yawnghwe; the president of the Shan State Council and prominent leader in religious affairs, the Sawbwa of Samkha, and there is the head of the Shan State and Shan minister, the Sawbwa of Mongmit, who alone of all the Sawbwas, has been merged with the Union Cabinet all along, over whose shoulders the mantle of foreign affairs hovered from the first, alighting awhile as if to see how it would fit, and now finally settling down comfortably and sleekly like what the Americans call a custom-made garment.
Although the duties of the Head of Shan State as Shan Minister naturally bring him into the Burmese Cabinet, it appears to many a most suitable personality to fulfill the role --- he looks so Burmese and has such a true Burmese accent unattained by any other Shan that the last syllable of his name is often mistaken for "Cho", sweet in all ways, instead of the "Khio" which means in Shan, green, as emeralds perhaps, for Mogok and its rich valley of precious stones was once part of his State and though it was taken away a long ago the connections remain, and the dowager Mahadevi, the Sawbwa's mother was one of Mogok's most be-gemmed daughters.
What I set out to say was that the differing aspects of these three big Sawbwas, and even more, that of a fourth frequenter of the Rangoon social round, the Myosa of Kokang, often lead people to ask what the background of their states is. They know about Yawnghwe, but little of Samkah, Mongmit or Kokang.
The state of Mongmit lies immediately adjacent to Taungpeng on the northwest, but it is a difficult task to get to its capital from Namhsan because of the hills intervening. One has to come south again to join Mandalay road at Kyaukme; from there it is necessary to motor 77 miles to Mogok, and then curve round again northeastward for 24 miles to Mongmit. In fact, from anywhere in the Shan States this is the only approach to Mongmit town. This lack of a direct route and past wars have left it a disproportionately small and undeveloped center for a state which is wealthy and a major one among the Shan States.
Actually its present area of 3733 square miles is the result of successive reductions. On the north the area which has Mohlaing as its center was in past days united under the same Sawbwa as Mongmit. After British annexation this area was attached to Bhamo district as a subdivision. On the south again, the gem-studded Mogok township and the Ruby Mines District as a whole was once under Mongmit state but was exchanged in 1607 with the Burmese king for Tagaung. Not only was the state larger, it held authority over eight minor Sawbwaships including Hsipaw and two of its present sub-states. From those glories Mongmit actually lost its privilege of being a Shan State under indirect rule after British annexation and was directly administered as a subdivision of Ruby Mines District for a while.
The reason for this was perhaps Mongmit's position on the edge of the Shan States proper, which made it almost a free-for-all territory as far as raids and depredations were concerned. At the time of the annexation it was estimated that the population held 50% Kachins, 20% Palaungs, 20% Shans, and 10% Burmese. No ruler could last long with these different elements being played up by his usurpers. When the chaos became too great, the Burmese King, and later the British authorities, would put an outsider to try and restore order.
Strangely enough the state is said to have been founded in 1238 by a Sawbwa from Kengtung hundreds of miles away. Although at present, Kengtung and Mongmit are not connected by marriage relations in any way, an unusual fact among big States, the hand of Kengtung has appeared more than once in the past centuries of Mongmit history, and one wonders why in modern times the connection has not been renewed in the customary fashion ... The Kengtung Sawbwa who founded the state installed his son as first Sawbwa of Mongmit, but this son soon had to return to rule his own state and handed over Mongmit to Sao Kai Hpa. Sao Kai Hpa built his capital town with a great deal of very stout fortifications but whether in the ensuing five centuries these fortifications were of any avail the records do not say. Certainly by the time the records speak there was absolute chaos; a ruler would set up, usurpers would attack the town and burn it down. In three years from 1837 to 1840 for example, nine Wuns were sent down from Mandalay, one after another, as each was killed or driven out by rivals.
The Burmese King exasperated by such goings on, fetched a Kengtung Sawbwa westwards again and installed him as ruler. There was comparative peace for three years, then the Sawbwa like his ancestor, had to return to rule Kengtung and the free-for-all fights started again. Now each successive aspirant had Kachins behind him, and after victory the Kachin soldiers broke up the pagodas and sacked the town as their share of loot.
After annexation therefore, the British installed Sao Maung, later Sir Sao Maung, of Yawnghwe as Regent. He was placed under the deputy commissioner of Ruby Mines District and an assistant commissioner was stationed at Mongmit to advise him. Punitive expeditions were also carried out by Gurkha Military Police on disorderly elements. Still Sao Maung failed to keep order, so in 1892 the British took over the state as a subdivision under the direct administration of the Assistant Commissioner.
Meanwhile, despite all vicissitudes of war and assassinations, the direct line of Mongmit Sawbwas had continued. An infant son, Sao Khin Maung, had been left by the last of the line and as being educated in Rangoon during Sao Maung's regency. After leaving school he was trained as a Myo-ok, and was installed as chief in 1906. The chaotic days of Mongmit were ended. Sao Khin Maung received the KSM in 1912 and the CIE in 1933. Mongmit entered the federation of Shan States in 1923 soon after Federation was instituted. Sao Khin Maung died in 1936 and was succeeded by his son Sao Khun Hkio, our head of state, "Shan Min" and foreign minister. Mongmit State, which suffered exclusion from the company of brother states for a period and looked to be even more excluded when the Sawbwa married an English wife, has staged a come-back into the forefront of the Council of Saohpas.
The main wealth of Mongmit State is in its timber which is the highest output in the whole Shan State. The B.B.T.C., Steel Brothers, and Messrs. Darwood and Co., all had workings there before the days of State Timber Extraction, and the royalties accruing from timber to the Sawbwa makes him one of the wealthy chiefs among the States. Mongmit also grows a fair amount of rice and used to supply Mogok area and Taungpeng from early times. But now the Mogok people begin to think the Mongmitters keep the best paddy for themselves and sell the worst, so they buy Namkham rice to a great extent.
The capital is at present little more than a village. It lies in a hot malarial valley which is, moreover, cursed with gnats during the greater part of the year. These gnats are so ubiquitous in Mongmit State as to have brought forth the old adage that he who sails on the Shweli River in these parts must learn to dance --- a St. Vitus' dance if possible, to ward off the insects. The Shweli river runs through the whole State.
Mongmit town though small now is really set among extensive ruins. Two streams enclose it, the Nam-Maung and Nam-Meik which join up later and flow into the Shweli 16 miles south of Mongmit. Of the Nam-maung a tale is told, accusing it of such selfishness as has banished a bigger river the Nam Pai which might otherwise have crated a more fertile valley in the state. This river, the Nam Pai rises in Mongmit State and was keeping company with the Nam-maung. When an elephant strayed to its banks one day, the Nam Pai caught it and with great generosity shared the carcass equally the Nam-maung. But when, a little while later, the Nam-maung caught a porcupine, it proffered but one quill to the Nam Pai and ate the rest. Disgusted at such behaviour the Nam Pai forswore the greedy river's company and made a detour through Mong Long where it has created a fertile valley.
A road is now under construction from Mongnaw on the Mandalay-Lashio road to Mongmit, so perhaps a more prosperous time lies ahead of the town. Its name, which means "the place where the dah fell" has not been one of good augury for the hacks of Kachin soldiers in search of enshrined treasure are still visible in the pagodas around.
There remains one other big State among the Northern unit. South Hsenwi, which now more commonly takes its name from its capital of Mongyai, is, as we have seen, the central division of the old state of Hsenwi, although the ruling family is actually the continuation of the original Hsenwi dynasty. The separation, effected in 1888, gave the new state an area of 2351 square miles.
Since South Hsenwi did not have an independent existence till 60 years ago there is not much history to it. The state contains a lot of high land; a big mass in the north-centre of it contains Loi Leng, the highest mountain in the Shan States (8777 feet), but the rest of the high land is rolling uplands rather than sharp ranges. These undulating downs are well-watered, capable of raising cattle, tobacco, and diverse garden produce if the state, which was recorded in 1942 as having made "quiet progress" were to be developed further.
Mongyai, the capital, is itself a healthy spot. It is quiet but there is neither dereliction nor sadness in the air as at Mongmit. Perhaps at Mongyai the air is infected by the spirit of the Sawbwa and Mahadevi, a young couple who are the happiest example of the monogamous marriages which is more and more replacing polygamy among the Sawbwas today. This particular marriage was, according to all Hollywood recipes, of handsome youth meets beautiful maiden, a love marriage begun in early years, but blessed also by the full sanction of Sawbwa traditions. No "arrangement" could have been more satisfactory, for the Mahadevi was the eldest daughter of the Sawbwa of Lawksawk, another monogamous marriage, whose mother in turn was a daughter of Kengtung Sawbwa. And what fruits it has borne! The Mahadevi, still a beautiful girl, has six little daughters all in a row, and now faces the difficult problem: Shall the seventh child who will have arrived by the time this is in print, be a daughter to make her the blessed mother of Seven Gems before she starts a line of seven sons, or should it be the long-awaited heir?
From a little north of Mongyai, a road runs 32 miles to Tanyang, and from there a mule-track leads into the country of the "wild" Was. South of Mongyai, another road runs to Mongkao and from there, another mule track to Pangyang, seat of the "tame" Was of Manglun which is included in the Shan State. More of the Was Anon.
The other remaining part of Hsenwi which has been detached into a separate state is Kokang, formerly the a-she-let, the East Riding, which lies wholly east of the Salween and reaches the China border. Indeed, Kokang may be said to be Chinese state within the bounds of Burma. The Shans used to list the number of villages in Kokang as 600, of which they said that five were Shan, and 455 where Chinese, the remainder being Palaungs, Was and Mengs. Not so long ago the wife of the Chief had bound feet, and the family spoke only Chinese. But still, this territory has always been under the suzerainty of Hsenwi, and made a separate state only after the recent Japanese war.
There is hardly a square mile of flat land in Kokang (you still cannot drive to this state but must approach it on a pony) yet the State is very densely populated compared to most parts of the Shan States and is also disproportionately wealthy. The inhabitants have spent incredible patience and labour in carving out terraces for rice cultivation out of the hill sides. In parts, each terrace, no more than six feet wide, may be six feet higher or lower than the next. The proverbial industry of the Chinese, you might say. Yet what will you say to the universal opium habit that prevails? Moral strictures seem beside the point when everyone smokes habitually and at all hours. It is like the Frenchman and his wine, and like the vineyards of France the poppy fields of Kokang, no less beautiful and no less a part of the people's life, stretch all over the State. Thousands of acres have been planted from earliest days. One cannot say that the essence so potent for such fragile flowers, has killed the race which has laboriously made those rice terraces. The moral appears to be, Work only when you must!
The Kokangese sits by with his pipe of opium while his paddy is husked by a stream. He makes the water flow along a bamboo runlet and through one hollowed-out end of a log. On the other end is a pestle poised over a mortar filled with grain. When the water is in the trough its weight presses the pestle down, when it runs out the pestle is raised again. Meanwhile, on hollowed out logs which he has hung around his house, the bees which have returned from sipping one particular white flower which blooms on these hillsides, make honey of a strong and simulating character.
Thus, "far above the years and nations", separated from the western world by the unnavigable Salween, the Kokangese sits with his pipe of peace, outside of all the striving trepidations and decisions of our clamourous times. Swinburne has described this empty tranquility of another poppy land: "There is an end of joy and sorrow / Peace all day long, all night, all morrow / But never a time to laugh or weep. / Their end is more than joy or anguish, / Than lives that laugh or lives that languish, / The end of all the poppied sleep." But who knows, there is an approach from the east also, and Kokangese may yet be awakened from his sleep to a new life of action, fears and blooded strife.
The Wa State of Manglun has, like Kokang, a non-Shan ruling dynasty which has been feudatory to a power in Burma for as far back as the records show, paying tribute at times to Hsenwi, at times to the Burmese King direct. Indeed Manglun, though commonly considered a Wa state, has more Shans living in its western half than Was. These east and west divisions are formed by the Salween which bisects the State from north to south.
Pangyang, centre of the western half is the seat of an Assistant Resident, who was, till recently, Harold Young, born into the American Baptist Mission of old Marcus Young, one of the great missionaries of the Burma-China borders. But Harold is, more than anything else, the Big White Shan to us. Is it telling on him to missionary authorities to recount his beliefs in were-wolves and similar ghosts of the Shan countryside, his sympathy with all magical manifestations which are so much a part of the Shan life? They are but aspects of his thorough soaking in a Tai environment. I remember cycling along the Alipore Road one day in Delhi far from the reaches of the Tai, when suddenly we were startled by a stream of imprecations in bawdy Shan flung out of an open window. It was Harold returned from some wild place and lodged in the roadside annexe of a hotel, trying in vain to get an hour's sleep in a noisy city.
These imprecations, like his bug "husky" frame belie Harold's tender nature. When a few of the Was of Manglun were brought, with Harold, to Lashio to be shown to Thakin Nu during his Shan tour, our gentle Premier, impressed by the somewhat wild appearance of these co-citizens of his country, is reported to have said: "We must invite them down to Rangoon --- but we had better have their guardian along with them too." That of course may be just a story about the Was and Harold Young ...
In east Manglun is the residence of the Sawbwa, a Wa, and the main state of Was. These Was have long since given up head-hunting and are said to be Buddhists. The heads on the posts of their villages are always animal heads. The "wild" Was of the Wa State proper to the north are the actual headhunters, are not cannibals either, as popular legends used to make out, especially in the tale that their old folk ascended trees to escape being eaten, only to be shaken down by the young like so much ripe meat for the pot. The heads were needed for productivity and for blessing on all important occasions of life such as marriage deaths, the founding of a new village. The reason is that their ancestors, two tadpoles call Yatawm and Yahtai, were barren until they wandered one day into a country of men and ate of human flesh, after which, the couple old as they were, produced nine sons and ten daughters all in a row.
The tame Was of Manglun appear not to relish tadpoles for ancestors, and substitute the gourds of the boothi plant instead. But their version also bears some grotesque touches. According to them Yatawm and Yahtai were a cross between nats and humans. One day a pair of gourds fell to them from the skies. They ate the gourds and planted the seeds. Within three years, the boothi creeper entwined itself over hill and dale and bore two fruit each as big as a mountain. Meanwhile Yahtai, after having eaten the gourd became pregnant and was in time delivered of a daughter with the ears and legs of a tiger. In the eyes of her parents, however, she was a beauty. They declared she should marry no man except one strong enough to open the gigantic gourds. Meanwhile from within the gourds great booming noises were issuing. They were by what biological connection with Yatawm and Yahtai one knows not, also pregnant.
In time a Nat, Kun Sang L'rong came down to earth and was unable to fly back. He wandered to the region of the boothis eventually, and seeing the Tiger Girl, fell in love with her. He sent for a heavenly sword and cut open the gourds. From one, tumbled out all kinds of animals, from the, other all kinds of men including Shans, Chinese, Kachins, etc. But Khun Sang L'rong declared that the race started by him and the Tiger Girl were, however, the Was, the original human beings, and that their country should always be independent of powers north, south, east, or west.
South of Mongyai and Manglun, we come to a group of five states which together once formed the South Riding or Taunglet of the old Hsenwi power. But it is not by reason of their common subordination in the past that I consider them as a group. It is because of the fact that together they can be said to form the heart of the Shanland. Geographically they are centrally situated, forming the greater part of the old plateau which as we have seen, is the core of the Shan States. The Salween runs its north-south course to the east of them, having only the jumbled ranges of Kengtung on its left bank. About 80 to 100 miles west of the Salween, a great range starting a little south of Hsipaw and running south all the way down the borders of Karenni marks off the limit of the plateau proper. Within the area enclosed thus by the Salween and this western range lie the States of: Keshi Mansam (bordering on Hsipaw), to the south of it, Mongkung in greater part and Monghsu in the eastern corner; to the south of this, the state of Mongnawng, and to the south of this again, the state of Laikha. The Nam Pang, biggest tributary to the Salween, flows roughly north to south through the whole region, with many sub-tributaries entering it along the course, while from the western range rises another main tributary of the Salween, the Nam Teng.
Ethonlogically also, these states are, "par excellence", the Shan States of the Shans. The Shans who nowhere form the sole population of any state reach here their highest proportion to the total population --- 47 percent in Kehsi Mansam and a similar percentage in the surrounding states. Moreover, they, unlike the Khuns of Kengtung or the Shans in Namkham or of Hsipaw and Mongmit, have no adjacent areas of a different people to influence them --- they are the Tai of Burma unadulterated --- the true Shan.
This is the region too, of Shan romances, in particular that of Khun Sam Law, a lover hero who was forcibly separated from his wife and who traversed the tracks along these river valleys in search of her, singing his quest of her wherever he went, marking the spot where each incident of his love story took place as momentoes for the Shan race.
The story of Khun Sam Law, unlike so many other legends handed down, has no Burmese or Hindu-Buddhist classical threads in it; it is no tale of King, nat or princess, but comes straight out of the Shan countryside, with the age old theme of wife and mother in conflict over a man's love. Though the theme is universal, however, the incidents are so typically Shan that I recount the story at some length.
Khun Sam Law, like most Shans of substance, came of a trading family of Kengtawng, a dependency of Mongnai State to the south of this region. Besides being rich he was handsome and all the women in town were bent on marrying him. In particular, one spinster, an ugly woman full of wiles, had won his mother over into pressing her suit. Khun Sam Law tried indirect methods of refusing his mother's plea -- he asked for 500 red cows and capital to try his hand at a trading venture, and thus left home.
The next few years were spent in visiting the northern towns as far as Taungpeng, and then he retraced his steps. While passing through Mongkung he went into a house to settle a business deal, and there saw the daughter of the house, Nang Upem. She was beautiful and he fell in love at once. Very soon, they were married. A year passed in all the joys of a happy marriage and Khun Sam Law forgot his parents and the spinster from Kengtawng.
One day, however, he remembered his mother, and suddenly overcome with remorse at his forgetfulness, he decided to go home for a visit. His wife, though pregnant with child, did not stay him. Arriving at Kengtawng, Khun Sam Law was forbidden by his mother to return to the wife whom she hated already for having estranged her son as she thought.
Nang Upem, waiting in Mongkung, grew worried at his long absence, and deciding that her child should be born in his father's home, she set forth with her servants, her cows and all her possessions.
Her mother-in-law received her with smiles in Khun Sam Law's presence, but soon found a pretext for sending her son out on another trip. Then she began to torture Nang Upem. She hid knives in the rice basket, so that the girl, in scooping up rice for the daily pot, cut her hands. She stuck other knives in the balustrade of the bamboo stairway, so that Nang Upem in fetching water and balancing her hand along the balustrade, cut her hands again. She fried foods all day so that the smell of oil cooking made these cuts into sores, and she served pickled sour dishes to make the sores fester.
Unable to bear more, Nang Upem set out, in advanced pregnancy, to return to Mongkung. Her child was born on the way, a son, and still-born after all his mother's sufferings. Nang Upem cried with the infant body in her arms: "What shall I do with you, my son. I do not want to put you in the river for fear you become a fish. And I do not want to put you into the earth for fear you become a frog. Let me put you on the branch of this tree. Become a little bird and call to your Father all you can. Tell him to come quickly after your mother." So the baby became a koel, which calls "Paw Hue, Paw Hue," all through the spring and summer, "Oh Father, Oh Father", the heart-rending cry of a lost firstborn. Nang Upem went on, and on arrival at Mongkung she died.
Meanwhile Khun Sam Law returned, and finding his wife gone, he got his fastest horse to follow her. He asked all he met on the way, even little children playing on the sands of the Teng river, for news of his wife, and everyone made the same reply. "Yes, she has gone, she has passed us. A long while ago. She passed us twice. The first was when she wore the lotus in her hair and she laughed at every step she took ... The second was when she wore `mawk mai,' and cry, cry she did at every step. Hurry, hurry or you will be late."
Khun Sam Law made more speed but he was too late. He arrived at Mongkung when his wife was already laid out. The house was crowded out and he could not get to her side. How could he see her? He took out all his money and threw it into the air. People scrambled and he passed through. Arriving at his wife's side, he looked at her, and stabbing himself, died.
They laid the two corpses in the same coffin, but his parents having followed him, his mother more revengeful than ever now, thrust a bamboo carrier's pole between the bodies to separate them even in death. But Khun Sam Law and Nang Upem like all true lovers, had prayed together, and after death they were taken together into the sky. If you look at the constellation called, in the West, Orion, you will see the bamboo pole with three stars to show the notches of the bamboo; on one side the red star which they call Betelgeuse is Khun Sam Law, and on the other side is Nang Upem, the star now called Rigel. The evening star is her little dog, and the Plieades her chickens. Her loom, her cows and other heavy possessions she left in Mongkung, where, as rocks, they always have been respected by the Mongkung people.
While Khun Sam Law sounds the keynote of the Shan spirit in romance, there are also the more material symbols of the Shan culture which are common to all the settlements no matter in what area. I refer to the dah, the Shan Khamauk, and the Shan bag, the characteristic lacquer and paper, the animal dances performed at festivals, and the music of the " Shan-bey-hton!" Some of these features have Burmese equivalents, but whereas they have disappeared from use in the towns of Burma and figure largely only in rural life, they still dominate the scene in all Shan centres including the capital town; nowhere have Shans become urbanised in the modern sense.
Down in the big towns of Lower Burma, our picture of the characteristic Shan is a trousered gentleman, rather untidy with a turban, a moustache, long hair, tattoos and a dah, many features in fact which were common to Burmans but are now relegated to the realms of the Shan by a cropped and blazer generation. The picture is a true one. This old gentleman may be seen walking to the bazaar in Taunggyi on a bazaar day, shikkho-ing a Sawbwa in a haw, or trimming a hedge in any village with his dah. But over and above the dahs of some other bamboo civilisations, the dah of a Shan is something special. His personal dah, that is, not the domestic one for chipping and hacking, but a finer one, the lethondaw which the humblest Shan has, for fighting, hunting and for dancing.
The best dahs come from Kehsi State, one of our middle group. And what is a best dah? My husband, a true Shan, says that "It should be heavy but not too heavy, light but not too light, in fact a good dah!" One which moreover, does not rattle in its hilt and whose sheath is wound as tight as possible with string. Such a dah may be bought for about Rs 20 to Rs 30, for that price you would not get a stout cord wound round the sheath with the loop for slinging over the shoulder. Good cords like these, of green or red wool from Laikha may cost as much as Rs 10. A good Kehsi dah with one of these stout Laikha cords, with the tip of silver by a local smith, matched by a few, a very few more bands of silver around the bands of string, and the whole oiled with linseed oil is a handsome memento of the Shan States.
Sometimes three, or even four of these swords are used to dance with, but this to my mind, smacks too much of ingenious contrivance and jugglery to add to the virtue of the dance. What is most enjoyable is a "straight" two-sword dance. Performed by a lithe tattooed Shan, from Laikha perhaps, the lightning flashes of movements from one attitude to another, the play of the taut muscles during the holding of a pose, the quick brushes of limb against limb in the passing by hair's breadth, which interpret the brushing of sharp steel against the vulnerable flesh, and the underlying all, the insistent drumming which corresponds with heartbeat, all add up to perfection of grace with virility. It is easier with such dancing and its unvarying accompaniment than it is with the Burmese stage dancing, entrancing though that is, to feel the possession of the dancer by a supra-natural exaltation; and his shikkho-ing and silent invocations before commencement have more continuity with his performance than the similar prostration's of an anyein dancer distracted by cosmetics, chit-chat, and bawdy witticisms.
The drums which are the most distinct feature of the accompanying music for these dancers (the rest being only cymbals and gong), and which are produced in three of this group of States, Mongnawng, Kehsi, and Mongkung, contrast greatly with Burmese ozi in their long stems, sometimes ten feet long, perhaps for the greater reverberation demanded by the primeval nature of the music which is pure rhythm, no melody, and which never fails to hit the blood to an uncontrollable pounding.
As for the familiar Shan bag, surely its design is a touch of genious; one of those obvious inventions, like the kinks in the hairpin, in the weaving and fitting together of the pieces so that there are no seams in the part which must bear the load. People who collect Shan bags should not be satisfied with the Lake area products of silk and wool most commonly sold, nor even with the thickly woven Kachin bags which never cost less than Rs 16 nowadays, but should try to get also the less familiar Lahu, Khun, Palaung and Black Karen styles.
Another characteristic Shan product is the excellent paper made of the mai-hsar, a species of the mulberry. This paper is strong, aesthetically pleasing, can be used for wrapping, writing and for decorative purposes. You can watch women even children, making it in many Shan towns. They boil the bark after the outer rind has been removed, pound it till it becomes a real pulpy mash. Then dividing it into little balls, each ball to make a sheet of paper, they fill a little cone or bamboo cup with it and pour it on to a tray made of pinni stretched tightly on a square bamboo frame. This tray lies submerged in water so that it is easy to make the pulp lie evenly all over. Then they lift the tray out, letting the water drain off, and lean the frame against something to let it dry. With sunshine, the pulp hardens in a few hours into a large sheet of paper which can be lifted up.
Inseparable from this paper are the folding books made of the thicker variety of it, still used in every cultured Shan home for copying verses, family legends, state chronicles and religious sermons. When the covers are lacquered and gilded such folding books are permanent treasures. Inseparable again from these books is the chanting which is the Shan's only true expressions of music. If he wishes to sing "songs" as we understand them, he sings a Burmese song, that is, provided he knows one. Otherwise he picks up what he considers to be a sufficiently poetic rendering of any theme, such as material copied out in these folding books, and chants it in a rhythmic intonation of which there are at most half-a-dozen established forms.
Of the origin of the animal dances no one is sure. Perhaps Tibet? Certainly they are not danced in Burma or Siam. Here is a funny thing about them. Chief among the traditional animals are the winged horse and the to. This to is a long sheepish animal, and might be thought in fact to represent a sheep, the Shans being unable to render the Burmese tho correctly. But no, the Shans who speak English, the same Shan suggest Tibet as a place of origin, say it is a llama, an animal not to be found in the traditional mythologies nor among the actual Shan State fauna, and the result is rather confusing; because there are lamas in Tibet, but not this kind of llamas, which are found in South America, and what connection is there between the Shans and South America? Perhaps my ignorant speculations here will bring forth an answer.
It is only to be expected that the Shan culture of which these dances, chants, folding books and swords form the most prominent features should be channeled through the group of states we are now discussing. They lie directly on any route which traverse the Shan States from north to south. Entering from the southern end through Taunggyi, the trunk road comes east to Loilem (in Laikha State) and then turns northward through Mongkung to Hsipaw. An alternative route branches off near Pangkitoo to Kehsi, and passing through Mongyai, goes to Lashio.
These motor roads are but following the tracks of centuries ago. One might therefore have expected that the capital towns here would have developed from being on the highroad of emigrations and commerce, but alas, the warring habits of past days made the position of these capitals the very reason of repeated destruction. Not only the particular Shan predilection for intestinal wars, but also the Burmese armies marching south or east to subdue revolting tributaries or aggressive Siamese across the southern and eastern borders had to pass this way. It is no use to count old scores and remember that the Burmese burnt here and the Shans there --- wars were the fashion in those days all over the world, a luxury which power-seeking nation makers could afford better than their modern counterparts because their weapons were less cruel and destructive.
A glance at the individual histories of these central states in very recent times will reveal two destructive campaigns, typical enough of all that went before.
Kehsi Mansam, in Burmese, Kyethi Bansan, has an area of 551 square miles. Most of this area is open rolling country, almost treeless except for the hills towards the west. The people have lived by agriculture. They get their rice from neighbouring areas and carry it to Taungpeng where, like the Hsipaw and other traders they exchange it for tea which is carried to Mandalay and realises money to bring back Burmese and imported goods for sale. As we have seen, the dahs of Kehsi are famous; good quality hats are also produced.
Kehsi is really a Myosaship. It was created as such in 1860 by a Royal Order of the Burmese King. Till then, it had been a part of Hsenwi. In 1882, the Sawbwa of Mongnai, an important state just south of this central group, rebelled against King Thibaw. The states all around Mongnai had to decide which side they would be on, not only in the Burmese expedition sent out to deal with Mongnai but in the subsequent Limbin Confederacy got up by Mongnai and other Sawbwas after the British conquest of Burma. These Sawbwas fled east from the Burmese King and were given refuge by Kengtung. When they returned after the rumpus had died down, however, they found that the Burmese power had fallen to the British. Some stayed in their states and gave allegiance to the new rulers, but others, notably Mongnai and Lawsawk, returned to Kengtung and invited the Limbin Prince, one of King Mindon's sons who was then in Moulmein, to come to them via Siam. They raised an army for him in Kengtung and marched westwards in a gallant attempt to restore a Burmese king at Mandalay, but were defeated by British punitive expeditions, when the whole thing fizzled out.
To those who are familiar with the environs of the Kengtung mountains and the personalities of many who lived in those times, the attempt is as sad and romantic as the adventure of Bonny Prince Charlie. At the time the Limbin Prince was as debonair as the Young Cavalier, "As he cam' marching' up the street, the pipes played loud and clear, / And all the folk cam' running' out to greet the Cavalier, Oh-Oh!"
Elder Aunt Tip Htila, then a young girl more interested in attaining masculine prowess than maidenly beauty, and getting in the hair of the officers in charge of the recruiting centres set up at the south and east gates of Kengtung Big Haw, trying to get herself tattooed along with the recruits, in which she did not succeed, being fobbed off with drawings on her legs in blue writing ink, and to get the invulnerability charms of gold and silver let into her flesh, in which she did succeed, thus getting two men sacked in wrath by her father, Aunt Tip Htila's imagination too was fired by the Royal Personage years --- many years --- later, however, when she was on a visit to Rangoon she met in the shop of P. Orr and Sons, a stout and middle-aged gentleman who greeted her.
"Don't you remember me?" It was the Limbin Prince, complacent enough without a throne.
"Had we succeeded them," he said, "I would now be King of Burma and you would be the Chief and only Queen. What a fine place we might have made it!" Aunt Tip Htila has been used to such gallantries all her life, her masculine spirit has never succeeded in hiding her beauty; and how she flips away all the compliments with her wit!
I must, by the way, introduce the Limbin Prince to American readers as the grandfather of Miss Junerose Bellamy, with many apologies to the venerating spirit of Burmese tradition for putting the cart before the horse as it were.
Now I have used a most unfortunate metaphor, as though I likened the young lady to a cart, but she will forgive me if she is familiar with that endearing character Ma Bokeson in the old Burmese jingle: "Miss Plumpity, with buttocks so round and in pair, Makes of them a cart to ride her to the fair ..."
Anyway, here was the rebellion of Mongnai and the central States had to take sides. Three of the five in our group (Kehsi, Laikha, and Mongkung) decided to stick to authority both times: The Burmese first, then the British to whom they sent representatives in 1885-86. For this decision they suffered ravages at the hands of their neighbors.
Mongkung, to the south of Kehsi, is a much richer area. Though the state is not very much bigger, it contains a large and productive valley made by the Teng, in which the capital town stands. This valley is one of the characteristic Shan valleys. You see it lying spread out with paddy fields as you top the ridge from the south, with enclosing hills on which pines and oaks grow. Where the hills rise higher and recede into the dark blue mass overhung with clouds and called the Elephant's head, are headwaters of the Teng which winds across the plain. You see bamboo clumps, pagodas, and monastery roofs, and the grouping of houses to form a town while smaller villages dot the distant horizon. All around in the fields here and there are flashes of water in sunlight, buffaloes and cultivators with bamboo hats. This is the complete picture of Shan valley settlement and the towns and villages which you meet after miles of uninhabited hill road may or may not contain all of its features. In Kengtung, Mongkung, Namkham, and Hsenwi you see the fairest, most beautiful and smiling examples.
The Teng River flowing through Mongkung, though so near its source, is a quiet stream, only rippling. That is because Khun Sam Law, meeting with Nang Upem along its banks and fearing that his words of love would be echoed by the waters, told the stream to hush. It is this same Teng, which having perforce to be silent here, lets out all its strength in a magnificent roaring drop further south in Mongnai, creating one of the biggest falls in Asia.
There is plenty of good rice, very sweet oranges, very juicy and delicious pineapples which will no doubt find their way into Mrs. Hunerwadel's cans in Taunggyi next year, and some take in this rich Mongkung valley. Good pottery and dahs are made in the villages surrounding the town.
Mongkung also has the distinction of still possessing a Haw from pre-war days. It is built of wood and though not an exact replica of any particular structure in the Royal City of Mandalay, it recalls the palace very strongly. Low and single-storied, it is approached by a vast open "room" supported on lofty round trunks. Leading in from that is another big square hall similarly supported on pillars, at the far end of which is a railed-off dais and on that the yazapalin. With the exception of Kengtung, none of the Shan Chiefs sit on this yazapalin or high throne. They use a thalun in from of it, reserving the higher seat as an altar. Behind this, in the central and two side-wings are the living quarters.
We had the rare treat of seeing in the open hall of this Haw, the Sawbwa mobilising his men to fight the KNDO on our way north from rebel-bound Taunggyi in August 1949. What a change coming from there, where buildings had been turned into "War Office" and "area Commander's Officer", passes issued with a stamp in English saying: "The Karens, Taunggyi," and streets full of very young khaki-clad figures hardly old enough to raise a down on their cheeks, to see in Mongkung so soon after, the traditional personal retainers of the Sawbwa called in. There they were, moustached Shans of the old gentle type, with turbans and pinni boungbis, siting on the floor of the Haw, receiving each his rifle from the Sawbwa's own stock, while bags of rice brought in by headmen were being loaded with rolls of bedding on to lorries; and the Sawbwa himself, who has his own eccentricities, was holding a rifle as he rushed about giving orders with his gaungbaung awry. Where the Union army could not reach out far enough or soon enough, the very same apparatus which had got up expeditions for or against the Burmese king had to be set creaking again.
Actually, it was a memorable trip, to see the Shan countryside waking up to this sort of activity. We had slept at Loilem the night before, the night during which the Shan officer sent by the KNDO to propose "Karen-Shan amalgamation against the Burmans" to the Hsenwi Sawbwa at Lashio, had returned. We woke up at the noise of the returning car, which had driven without a stop all night, at the house of Brother Sao Huk, who sheltered everyone during those few nights to be told (in hushed tones as the KNDO officer was in occupation of the Circuit House nearby) that Hsenwi had given the answer: "No Amalgamation, We will fight"; had sped onwards as soon as it was light to see Hsenwi if only gratitude for having declared his intention so uncompromisingly when all sorts of wild rumours started by the KNDO that the Shan Sawbwas were in with them had been poured into our ears during the five days we had been "under" the rebels, and a little further north had run into Kehsi Sawbwa who was rushing through the states to tell each Chief to mobilise. It was this order of the Special Commissioner's that we saw the Mongkung Sawbwa obeying in his own inimitable fashion.
The chief figure in commanding these levies raised from all the states, who later did such a fine job was the Sawbwa of Laikha, adjacent State to Mongkung and third partner in the group which had stood up for Mandalay and the Pax Britannica.
During the 19th century also, Laikha had had a prominent military history. In 1794 the State was ruled by Khun Lek who was a great favourite of Shwebo Min, and who held his throne for a record 60 years. On one occasion he took command as Bogyoke of a conglomerate army of all the races under the Burmese King, including Manipuri horsemen, and marched south to subdue the Karens of Karenni who had just begun to consolidate themselves as a border menace and rebels against the Burmese King. His son was also a military leader. He succeeded in raising a Siamese siege of Kengtung and as a reward was given the administration of Lawksawk, Mongping, and Mongkung by King Mindon. When the Limbin Confederacy attacked the three non-cooperating states, however, Laikha was ravaged from end to end. And then followed a year of famine, so the State has had to start its prosperity again only after British Annexation.
Laikha has always been noteworthy for its iron ore which supplied material for all the dahs of surrounding areas. The iron implements of all kinds such as spades, axes, swords, scissors, and tongs made in Laikha itself were famous for their quality and found a sale as far off as Chiengmai. Laikha lacquer and silverware also have high reputation. Thanapet is produced in quantity. Panglong of the Panglong Conference is in this state, a pretty village six miles outside Loilem. It was chosen for its central position for states north and south, and is the site of a big bazaar dating from olden days. At present an Anglican mission maintains a hospital with a very good doctor and nurse in Panglong.
Mongnawng, to the east of Laikha became an independent Sawbwaship after its ruler had driven back the Laos of Chiengmai from the Kengtung border during Pagan Min's reign. It enjoyed peace and progress until the time of Mongnai's rebellion. The Mongnawng Sawbwa then was brother-in-law to Mongnai and decided to throw in his lot with his relative. He fled to Kengtung and Burmese troops entered and ravaged the state. Mongnawng is mostly open undulating country, with jagged limestone hills sticking up here and there. The capital lies in the fertile Nam Pang valley. The finest bamboo work in the Shan States is done here. Boxes of all kinds, with minute designs in coloured and natural spathes, and khamauks. The essentially rural character of Shan society to this day is seen in use made of the khamauk by all classes, even the towny non-agricultural strata, rather than of the sunshade. A Sao may, if he likes, line his khamauk with silk, stitch a band of velvet for holding the cord, or enclose the tip of the crown in silver. But a khamauk it remains, woven to shield the peasant majority against sun and rain.
To the east of Mongkung lies the small state of Mong Hsang, once an independent state. The two states joined the Limbin Confederacy but only in name. The country here is largely rugged and with barren hills, but none are very high and after crossing the Nam Pang on a floating bridge, a bamboo marvel which spans the entire stream, its submerged layers like the pipes of a giant organ for water music, you drive, ten miles further on, into the village of Monghsu, indescribably quiet and peaceful with its old pagodas and tiny stream, the journey's end of an excursion along the byways of the true Shan country.
If in this chapter I have written very little under the heading of individual states and instead, a long preamble, it is because the people and the life in these states is best pictured by a description of the Shan environment. There is not a single big town in this whole region, only villages all over, in which people cultivate their patches, visit the bazaar on every fifth day, and for the other four, either live in their homes with their iron and bamboo wares, their khamauks and their Shan paper, until one of the four pwes comes around with gambling and kadaws and dancing, or else go forth to trade with a bullock cart like Khun Sam Law, chanting all the way of the pleasures of reunion with wife and children.
Continuing southward from the central states on the extension of the Shan plateau is the State of Mongnai. Mongnai belongs to our central group in its essentially Shan character, but it also stands apart by reason of its greater importance. Today it takes fourth place in Council, a high rank which has been handed down from the days of the Burmese monarchy.
Right through the 19th century, Mongnai was the seat of the Burmese King's Viceroy. A sitkegyi sent from Mandalay held court here, his chief duty being to gather in revenues from the chiefs of the southern Shan States. Attached to his court was a Bohmu and a garrison of Burmese soldiers, not only to keep the peace generally, such as it was, but also to deal with constant encroachments on the border from south and east of Mongnai by the Siamese from Chiengmai. There were about 400 of these soldiers and they had to be fed by the Sawbwas of the states surrounding. For pay they were sent Rs. 10 each per month from Mandalay, and as perquisites they had the pillage of the countryside ...
The garrison and sitkegyi's entourage naturally made Mongnai a prosperous town. Probably the largest then in the Shan States, for contemporary estimates put it at 5,000, 10,000, and once even 16,000 households strong. The campaigns just before and at the start of the British annexation have reduced the smallest of these figures by about two-thirds. In fact, with all Shan capitals, the glory is of the past. Not only did internecine wars destroy them, but also disease, for these valley sites are never the most healthy spots. The Shan race today, is not only spent by the constant warring of the past but also sapped to its vitals almost, by malaria.
Of the antiquity of Mongnai, there is no doubt. The traces of old cities found so often in the Hsenwi area, cities of which nothing is known, not even surmised, merely brickwork in jungle as they are now, are found again frequently in Mongnai State. Burmese records put the founding of the capital city at 519 BC, and assigns to it the classical name of Kambawza. The king was probably feudatory to Mong Mao; all is obscure, but it was certainly a large power, rivaling Chiengmai and extending at one time over Yawnghwe right to the Myelat area.
In a refixing of the boundaries in 1802 when much of this area was taken away, the sub-state of Kengtawng was added. Kengtawng, you will remember, was the home of Khun Sam Law of Shan romance. In more recent times it produced another son, a very different reputation, who is responsible, indirectly at first, and directly later, for all the carnage which left these central states a ruin at the end of the 19th century.
The real name of this man is obscure. He became known by his exit from monkhood, being a phongyi-lutwet, a monk become man as we say with an opprobrious "Nga" thrown in for his war-mongering habits.
Twet-Nga-Lu, having made his debut by an attack on Mongnai town, was later appointed Administrator of Kengtawng State by King Thibaw. Mongnai Sawbwa, objecting, petitioned against the appointment. King Thibaw flew into a rage at such officiousness and sent for the Sawbwa. The Sawbwa sent his sister instead. Vain sacrifice of a girl --- she was arrested, not honored, and Mongnai was summoned again. He shilly-shallied and the Sitkegyi, interpreting this delay as an intent to flee, instructed the Sawbwas of Mawkmai and Kengtung not to harbour Mongnai if he fled to them. This drastic order touched off a Shan rebellion led by the Sawbwa. Wholesale massacre of the Burmese followed; no hiding for nay Burman, the Shans had a formula for detecting all masquerades. Pointing their dahs they ordered every man to say in Shan "Tomato!", "Makhersohm" it was, but alas, no Burma can produce any such sound, and all their broad renderings of "Makaisun" and such like were cut short with a thrust. It was a bloody debacle. Five Burmese regiments were rushed down from Mandalay together with auxiliaries from the loyal states. Mongnai fled.
After the Burmese ravages, Twet-Nga-Lu took power and some other leaders ganged up with him, but they were defeated by neighbouring Mongpawn who handed back the State to the Sawbwa's adherents. Twet-Nga-Lu made more attempts, getting Siamese soldiers for raids not only on Mongnai but on nearby states also. Meanwhile, the British had arrived, and recognising him for a nuisance, they sent an expedition which caught him actually in his bed having a nap, from which he was aroused and arrested by young Lieutenant Fowler, officer in charge.
Mongnai State today has an area of 3100 square miles enclosed between the Salween on the east and the range running south from Hsipaw on the west. The Teng is the chief river of the region, creating a broad and long valley in which, however, the capital is not situated. The big waterfall on the Teng is in this region, but is difficult to approach for visitors. A car can go only as far as Hsai Kao to the north of the falls and from there a detour has to be made on foot.
A smaller valley is the Nawngwang, mistier even than the average Shan valley into which the winter sun, as soon as it kisses the mountain tops, rolls down the mist, to lie uncomfortably damp over the enclosed valley, till a late hour in the morning. Here and in the Ho Na Long Circle, is grown good tobacco, second only to the Langkha tobacco of Mawkmai State and, in the past, a great draw for traders to Mongnai.
What a race of traders the Shans are! The picture of a feudal peasantry evaporates before this more prominent aspect of them. No villains yoked unremittingly to the soil, the humblest peasant must by ancient usage stop producing every fifth day and carry his produce to the market to be exchanged for something else. Be it only bundles of pine resin for kindling wood, or as here in Mongnai, bamboo containers of Kyein-ye, rain water which has been allowed to drip into these containers from the leaves of the cane plant all during the monsoon, and is sought by people from all over as hair restorer and promoter; be it only such paltry produce, the Shan still walks miles to bazaar with it and brings back a fair exchange. But the Shan who works harder, let him, after a series of exchanges, amass a cart and oxen and sufficient money only to buy a cartload of anything, he is off on a trading venture to north, south, east, or west of the whole Shan country. The lone carter chanting his way along the winding hill-roads in the lazy happiness of feeling himself his own master, or the ones who preferring company, bivouac with their night fires offsetting the sound of waterfalls and the cold pine-scented winds, are as age-old a feature of the Shan countryside as they are true of today.
The five-day bazaar, the big markets at pwes, and the preference of the Shan for individual effort have caused this habit of trading. Also the peculiar reluctance of the hill tribes to leave their fastnesses for long or to grow other than their traditional produce. The Shans are their natural suppliers. Take only the case of the Palaungs of Taungpeng and their tea. Shan traders from every state, Hsipaw, Mongyai, Kehsi, Mongkung, Laikha, and as far south as here at Mongnai take rice or other produce north-westwards and going up to the Palaungs, get tea which they take for exchange at Mandalay. A great deal of this trading is done by motor now but its essential character remains the same.
Mongnai town is situated about 30 miles southeast from Loilem on the trunk road eastward from Taunggyi. Its tall double gateways stand bereft of their arches, gates, walls and all, yet driving through them you enter at once into the unmistakable air of the antiquity which rests over Mongnai. An air which is curiously reminiscent of the old capitals of Upper Burma. Like them, those centres of our past history fashioned in teak and expressing in the ascensions, foliations and perforations of this beautiful and malleable material, a joy and wonder at the life of woodland beasts and celestial beings alike, and shading them when finished in fragility and loveliness to be immolated by the buffeting of yearly monsoon and never-quiescent war, pervaded also by the doctrine of annisa which makes vain endeavour of the attempt to perpetuate in stone and careful repair, the achievements of a life which is but one short period in a recurring cycle of lives, like all our past cities, founded, lived in and abandoned under these influences, Mongnai shows little or nothing of its past glories.
Yet, as in those other capitals, something persists. Who but the most insensitive of materialists will say that Mandalay is nothing more than a name now because its glories of teak and gold and mosaic are no more? Who can deny the suggestion of an intangible beauty which rests above the decayed and brunt city, above the dusty plain, a suggestion which, moreover, would be felt without a sight of the solid monuments of pagodas which do remain?
The human spirit does not vanish into nothing at the dissolution of its shell it seems, but leaves behind a faint emanation, so faint that only with the accretion of myriad emanations through the centuries it whispers, evoking, saddening or reminding --- who knows? --- of past lives lived here.
In Mongnai, if one must count the factors which suggest such a spirit, there are the layout of the old streets, the great trees, pipul and tamarind, the profusion of old roofs of monasteries and pagodas, the grouping of palms.
The Sawbwa, Sao Pye, the man with the most famous laugh in the Shan States, a full-hearted guffaw that finds causes to be heard every few minutes, succeeded his father not long ago. The old Sawbwa's funeral in January 1949 was the most recent one of a big Sawbwa of the older generation. There is always a great to-do when a big chief dies. People, especially other Sawbwa's families from every state have an obligation, amounting to a family duty, to attend and most officials motor from whatever area they are in, as a mark of sympathy. A camp of bamboo bashas, called tawmaws here, must be erected, a mess hall put up, food laid on for a week, pwe and gambling provided, besides all the arrangements for observance of funeral ritual, including provision of white mourning for guests who come unequipped.
Mongnai Sawbwa's funeral was attended by the Premier and his entourage and in the traditional Shan style the gathering for religious and social observance was utilised for administrative discussions. One wonders who translates the Premier's speeches for the benefit of the English press. Sometimes a good job is done --- although the admonitory Burmese idiom must always sound a little peculiar in English, some admirable quality, of the earnestness of the speaker perhaps, comes through. At Mongnai, he was reported by one paper to have begun his address to the Sawbwas by saying: "Don't be fools!" Surely not.
No visitor to Mongnai should miss a visit to Maung Nyun, the carver who fashions the little wooden carvings painted in bright enamel paints, the better to show off tribal costumes and attitudes. So many people importune ask for these carvings and cannot understand why they are so hard to come by. A visit to Maung Nyun would explain why. He works alone; the figures sold in the Main Road of Taunggyi are travesties of his work. He works holding the piece of wood between his two feet as a vice, and crouching down to reach it, works with an ordinary knife and chisel. It is a great strain on his eyes, and no wonder that he finds it easier money to mend watches, and will turn out a series only to oblige the Sawbwa, the Chief Education Officer in Taunggyi, or U Hla Pe who keeps an art shop. And then, not always!
To the southeast and southwest of Mongnai lie the states of Mongpan and Mawkmai respectively. Though both large they are of relatively recent origin.
Mongpan is interesting as a rare example of deliberate colonisation by a Burmese power, a colonisation which put settlers on jungle land and has yielded a surprisingly rich harvest. In 1737, King Alaungpaya returned this way from an expedition to Siam, for Mongpan, which straddles the Salween, marches with Siam on its southern and eastern boundaries. The King created a Myosaship but only of the territory west of the Salween. Then in 1867, King Mindon ordered the Myosa to colonise east of the river. It was wild there --- only Burmese patrols sought out transgressing Siamese in the jungles. The Myosa got settlers from among his subjects and from Mongnai. The jungle was cleared in two river valleys, and villages were founded. Four administrative circles of Mong Tong, Mong Hang, Mong Kyawt and Mong Hta were marked out. Then valuable timber was found. Teak, padauk, thitsi, etc. could be obtained in quantity. Individual workings began at the end of the 19th century and were succeeded later by T. D. Findlay and Company. Now the state Timber Board finds Mongpan the richest timber area in the Southern Shan States, capable of sufficient production in a short time to buy out the assets of the Company.
With the closing of the Siamese frontier at Kengtung, cheap textiles obtainable in the shops of Taunggyi are trickling in by this Mongpan border, and the State, hitherto prominent only for timber and a little mining of tungsten, may yet become a trader's paradise like Kengtung.
But before passing on all of its Siamese frontier trade, Kengtung has, already pushed its burden of Kuomintang Chinese troops this way, where, it is rumoured the KNDO remnants skulking in neighbouring jungles have sent contacts to make common cause with them.
Mawkmai, also straddling the Salween, became a Shan State only after 1800. Before that it was not clearly defined as either Burma or Siam. But a certain Hsai Khiao of a family from Chiengmai which came and settled here in some position of authority proved of such help to the Burmese King in putting down rebellion and dacoity that he was created Sawbwa of the area.
Mawkmai, the capital, is situated in a big valley twenty by six miles broad, of the Nam Nyin, a tributary of the Teng. Rice, oranges, cotton, and other crops are produced in quantity and quality. Coconut palms are a prominent feature here as in Mongpan and Mongnai. This fertile valley was the chief target of the raiding Karens who issued from their fastnesses periodically to swoop on the valleys and replenish their food supplies. "The mountain sheep are sweeter, But the valley sheep are fatter. And so we deem it meeter to carry off the latter." I quote from a faulty memory perhaps. But this spirit of raiding has gone on without a break since ages past. In ancient days for human captives to sell in Siam as slaves. In more recent times for wholesale replenishing when the British authority, being already established, forced Karenni to pay Rs. 60,000 as compensation to Mawkmai. And even more recently, in 1948, by other Karens occupying these same fastnesses, in Taunggyi for money and ammunition. Finally in 1949 for ammunition, rice, clothing, money, building material, vehicles, fuel, etc, etc. May that be the last.
The Teng river flows through Mawkmai State after leaving the Mongnai area, and in the long valley created by it lies Langkho where the finest tobacco in the Shan States is grown. Before the war, this tobacco was packaged in tins and sold as Blue Band pipe tobacco. It was a successful business, the army giving it considerable custom. This tobacco is no longer obtainable now owing to the difficulty of importing tins. Another industry lying idle for lack of encouragement.
Langkho is a big village by Shan standards. A Christian missionary centre is maintained by an Anglican missionary with three little daughters, golden like daffodils, but being transplanted on to the low-lying Shan soil of Langkho, known instead as Nang Naw, Nang Noom, and Nang Wo Kham, that is to say, Tender Shoot, Youthful Bloom, and Golden Lotus. Langkho is an extremely hot place, and malarious. One wonders, despite the present missionary's twinkling eyes and sense of humour, whether the original choice of location was not made as an attack on the hottest bed of "Sin" so to speak. For in Langkho, alone of all the Shan settlements, the men and women bathe openly in unashamed nakedness. A local male going into the water with a wrapping round his loins would soon bring the women around to ask if he were hiding a disease. In past days, the British officers touring these regions and, too shy to go near, using their binoculars for a good view, could justify their action as an observation of wild life. Indigenous visitors unable to use such a ruse end by giving a wide berth to what is the chief sight of Langkho.
Westwards of the south central states we come, across ranges to three river valleys which run north to south and roughly parallel to each other. They are the valleys of the Nam Pawn, one of the main tributaries of the Salween, the Nam Tam Phak which is a tributary of the Nam Pawn, running parallel a little west and south of it, and the Nam Pilu, another tributary further south and west again. Within these valleys are the States of Mongpawn in the first valley, five little states of Hopong, Namkhok, Nawngwawng, Wanyin, and Hsatung in the second, and the three states of Samka, Sakoi and Mongpai in the third.
In coming westwards to these states we leave not only the open main plateau for narrow confined valleys, but also the states where the purely Shan population predominates without question for those where the Taungthu population is very much in prominence. The Shans further east may also have Taungthu blood but it is not obvious in most cases, the Taungthu women having discarded their dress and settled alongside their Shan neighbours. But here, the Taungthus, retaining their dress, their separate villages and their particular pursuits are also found to be sometimes equal to the Shan population, and in the case of Hsatung, actually forming the majority and the ruling house.
The Taungthus, called by the Shans Tawnghsu, are very closely related to the Karens. Their speech is not unlike Karen dialects, and a pre-war census actually listed them under the same heading as Karens. The belief generally held in the Shan States is that they migrated northwards from Thaton in Burma after King Manuha was taken captive to Pagan by Anawrahta Min. A settlement of them was started at Hsatung while others settled in the Myelat further to the west. This migration appears to be a backwash northwards, for the Taungthus migrating southwards into Burma earlier than the Shans had already been pressed southwards as far as Siam and Cambodia and the Lower Mekong. Here in the Shan States they do not go east of the Salween nor north of Mongkung State in any large numbers. The western range of the Shan plateau proper appears to be their chief habitat.
Even casual visitors to the Shan States will be familiar with the appearance of Taungthus, for they live in the villages surrounding Taunggyi and the Myelat valleys and come into the towns on every bazaar day. The men all wear Shan dress, but the women when decked out in new clothes round Thadingyut or Tabaung still put out a magnificent show of tribal costume. The black smock has slashes of purple or green velvet let in at the elbows, the black leggins similarly decorated, the earplugs of a reddish alloy richly chased; the black wimple hung with coloured tassels shows the silver hair ornaments, and the whole is set off by the pink cheeks and sturdy gait of the average healthy Taungthu girl.
This is of course the finished product which enters the bazaar grounds after a five-mile walk from the village. What a natural beauty these hill women show, one writer has exclaimed, forgetting that the instinct to adorn is one of the most primitive. The Taungthu girl's fine showing on pwe day is altogether calculated. Those earrings have been soaking in tamarind water and a dash of turmeric all night. Half a mile before she arrives at the bazaar, at the stream under the banyan perhaps, where the muddy village lane comes out to join the town road, she has stopped to wash her feet and legs and don the brand new leggins, has chewed a handful of uncooked rice, and rubbing it between her palms has applied it to her face to take the heat and sweat off.
Most Taungthus are cultivators of taungya rice and wheat and diverse garden produce, their industry and folk knowledge resulting in fine vegetables of all kinds. They are prosperous by the standards of Shan States agricultural economy -- many Taungthus when they have bought a stock of heavy silver jewelry, run to a stock of gold set solidly among their teeth.
Buddhism is the religion they profess, but it is a Buddhism very largely overlaid with spirit worship as is only to be expected from a purely rural population who have no literature of their own though they do possess a written character. Of their fervour for the religion there is no question. When the relics of the Buddha were scheduled to be brought up to Taunggyi early this year, the feeling everywhere that the visit of such sacred objects could not help but bring blessing to the people, perhaps in the form of peace, was justified most signally in the surrenders by Taungthu insurgents here and there, surrenders made with the idea of being able to come into town to worship when the relics arrived.
As it turns out, however, the beneficent influence of the Relics brought about a truce, rather than the peace hoped for. Despite the efforts of a peace negotiation committee the Taungthus, the "bad ones" that is, are still giving trouble. In the Shan States they are, in fact that baffling elusive 5 percent that is withholding our millennium of gold and silver rain.
And what is the aim and object of the Taungthu "revolt", such as it is? People who like making capital of human stupidity and vanity will tell you that there has always been bad blood between Shan and Taungthu, that the Shans look down so much on the Taungthus that they have a rhyme: "That oafish Taungthu, he will worship the little ridges of the paddy field in mistake for high towers, the piled up coils of chicken's droppings in mistake for pagodas." In the face of this bad blood, it may be said, the hardy Taungthu resents living under the rule of the effete Shan and desires separate states where the Taungthu population is large, to wit, most of the southern Shan States on the west of the range which runs south from Hsipaw.
Yet the Taungthus voiced no desire for a Taungthu autonomy in British times. None of the states in which they predominate are large, nor, except in the case of Hsatung have they had histories of longer than a century as independent states under Chiefs, Taungthu or Shan. It was after independence that a Taungthu desire for increased representation in the Shan State Council was first heard. The quota allotted was three out of a total of 25, and this remains the quota today.
Actually, there has never been a regular Taungthu revolt equivalent to the KNDO affair. Violence started only as an aftermath of the KNDO occupation of the Shan States. Recruitments of Taungthus were made by the rebels; in Taunggyi for example, they were offering Rs. 100 cash down and a rifle in hand to any who joined, plus the prospect of so much loot later. A greater impetus was given then by the appeal to them as blood brothers of the Karen, to unite against an old enemy, the Shan. When the KNDO scuttled, these armed Taungthus were left behind, and they harry the countryside levying protection money on stray settlements of Gurkhas, collecting food sums from villages by a mile or two outside the town, dashing into the towns themselves in smash and grab raids. All the refuge given by woods and hills and jungle paths are theirs, and the anonymity given by picking up a hoe and digging at an isolated taungya.
Mongpawn, the most easterly of the states in which the Taungthu population is prominent is 366 square miles in area. It was set up as a Myosaship in 1816 but given back again to Mongnai later. Only when Mongnai fled from the Burmese wrath and the Mongpawn Myosa went down to Mandalay, was he reinstalled as an independent Chief. He showed great level-headness and loyalty all around in the confused years that followed, defeating the usurper Twet-Nga-Lu and handling back Mongnai to the exiled Sawbwa's followers, yet keeping out of the Limbin Confederacy and maintaining peace in his state. He was created a Sawbwa by the British, and found occasion to stand up for authority again about 25 years later under very different circumstances.
In the early twenties the strike fever initiated down in Rangoon by the University Boycott spread all over the country and apparently came up to Taunggyi and into the Shan Chiefs School. This Shan Chiefs School, though it was by the 1930's not much different from any other good boarding school in Burma, was in the first two decades of its institution a rare and wonderful place. Its purpose was to impart some sort of Western and modern education for the sons, nephews and more distant relatives of ruling families and the families of high officials. For this, a sum of Rs. 100 per boy was allotted by Government. The curriculum was the old Anglo-Vernacular Code, Vernacular meaning Burmese, however, and not Shan. The Headmaster was British as was a good deal of the controlling policy. But the atmosphere prevailing in the school was pure Shan of the late 19th century. The high age of the boys for one thing; there were many pupils with moustaches. Then the boys were allowed private servants and private furnishings. Aunt Tip Htila says that she sent her son to boarding school with eleven retainers and his own piano. But Aunt Tip Htila is a notorious exaggerator. Most notable of all, arms, dahs, and firearms, were allowed.
Yet let it not be thought that this old Shan Chiefs School was therefore a wrong sort of institution. These things were but a reflection of the social conditions prevailing. Outside of such concessions a much stricter discipline than one sees in the schools these days was enforced. The British Headmaster carried over many of the austerities of a British public school. Baths had to be taken under a cold tap out of doors in the bitterest winter's frost, long walks and hours of organised sports were prescribed; on the other hand, formal Shan dress of trousers, jacket and turban, even for small boys was insisted upon.
It was at this institution that a strike took place in the 1920's for some cause forgotten except that it had to do with religious observance or a Shan national spirit. The strikers decided to quit school as a protest against British authority. Fully armed and descending by jungle paths they made tracks for Mongpawn, 38 miles away, Sao Sam Htun the Mongpawn heir, who twenty-two years later was assassinated in Rangoon being among them. Arriving at Mongpawn, they went to the Haw still fired by a pride in this revolt of Shan chiefs and chiefs-to-be against the ruling authority. Alas for their patriotic fervour. Old Mongpawn called his son to stand out, and pointing to the dahs which hung by their read and green cords along the wall, he said: "I put you in school and you have run away. Now which one of these am I to use on you? You have the choice of the green on the red."
The upshot of this was not an execution, however; merely that the strikers, now feeling very flat and exactly like school boys once again were sent back to Taunggyi. Here an expulsion order awaited them, but old Monpawn said that as he had captured the prisoners and granted them his pardon, no one else could punish them. He got his way because he was always right. Only old Aunt Tip Htila seemed to have little respect for his judgment. Taking great offence during a visit to India of Sawbwas with their wives, when he went without wife and she without husband, and he quipped, while cocking a thumb at her turned back, that in fact he did have a Mahadevi along, she hung a notice outside her Haw for years, saying "Mongpawn Sawbwa Not Allowed."
The Mongpawn Sawbwa who was assassinated in 1947 succeeded his father at a very young age after training as an administrative officer in Burma proper. The qualities which led to his election as the first Frontier Areas Minister were his from the beginning, but under the old system which gave no scope for any Chief to play a prominent role in Shan affairs outside of his own state, the first 19 years had perforce to be spent in obscurity; for Mongpawn unlike other more fortunate states is a small and poor area yielding insufficient revenue for any development schemes.
Sao Sam Htun spent his time studying deeply, especially of politics and government, and in working personally at agricultural experiments which might benefit his poor State. Grapefruit, avocado, olive and other foreign trees as well as improved strains of native crops were planted and tended by himself. When Bogyoke Aung San presented at Panglong in 1947 the scheme for a union of the hill peoples with the rest of Burma, Mongpawn was chosen by Shan, Chin, and Kachin delegates as Counselor for Frontier Areas, in spite of being a small Chief, for his reputation as a hardworking and studious man, his close touch with all Frontier problems, and his easy and affectionate disposition towards all. The jubilation with which he and his friends greeted this appointment at last giving him an opportunity to use his talents can be imagined, so how just more their greatest sorrow at his untimely end.
Mongpawn lies in a long and narrow valley. The population of the state is almost equally divided between Taungthu and Shan. There is believed to be mineral wealth but nothing of importance is worked up to date. Cotton is grown, and thanapet of a fine quality, but not much rice. The town itself is an unhealthy spot and when one passes it now on the 38th mile from Taunggyi to Loilem, it wears an air of wretchedness and poverty. Its glory is in the avenue of Butea trees which form a flaming highway of red blossom as you descend into the valley from the west during February and March.
27 miles from Mongpawn is Hopong town. It is situated in an area which according to its name, was once more thickly covered with elephant grass, until in the middle of the 18th century, a Taungthu and his brother migrating northwards decided to settle and found a prosperous state. During the dissensions of the Limbin Confederacy when the Myosa had fled, an official of Taungthu extraction was appointed to the myosaship and did so well that he was confirmed in the appointment. Thus Hopong is a strong Taungthu area, although the present Myosa, his extraction ignored, is not regarded as Taungthu by the Taungthus.
The whole state is but 18 miles from north to south and 15 miles at the widest. Though it is very hilly towards the north and east a good proportion of the land is cultivated. Rice, oranges, thanapet, tobacco, and onions are raised, but chiefly the value of Hopong lies in its situation as a crossroads. It is only 11 miles from Taunggyi the capital; the road from Loilem which is a continuation of both the northern Shan State road and the Siam-Kengtung road, as well as of the branch from Mongnai, meets at Hopong the road which runs south through the rest of the Tam Hpak valley to Karrenni and from there south through Loikaw to Toungoo. Thus the pwes and bazaar at Hopong are certain of attracting a good attendance, and the Hopong Myosa is the outstanding target for critics who disapprove of gambling or the enrichment of the "Privy Purse" by the large sums (anything up to Rs 40,000 a pwe) paid for the gambling contracts at these pwes.
This "gambling money" has been perquisite of the Sawbwa from ancient times and contributed largely to his wealth. For despite popular belief, a Sawbwa is not really rich in the modern sense. Unless he is one of the few big Chiefs, his cash income is small. Unlike absentee landlords he can enjoy his patrimony only when he resides in his state as a country squire surrounded by his fields, his cattle, fuel and food supplies, his retainers and his tributes of perishable goods.
But this in parenthesis. The "gambling money" in some states these days is kept, in part at least, for religious, educational, social and medical expenditures. In others, it may pay for the education of the ruling family. In others again, it may drop, solid as a nugget, into the Sawbwa's pocket which is lined with a stout material resistant to pressure of any kind. Whatever its use the whole matter is one of the thorny touch-me-not problems of the Shan States, and I might have been wise enough too, perhaps, to have made a big detour round subject here.
But I cannot help contributing my bit. As one who enjoys a quarterly fling at a lay-gaung-gyin, who has seen the enjoyment of the peasant crowds in the pwes of which the gambling though but a part is an inseparable part, and who believes in the superiority of this social pattern of a rural population to the teashops and night-clubs of the town gyabos, I wish the critics would clear their minds on the points at issue and refrain from inciting young men to lie across the gambling tables in protest or even to throw hand grenades into the crowds as they have done at this Hopong pwe. Attack the use of the money certainly where it goes to enrich one man indiscriminately: this whether done from jealousy or from social idealism is a commendable act; but leave the gambling alone. The pwes come no often than the State Lottery, and are over after a few days with a clean break unknown to the weekly or daily poker parties. The people go back to their fields, and looking forward to the next pwe, must produce enough to exchange there, or squander there if they like.
In the absence of an efficient form of taxation, this gambling money, if properly controlled and spent, perhaps pooled, could be a boon. Early this year, the UMP in Taunggyi, in need of amenities for the men, were "allowed a pwe" and got Rs 40000 from the gambling contract. If schools and hospitals or the Taunggyi Maternity Home which is always in need of money though and its wards full of poor patients, could be "allowed a night's gambling" at pwes each year, they would do fine.
Hopong valley is a particularly beautiful spot for the motorist or anyone to pause in. Looking down form the west you see the whole panorama of the plain spread before you, as though Nature is out to display every form in which she can show beauty. The afternoon sunlight shines on the emerald of cultivated patches, is absorbed into the deepness of thick groves whose verdure suggest springs and gurgling water, and comes out again over the great spreading trees whose domes it touches into glory. Bamboos bend as sweetly as always over the meandering streamlets while along the lanes "?Nun" trees flutter their white veils with demure coquettishness. Here and there are isolated hills and, some humped over with smooth green, but others with rocky faces and jagged towers hung only at strategic points with climbing creepers; and behind, the mountains are sharp grim peaks, of which the traveling clouds puffing as they go past above, make volcanoes out of them. A breeze comes from right across the broad valley and the bells of Hopong pagoda round whose slender taper and attendant spires the gamblers flock three times a year. All around the view suggest good land for farmers, good camping grounds for traders coming to the pwe.
The road from Hopong is a decent metal surface of 96 miles running south to Loikaw the capital of Karenni State. This was the road which kept the KNDO supplied and able to hold on to Toungoo for so long. Along it are situated the little towns which form centres of sub-states, all of them except Hsatung being included at one time in the state of Nawngwawng 20 miles south of Hopong. First comes Namkhok, a state of about 15 miles by 8, so small that the Royal Order which created it defined its boundaries by using such localized landmarks as rocks, trees, and chaung. But the parent state of Nawngwawng is even smaller today: 28 square miles on which is grown mostly paddy. In these two areas very few Taungthu live, increasing again only at Wanyin the next one south of here, where they are in a proportion of about five to three to the Shans. Probably this is due to the rising of the gradient there. Wanyin has rolling downs bounded on the east by a high range with peaks attaining 8000 feet and Rice. over, garlic, good ranges, cotton and thanatpet are produced in these areas and marketed easily along this motor road.
12 miles south of Wanyin is Hsihseng, capital of Hsatung State and headquarters proper of the Taungthu race. Its boundaries with Wanyin is the only artificial one. East of it is the Nam Pawn, south of it the Nam Tam Hpak takes a bend across to the east to join Nam Pawn, and thus gives a barrier against the raiders of Karenni in past days, while to the west a high range separates it from the Pilu valley. Hsatung has thus had a relatively peaceful history, and together with Taungthu industriousness, the villages here have been able to develop their prosperity. A great deal of the state is rolling downs within woods. There is teak forest, a good output of rice, and cotton.
Sao Khin Kyi, the last Myosa, was one of the prominent figures in the Shan States. A big-made handsome man with a strong temper, and the only Taungthu Chief, he seemed cut out to lead the Taungthus into anything which would have advanced their cause. As if in vindication of their original home also, he found a wife from Tennaserim. She was as rich as she was beautiful, and it was good to see the prosperity of this well-matched pair as they develop with her wealth and the resources of the state into the ownership of a row of shops and cinema hall in Taunggyi, right in the midst of Indian and Chinese, the only indigenous effort in the middle of an Indian and Chinese street front. But an end came with dramatic suddenness. The few bombs which hit the main street of Taunggyi picked out all the Hsatung Myosa lot, wrecked it to the foundations, and soon afterwards in 1945, just when political schemes were in the melting pot and minority leaders were to be called upon to extricate and fashion the particular part belonging to their peoples, the burly Taungthu Chief was stricken with a paralytic stroke which kept him prone for a painful and frustrated year and then killed him. The use made of Karenni and the Loikaw highway further rendered the state unsafe for his family or for any economic efforts. The Hsatung children were sent to Rangoon for education, the heir had perforce to go through his shinbyu ceremony in Moulmein, and the Mahadevi, who strove to keep up a life with the state all the while and is now reviving the timber work, remains in Taunggyi, still beautiful but with eyes which have shed the tears of a lifetime.
The Pilu River which has carved its valley to the west of this area flows out of the Inle Lake as a reedy stream hardly definable from the marsh of the surrounding lake area. Soon the banks begin to take shape, however, and sometime after the Pilu has become a river again when the state of Samkha is reached. Samkha, called Saga in Burmese perhaps from a pagoda of saga wood said to have been built there by Asoka, was once a fairly prosperous paddy growing area. It is shut in by high hills which send down heavy morning mists and make of it an unhealthy place. The highroads of trade now running east and west of it are cut off by the enclosing range and Samkha's only means of communication with anywhere is by slow boat. Thus it has become a deserted town, showing the quickest depletion of population within the last 15 or 20 years; as final sealing of its doom, the rebels have been running in and out of it, burning and scaring away what few settlements remain about it. To sail down the Pilu to Samkha take you a sad journey past a profusion of dilapidated monasteries and zedis standing amidst parched and uncultivated fields.
Yet the family of the Sawbwa is strikingly resurgent against this background of moribund dereliction. Its members are numerous and widespread over the Shan States, with considerable artistic talents. The Sawbwa himself, as if he has absorbed too well the doctrines of annatta and anicca, is a prime mover in religious affairs. Sakoi, next to Samkha in the same valley is equally neglected and unproductive.
Among the ranges to the south and west of these two states is the watershed between Sittang and the Salween systems, and thus we find here in Mongpai State the most farthest south-western limit of Shan settlement. It is surprising indeed how the State continued to exist a Shan power for so long. The capital and its environs are in the valley of the Pilu, but all the rest is a confusion of highland, and among the country and across the borders of the state, is an area of great diversity and a number of "wild tribes". The population of the State itself contains about an equal number of Shans and Taungthus, numbers of Red Karens, White Karens, Yinbaws, Inthas, etc. but forming the great majority are the Padaungs, for this is the Padaung stronghold.
The Padaungs belong to the same family as the Taungthus and are thought by some to be part of the Taungthu migration northwards from Thaton. To the outside world they are known for their long-necked women. The hard-working men who are zealous agriculturists growing irrigated crops such as maize, millet and cotton, and raising cattle and pigs are not very distinguishable from the Shans. The women look oddly attractive: many of them, slim girls with loose smocks, short striped skirts, their famous necklaces of brass-rings added year by year and in their late teens lifting up their faces into a youthful tilt and giving their eyes an amused and quizzical expression.
It was not from this Padaung majority, however, that the Shan power, first set up in the 16th century by the ruler of On Baung Hsipaw when he was invited to become King of Ava, received the greatest harassment. The Karens in the south who had consolidated their strength by the 18th century were the main aggressors, raiding, breaking the water-wheels used for irrigation, drawing down the Burmese armies to fight them. Sometimes the Padaungs came down and joined the fight. It was they, who coming in 1837, chose a candidate for this Sawbwaship, a Shan, who, set up by Padaung support, held his throne through the reigns of Burmese kings and resigned only in 1890 in favour of his son, after the British had come.
But who the Padaungs had appointed the Padaungs could depose, it seemed. Before the British regime could expire, in 1946, this Shan ruling house had again to flee before Padaung opposition and are in exile today, while Mongpai is regarded as part of Karenni. The state was taken over by Dai Bahan, a Padaung leader who, to add to the confusion, had been converted to the Roman Catholic faith; for now with the intrusion of Karens from Burma into Karenni politics, a religious feud was added in these region. The Roman Catholic missionaries, as well as the American Baptist Mission, arrived in Karenni in the 19th century, and as is the habit of Christian missionaries among the hill peoples, their spheres of operations were defined, so that, generally speaking, the Roman Catholic convert majority are Padaungs and the American Baptist Mission convert majority are the Red Karens.
When the politics of Karenni split people into factions, Dai Bahan Mongpai, the leader of Catholic Padaungs, siding with the established Loikaw government, were in opposition to the KNDO sympathisers whose leaders are far more closely connected with the American Baptist Mission as everyone knows. Dai Bahan after fierce tussles, reversals and victories all over these barren hills, was pushed out from Karenni, and arrived in 1948 at the Kalaw Circuit House, a very sick man, a victim of blackwater fever. A handful of followers were with him and they mounted guard round the Circuit House and kept watch over their dying leader. Such faithfulness of followers when a leader has nothing more to offer is the most touching thing, and makes up for the stupidity of men on other occasions when they will no sooner have installed a man in office but will shout him down at the instigation of someone who wants the office.
Mongpai today is still one of the "unsafe" areas, and the road running through it from Loikaw to the Myelat is not to be recommended to travelers.
Against the background of small states found west of Mongnai, either strung along the river valleys or segmented together in the Myelat area, it is not surprising to find the important state of Yawnghwe standing out distinctly. All this western portion of the southern Shan State was, as a matter of fact, divided up between Mongnai and Yawnghwe, the Nam Pawn forming the boundary. A royal Order of 1808 stated:
The limits of Nyaung Shwe State are hereby declared to be, on the east of Pon Chaung (Nam Pawn) and Mone (Mongnai) State; on the south, Mobye (Mongpai) and Toungoo; on the west the Sittang and Paunglaung Rivers, Hlaingdet and Yamethin; on the north, the Mintnge, Thibaw, and Mongmit as shown in this map submitted by the Nyaung Shwe Sawbwa.
Appointment orders of all subordinate ranks are hereby withdrawn, such appointments are now vested in the Nyaung Shwe Sawbwa.
I quote to show how close we have approached to Burma proper in the mention of several of its districts as southern and western boundaries.
Now, the area of the State is about 1400 square miles only, the most conspicuous detachment being Lawsawk to its north, which has an area bigger than that of Yawnghwe today. The present area includes a number of substates under Myosas, such as Tigit, Heho, Naungpalam, etc. It includes also a diversity of natural features of which the most prominent is the Inle Lake in the eastern half of the State, a magnificent expanse of water about 70 square miles in area. To the east of this rises steeply ranges which runs the entire north-south length of the State, and at the northern end of which is situated at 4700 feet above sea-level, Taunggyi, the capital of the Shan State. This range divides Yawnghwe State from the Nam Tam Hpak valley. To the south of the lake is the plain of the Pilu, merging into Samkha and Sakoi, while west of the lake is the undulating low hills and valleys of the Myelat country, rising gradually into high elevations in the south. With no great mass of highland except for the eastern range, Yawnghwe State is the most densely populated in the Shan State if we exclude the little states which have an area consisting largely of their capital towns and environs.
The total population of 126,000 is composed of Inthas, Taungthus, Shans, Taungyos, Danus, Burmans and Danaws. Tanugyos are very similar to the Taungthus, perhaps the difference is that they have more Burmese blood where the Taungthus have more Karen. Of the Danus and Danaws, more when we come to the area in which they predominate. Here in Yawnghwe state, it is the Inthas who form the most outstanding people.
It is generally agreed that these Inthas are of Tavoyan descent. On the exact manner of their transplantation here from far Tenasserim, two accepted accounts are given, one more fanciful than the other. The more historically interesting version states that when the present town of Yawnghwe was built in 1359, two brothers, Nga Taung and Nga Naung came from Tavoy and took service under the Sawbwa. With his permission and help they made a trip to Tavoy and brought back 36 households. These were settled a little north of Yawnghwe, but soon multiplied all over the Lake District.
This spreading of Inthas is not surprising if the forbears were as industrious as their present-day descendants are. Together with their different racial origin from the Shans around them, this industriousness and a great zeal for religious works has produced a life pattern distinct enough to be called Inn culture.
The very language of the Inthas sets the key to this cultural pattern. It is Burmese, but by now incomprehensible to any but themselves. One authority thus traced the history of the confused mixture of influences which has produced the Intha dialect: The Tavoyans are believed to be descendants of an Arakanese colony. During their sojourn in Tenasserim, their dialect, with its Arakanese echoes was affected by Siam influences. Whey they came to Yawnghwe, the eastern Tai ones were further modified by Western Tai, quite different tonally. Thus no Burman who does not know Shan can understand an Intha wholly, while an eastern Shan would fare worse. The Inthas say that during one of the Burmese reigns an order was issued to them to speak Burmese, and not knowing it well enough for all purposes they nevertheless were forced to obey by inventing terms of their own. Today, the Burman can appreciate the directness, even a poetic directness, of certain Intha-composed terms --- unfortunately the choicest examples quoted have bawdy meanings, so my word must be taken for this.
Although here in Taunggyi, the Inthas are known as great producers of vegetables, a good part of the labour of lake life is devoted to rice cultivation. There are no extensive paddy-fields, but every available acre is put under cultivation. Early rice is the main crop and in some villages, a second crop is put down after this early paddy is reaped. In certain villages again, the paddy land is actually submerged during a part of the year. In the summer months when the lake goes low enough, you will see the men laboriously paling out this water --- standing in line alongside a device which flings out the equivalent of a bucketful at each tread of a foot on a pedal, a sight beautiful to watch in its steady rhythm, but actually spelling so much sweat and toil. Such patches are too wet to be ploughed by a buffalo, the spade has to be resorted to, to cut out weeds and then the soil is stirred about until it is fit to receive the seed. Despite all this effort, Yawnghwe state has to import rice from neighbouring Hsihseng to feed its Inthas.
Where the marsh becomes more solid ground, tall lattices of betel vine line the water channels in the villages. These village gardens produce a great variety of vegetables and flowers. Much further back where the first slopes begin, groundnuts, garlic, bananas, and onions are grown; and above these again are the taungyas with their paddy.
The other large product of the lake is of course, fish. Not very good fish, being chiefly nga-khu, nga-hpe, and nga-hpein, full of little bones. But large quantities of it get sold every bazaar day in Taunggyi and other nearby towns. The fastidious eschew Inn fish because of the dearth of cemeteries in the lake area point to where the dead lie. But the Intha make very solid coffins for their dead before submerging them. All matter undergoes metamorphosis anyway. The latrines which overhang vegetable gardens in so many villages send their waste waters seeping through the subsoil to be drawn up in time by Nature's wonderful filtering process into the juicy insides of melons and cucumbers, and the harmless nga-hpein is probably no different from any other fish.
The lack of extensive solid land for cultivation has caused an increased industry in the Intha instead of providing him with an excuse for idleness. In villages which are built wholly on the water, handicrafts are intensively practiced. Here is the second largest silk weaving centre in Burma after Amarapura. Getting raw silk from China, centres in the southern end of the lake, at Nampan, and Impaukhon especially, have been productive since old days. The industry has kept up so well with modern times that the "Bangkok" longyis now produced here are quite indistinguishable from the ones formerly brought from Chiengmai and Korat. The clack of looms from every house in Impaukhon come right across the water all day and every day. Each loom produces one double piece every bazaar day, with 2000 workers operating, this village of bamboo huts handles many thousands of rupees at every bazaar period. Alas, the weaver who sits at the loom all day gets but a few rupees out of the sixty odd that are paid for the piece. Towards the north end of the lake are also villages which produce good quality pinnis or cotton homespuns worn by Shans and Taungthus.
Weaving is of course the work of women, and the chief industry of the lake area and thus leave the men in certain villages all the leisure for playing cards. But male craftsmen in other villages produce large quantities of silver, brass, and lacquer ware, pottery and Shan bags.
With all this industry in the fields during half the year, in the cottages during the other half, the Intha lives frugally, using his savings chiefly for religious expenditures. Quite a lot of his sweat has, however to be spent in rowing himself from point to point. No doubt the leg rowing was evolved to save fatigue --- it is only an alternative form, not the sole one. Rowboats traverse the entire length of the lake, about 12 miles every bazaar day, to take goods either to Yawnghwe or right up to Taunggyi from there. Outboard motors have been bought by a good number of boatmen, but the constantly recurring petrol shortage during disturbances, lack of technical care of the engines, and worst of all, the choking prolific water hyacinths all over, still make rowing the chief propelling power.
Entrance to the lake is through a narrow channel which takes about an hour to traverse. Land and water are hardly distinguishable here; it is a kind of fenland, but a busy, almost jolly, fenland. The haphazard juxtaposition of land and water in the warm and languorous Yawnghwe air appeals to a play instinct of long-forgotten days. The monasteries stretch in a long series of rooms connected by little bridging steps over the water and boys run up and down. The houses grow hedges to fence in their particular bit of water, it seems, in which pool their ducks and buffaloes sport, while cows, pigs, and poultry crowd companionably on the drier patches above. The water lane has no banks, no boundary, it merely connects the houses on the left to the paddy fields on the right, where cranes and transplanters stand knee-deep in mud. On dry perches provided by the gazins, paddy birds more dainty, and beside them little boys, dipping conical baskets in the mud for fish. Flat boat after flat boat maneuver past with pots, melons, rice, firewood, vegetables or a moving householder's goods. This is the bottle-neck of the whole Inn with its dozens of villages and its 60,000 inhabitants. And everywhere the water hyacinths lay their stringing web --- paying a higher price for a boat with a motor, you are forced to turn off the engine and pole the boat, until buffaloes wading across at ease, hold up even such slow motion.
Going thus through the orifice, the lake bursts on one in a sudden vision; with no warning the last obscuring reeds disappear; the open sea is before you, choppy and devoid of any landmarks. The haze so common in Shan valleys blots out the distant scene. Through the binoculars, however, green shores spring up, and folds in purple mountains, and villages roofed with thatch or sheets of dazzling corrugation, with orange-tinged fishing baskets drying in the sun, while ducks and teals in squatting myriads enliven the bays and inlets.
Racing the engine to the full in this expanse brings you in ten minutes time to the mid-lake bungalow. Here it is possible to camp a few nights. There are some chairs, a couple of beds, several rooms and kitchen. The floor boards gape, but the old durwan is expert at fishing things out of the water for you. The water is disconcertingly clear under the lavatories: you can watch the fish making their meal ... another delinquent action of the incorrigible nga-hpein.
Approaching the bungalow a peculiar sight of the hazy horizon is what looks like a series of battleships row upon row, with funnels sticking up it seems. These are little "floating islands", patches of reeds towed along to mid lake and staked in place row by row, to provide seats for the fishermen.
All about the lake these fishing Inthas provide silhouettes of a beautiful rhythm. The standing rower, tall at one end of the flat boat, as he kicks back the leg which is hooked round his oar and thrusts his chest forward with each kick. The fisherman journeying to his perch with his great basket lying in his boat, is bobbed up and down steadily by the lapping waves; the fisherman already at work has his basket down in the water and prods into it with a steady beat; and the drifting boatman standing at another boat's end breasts the wind which blows back his wide hat and baggy Shan trousers with a recurrent flapping and reveals the outlines of his limbs with each flap.
The villages are either completely aquatic like the weaving Impaukhon, or semi-aquatic like Nampan, or altogether dry like Thale-U. Going everywhere by water, the tracks to and around these villages come in time to represent lanes, roads, highways or great squares. At Nampan especially, the great bazaar center of the lake, several broad avenues meet to form a great square or place which forms the parking area for the boats attending the bazaar. It is a mystery, seeing the great collection of empty boats before it, how the owners identify them as readily cinemagoers their cars in a big town. Even the oars have been removed, for carrying the big baskets on, and are thrust into the fencing all around the great bazaar square, a pair behind each seller.
Nampan is also important as a religious centre, for at the village of Namhu near it are kept the sacred images which are carried to Yawnghwe town and all around the lake in a grand procession of boats every Thandingyut in the Hpaungdaw-U festival. The story of these images incorporates the more fanciful of the two accounts of how Inthas came to Yawnghwe.
During the 14th century when magical events had not yet been banished from this part of the world, Prince Padrikhaya of a certain kingdom of India, hearing of the beauty of Shwe Einsi, the Burmese Princess of Pagan, decided to come across and woo her. He obtained a piece of quicksilver which if kept in the mouth enabled one to fly, and thus he made, straight as the crow files for Pagan. Just outside the city, however, he learned from a departing rahan, also in flight, that the princess had just got married. His open-mouthed dismay at this news caused the quicksilver to fall out. The prince's human weight made him fall into a clump of bamboos which killed him outright. But by this time, the Princess being on the point of conceiving a child, his spirit flew right into her womb, and was later born as the child who became King Manisithu.
Meanwhile, the quicksilver had fallen into a thinganet tree in which it was buried and though the growing Manisithu who knew about it caused many searches for it to be made, it was never recovered. Years later, however, the tree into which it fell was cut down and it was reported to the King that the wood possessed the same magical properties as the quicksilver had done. A barge was ordered to be built of it, and in this Manisithu voyaged to the Shan States. But first he went to Tavoy to get some artisans for pagoda building. With these he went up to Mongpai and from there sailed into and all around the lake District, building a pagoda at each place that he came to. When he left the Lake he left behind five images which are the images carried around at Thadingyut, and also the Tavoyan artificers who multiplied and live in the lake till this day.
Indeed the dominant features of any solid piece of land, however, are the big and numerous monasteries. The Inthas, after all their hard work, eat very frugally and give their wealth to religious works. But this philanthropy is extending now to lay schools, usually promoted cooperative effort though set up by the State authority. Yawnghwe, has, along with Hsenwi, the greatest number of state schools in the Shan States, Whether because their great expanse of water has an equalising effect or because they live on the edge of the highroads of commerce with Burma Proper, the Inthas also show a more democratic outlook and a more homogenous economic development throughout the State than anywhere else in the Shan States.
The lake area of Yawnghwe is so fascinating that one tends to forget that there is a large part of the State outside of it. There is Tigit where a Soil Conservation Demonstration Centre has been set up; there is Taungni seven miles from the main road to Taunggyi where a big bazaar is held and where some large planting of wheat is just being started: there is Nawngpalam to the northwest where Mr. Hackett of the American Baptist Mission has set up a farming centre with school and dispensary and where Taungthus form the majority population: there are Kyaukhtat and Bawsine where mining of lead is being done, and although with only simple implements so far has already enriched the mine owners before communications by rail were interrupted. There are other areas too, but chief of them is Heho, the air terminal, and before that as it is now, an important cross-roads in the Myelat.
Taunggyi, the capital of the Shan State is geographically in Yawnghwe State. It was built in 1896 as a British hill-station to replace Fort Stedman (Maingthauk down in the lake) which was too hot. 1500 feet above Yawnghwe valley, the greatest asset of the town is the beauty of its site. There is a dramatic quality about the way the Taung Gyi or Big Mountain, the Crag it has come to be called, dominate the town: rearing its head exactly like a lion, with its paws stretched out at the southern end, and its long body extended in a succession of spurs which open out at the northeastern end into rolling downs for villages, guarding the hills into the Shan country proper from the ledge on which the town is built.
As an administrative centre for the Shans, Taunggyi has just happened. It is no doubt near the Thazi-Mekitila railway line, but this as we have seen is the very edge of the Shan country, and State representatives have to make long journeys to attend conferences there. Now and again more central places, such as Mongkung and Loilem have been proposed as capital, but with not much conviction. Meanwhile, Taunggyi progresses by leaps and bounds.
As a resident of Taunggyi who would choose no other place in preference to it, I should not embark on the beauties both of Nature and of human life which compose it, for fear of filling too many columns. Instead I will remark that the aspect which strikes a stranger most in the main Road of this Shan capital is the great Indian population. Lashio is more Chinese, but the Chinese here, though they have just built an impressive community school, cannot compete with the Indians. The streets appear to be full of black beards and turbans; then again there must be many many Muslims because there are four mosques; then again there are all the rich Hindus surely, for our houses overflow with gifts of delicious sweets at Diwali time. Perhaps that is why the ashes of Gandhi were carried here and across the Shan hills to the Salween, the great Tai River, which at first sight appears to have very little connection with India, except its rising in those everlasting Himalayan mountains in whose awesome depths and heights the supranatural world is imagined by us and all Indians alike. For whatever reason the ashes came, they do us an honour. His voice, so true to those who could hear, was regarded by a great part of the western world as that of an unpractical, almost cranky sophist and "fakir". Yet where have the "practical" realists so experienced in world statesmanship landed us now? On the battlefields where the big nations are going to fight their battles with each other.
The main interest of Yawnghwe town are in its two old pagodas: the Yadana Man Aung said to have been built by Dhamma Thawka Min and the Bawrithat just outside the town, said to have been built by King Anawrahta. The Haw is the only solidly built Haw besides Kengtung's left standing in the Shan States today, and Kengtung's is no interpretation of the past. Yawnghwe Haw is modeled on a rectangular pattern from Mandalay: the long main body in which are audience halls and throne-room, and four wings for separate living quarters, to house if desired, the queens of the north, south, east, and west.
Visitors should not miss a sight of it. The great space of the throne rooms with their highly polished floors, raised dais, lofty pillars, are perhaps the only example in Burma today which can hint at the splendours which have fallen into dust and ashes. The unfinished ramparts which suggest castle ruins as you drive in are said to be left thus owing to the belief that the completion of a Haw is the completion of the dynasty. Actually, the Sawbwa who is at present the President of the Union, can safely finish his Haw. His two adult sons are, in the opinion of this writer, intellectually the fairest flowering among the Saos or even of all the Shans of today; and he has five or six more in the Presidential House to follow. Their mother comes from Hsenwi in the far north, bringing from those northern mountains all the animation, shall I say even the irrepressibility of Tai women. The wife of the heir also comes from that State.
The little States in the extreme southwest corner of the Shan country are, if one likes method, a fitting subject for this last chapter of the series, for the territory they comprise is called "Myelat", suggestive of a returning to Burmese territory whichever way you interpret the term.
No one is certain as to the exact meaning which this name was first intended to express. The most correct etymologically would no doubt be "empty" in the sense of "uninhabited." But history contradicts this. May be a no man's land between Burmese and Shan territory was denoted; or may be an altogether different "lat" meaning middle, the middle country between Shan hill and Burman plain was intended?
The term, as a unit of administration anyway, existed from the time of the Burmese Kings. At first the states in this region, like the rest of the southern Shan States, came under the authority of the Sitkegyi at Mongnai. This authority, being chiefly concerned with the collection of revenue as tribute the Burmese King, has left behind an echo to this day. The chiefs in this area who were placed one grade lower than Myosas were styled Ngwekhunhmus, or Chiefs of Silver Revenue, as contrasted to certain Shwehums, the chiefs paying golden revenue, on the west bank of the Irrawaddy.
The silver revenue from the little states of the area was sent to the King through the representative at Mongnai till the time of King Mindon. Then one of the royal uncles came to attend a durbar at Mongnai and to discuss the question of revenue at some length. He discovered that the politically insignificant states of these area could between them total a considerable amount. On return to Amarapura, therefore, he advised the King to install a special representative at Myelat, to make sure of efficient collection, suggesting that the amount obtained would easily make up for the expenses of a new post.
Thus a definite administrative term, the Myelat, was created, and a Myelat Wun appointed and stationed in the Lake area, for the jurisdiction marked out stretched as far east as Hsatung and Hopong. This authority was independent of Mongnai and was directly responsible to the Hlutdaw at the Burmese capital. It did not interfere greatly with the rule of the chiefs, confining its duties to revenue collection and the settling of more important criminal cases.
To interpret Myelat as the middling country, though least correct etymologically, would be the most apt from a geographical point of view. The terrain is halfway between the hilly eastern Shan country and the plains of Burma proper. Apart from the hills bordering Karenni on the southern and the actual climb from the Thazi plain, the whole territory is one of gentle undulations and of roads with gentle gradients.
It is in fact the ideal motoring country for visitors. Though the central and northern states offer more real beauty, the tiresome 60 miles of excessively winding road to Loilem lie between them and an approach from the southern end. Here in the Myelat, a diversity of scenery opens out to you immediately after ascent from Thazi, in the pine groves of Kalaw, the 44-mile succession of rounded spur and hollowed valley to Taunggyi which homesick Englishmen describe as a bit of Surrey, the rural lanes branching off to less well-known western corners, the drive through a plain with occasional lotus pools to the secluded valley in which Lawksawk town is situated, the lake at Pindaya backed steeply by mountains and caves, or the open plateau of Tigit and Pinlaung which you ascend imperceptibly but which offers a racing road in the invigorating air of 4000 feet above sea-level. This diversity of scene is traversed between towns near enough to provide stops for lunch and tea and night camping.
One of charms of Nature in the Myelat is the way she reveals her soft contours. All the gentle slopes are almost bare of trees. But it is this very distinctive feature of the landscape which gives the soil experts such cause for worry. We hear a great deal nowadays about he impoverishment and loss of soil all over the earth by exhaustive and reckless cultivation; in Burma, the Myelat is the prime example pointed out by the soil conservationists. Indeed the zeal of the Shan State Soil Conservation Officer, U Ah We Nyein, is so great that he had the Premier's eyes pop alarmingly, when a born orator, he described and demonstrated the erosion that was going on and that would very likely make this area an uninhabited one, a true Myelat, in 60 year's time.
But let me quote from my own description of a past journey made on this very stretch, both as a guide to Myelat scenery as well as a lesson in how the present-day soil conservationist reads the beauties of landscape.
Five miles from Aungban we passed a hillock marked Soil Conservation Centre, ridged into contour furrows and planted with trees at the top. All around were the potato fields of peasants, little ant-heaps of red mud round each cluster of plants, and an occasional figure in loose black smock at work. We were racing fast. The road was of good metal, the country so pleasant and rolling. The gentle slopes around us were bared to show lovely curves and roundedness, and the shadows in each hollow. The light from the sky across which clouds with their "goings-on" made now here, now there, coquetted with both slope and hollow; now kissing the brow of the hill, now playing of the bosom of the plain. Great trees so few as to show their girth stood here and there, their spreading graciousness smiling indulgence. Ditches with exposed red earth made bright colour on the new-washed green, accentuated the faint delineations which seemed to cross the surface of the land everywhere. And under the shade of the great trees, bunched cacti, the agave, sprouted, spreading out like big lotuses arranged by Nature to suit the scale of her landscape gardening.
Then coming over the last spur looking down on the Heho plain we saw a sea of green, shimmering and fair with youngness of the green, without tree or bush to break the surface, but in its centre a white pagoda, small, looking for all the world like a sail on the green sea. Entranced it held us in the still air, as it stood there "without a breath of motion, as idle as a painted ship, upon a painted ocean."
Alas, beneath the fair face was a sinister story, which shows how we thoughtless admirers of scenery are misled. To our soil conserving guide in the back seat all the marks of beauty were but stages in a tale of horror. Those great trees, he said, show by their girth that within living memory this region was all forest, thick like the virgin fortes we saw on the slopes up to Kalaw. The faint delineations and bare slopes were all that remained of that now, after patch after patch for easy crops, easy come and easy go. The land was so plentiful and the water so conveniently flowing from the top down through the furrows, eroding the soil. All those ditches of brave red were, after all the gullies which cut like ever-deepening gashes into the richness of soil (and stab deep into the heart of every soil conservationist); they were the ends of slopes into which the reckless peasants drained their fields. And even that fair lustrous plain, though free from slopes of running water, had a dreadful fate awaiting it, for stone and gravel washed down from the eroded slopes would come and bury all its fertile top soil. Burial erosion it would be.
All the land would then be useless for men's crops and even the grasses which could grow would not nourish cattle, man's first and last hope. For as a soil conservation pamphlet from elsewhere states, civilization lies in a few inches of top soil ... So, in 60 years' time such things continuing, all life will have fled from the Myelat as from a plagued land. Only the agave and the soil conservation centre were symbols of a future. The agave which you often see planted in rows across is being used as a means of conserving soil.
However, discounting levity, the Soil Conservation Centre is trying to instruct the peasants, demonstrating contour planting, green manuring of the soil, planting of trees to conserve water supply, selection of grasses which will cling to the earth as stickily as a certain type of love (after which they are therefore called), as well as producing the stock farm crops of the region by a soil conserving type of agriculture, marking out plots where the more cooperative peasants grow crops under instruction from the Centre. Besides the main centre at Hsamongkham on the 33rd mile between Kalaw and Taunggyi, are centres at Tigit, Pinlaung, Poila, Pindaya, Kyone, and Pinhmi.
These centres are under the immediate care of the Soil Conservation Officer who works with indefatigable enthusiasm and is, as I have said, a great orator (for oratory is needed to make people's hair stand on end at the thought of the dusty and wrinkled desert which will soon succeed the beautiful Myelat if soil is not conserved), and the whole programme which aims to follow up the word all over the Shan State in a Five Year Plan is overseen by the State's Principal Forest Officer, U Kyi, who has recently added to his original brilliant approach and his forestry knowledge of long standing, a survey, coastwide as they say, of Soil Conservation work in the USA.
Wasteful methods notwithstanding the Myelat is the greatest farm crop area in the Shan States, and the cultivators working along their own lines are still in the heyday of productivity. This is the area which has identified the potato with the Shan, almost as completely as with the Irishman. Grown in little mounds in almost every garden and in more extensive fields throughout the states of Hsamongkham, Heho, Maw, Yengan, Poila, Pindaya, Tigit, and Lonpo, that is to say, almost every state of the Myelat, enough potatoes are produced to have exported in 1939-1940, over Rs 30 lakhs worth. But this is also the cabbage patch of Burma. I have seen some prize heads of 20 inch diameter from Lawksawk, and equally impressive are the trucks loading up about October and November round Pindaya and Poila with tight firm heads, 2000 to a truck. When Pindaya plays Aungban at foot ball the fans do not shout the names of the states. Their parochial fervour runs along more horticultural furrows. "Potato!" and "Cabbage!" are the stirring calls which arouse maximum competitive efforts.
The other main crops of the Myelat are also capable of being raised in quantity. Groundnut is already grown on an extensive scale, and wheat, though it has just started as a large area crop, has caught on in almost every private garden as a winter crop after the groundnut or maize has been cleared.
It might be thought that the inhabitants of this border country would be a Shan-Burmese mixture shading off into a stronger Burmese strain as the western boundary is approached. But not so; the small Shan population found in this area remains distinctly Shan. Crowding on them however, are the Taungthus, spilling over westwards from the stream which pushed north along the Tam Hpak valley to the east; Taungyos, who to the observer can pass for a kind of Taungthus except that a red smock is substituted for the black and that the speech is more Burmese where the Taungthu is more Karen in character; Zayeins and other types of Karens in the regions of Loilong immediately next to Karenni, Inthas from the Lake area; a greater number of Indians, Chinese and Burmans than in most other parts of the Shan State as is to be expected; and then peculiar to the Shan-Burmese border areas, the Danus. The Danus are found also in the Ruby Mines District, Hsum Hsai district of Hsipaw and around Maymyo, but most particularly they are associated with this Myelat region, especially Yengan, Maw, and Lawksawk.
The origin of the name Danu is obscure, and some sources record that they were not found in the Myelat before the Taungthus came, thus linking them with Karens and Taungthus; otherwise they might be classed as undeniably Burmese in origin, with certain changes in speech and customs consequent on living in an undeveloped and hilly border region. Sir George Scott, that wonderful British gentleman who recorded the local lore of every district in which he served, has translated the account discovered in a Burmese narrator from Meiktila. According to this account the first that was ever heard of Danus was when King Anawrahta went up towards the Shan States and "met with a wild and jungly man of a strange race between Burma and the Shan States."
"Now these Danus," says the narrator, "drank water from the valleys, so they spoke very slowly ... When Danu bachelors courted a maid they took with them a betel-box to the girl's house and each young man placed his betel-box in from of the maid, and when the lassie took a betel-leaf, the lad from whose betel-box she took the leaf knew that she loved him and he took up his betel-box and went home ... The religion of the danus was like the Burmese but they were very wild ... They used to sleep around the fire and they had no other blanket but that, not even in their houses. And as they had no pillows they used to sleep with their heads on each other's bodies like kittens or puppy dogs."
To confuse matters further there are also Danaws in the Myelat, something like the Danus but they wear Taungthu dress. But short of writing an anthropological treatise here, one must draw the line somewhere about delving into minutely differing racial origins. Otherwise I might have described the Ying Hsek and Ying Lam, the Mepu, Zayeins and Bres, the Liu and the Lao, the Lisaws, the red and Black Lahus, the Mungs, the Yaos, the Da-yes, etc. in this series of articles, in addition to the Khuns, Shans, Palaungs, Was, Padaungs, Kaws, Lahus, Taungthus, Inthas, and Danus as I have already done. To most people it will appear that the Myelat inhabitants are a border mixture looking more Burmese than they do Shan, and speaking Burmese with a very peculiar accent, and that it is unreasonable to laugh at them because they can speak neither Shan nor Burmese correctly.
The States occupied by this diverse population, together with their areas in square miles are as follows: the state of Hsamongkham (449) commands the whole area as its capital town of Aungban is at a junction of roads to all other states. Radiating from here like Kyone (24) immediately north; Poila (178), Pindaya (86) and Lawksawk(2362) curving northeastwards; while Yengan (359) and Maw or Baw (capital Ye-U 741) curve northwestwards; Pinhmi (3) a few miles south; Yawnghwe sub-state of Heho adjoining west; and Yawnghwe sub-state of Tigit and the large state of Loilong (1096), capital Pinlaung) curving southwestwards.
The state of Hsamongkham, whose small-sized ruler Sao Htun Aye is prominent in Shan councils and is now acting as Resident of the Southern Shan States, also contains within it the town of Kalaw, a notified area British station out of all proportion to the rest of Myelat towns in the extent of its built-up area, but for all intents and purposes this built-up area is like a disused appendix to the main highway of commerce which runs past it from the Myelat down to Thazi.
Kalaw is too well-known as a summer resort and the sancturary of retired British and Eurasians of former days to need description. It has a certain beauty in the glades and nooks afforded by its innumerable hillocks and pine-groves, in its fertile soil which raises far more beautiful gardens than is possible in neighbouring Taunggyi, and in the air of quiet among high mountains. It is a beauty which must appeal particulary to old people, a world of cosy green lawn bounded by the bend of a spur and the crowning of a pine grove.
But the eyes of youth require longer views, more boundless horizons, less enfolding. Give me, instead, the open aspect of Taunggyi where all human inhabitants are crowded together in the limited area of the level platform edge, but have in front of them the sheer drop into the Yawnghwe valley, and across its gulf, the prospect of seven ranges of hills on a clear day, young green and dark green, blue and purple and pink, dissolving into the radiant light at the farthest. Now especially, Kalaw is dead, the charming houses which people won't buy are becoming dilapidated, and the only sign of a living spirit is that the Hotel Kalaw, previously the sanctum of a Gymkhana type of European social life, now offers tooth-picks on the table in recognition of a new clientele.
This hotel deserves to see better times before long because of its gallant perseverance through seasons when but one guest or two frequented it. Kalaw though offering little life within its own area, is an ideal point for excursions into the Myelat country. Aungban town itself would be more central but it has no bungalow for visitors. The motor route offering a "round trip" is by a fortunate coincidence the most interesting and worthy of visit --- from Kalaw through Aungban, with Poila on the right to Pindaya, thence to Lawksawk, a total of 64 miles; from there a curve round in the other direction through Lawksawk valley to meet the Taunggyi-Kalaw road, and passing through Heho, back to Aungban. Two other trips, one to Tigit and Pinlaung, and another branching off the Pindaya road to Yengan and Ye-U suffice to cover the Myelat. The trip to Yengan and Ye-U in keeping with the undevelped aspect of its area, is the dullest but a road under construction from Ye-U straight down to Kyaukse on the Rangoon-Mandalay will provided a short cut through its state from Mandalay to the whole Southern Shan States.
[ One page missing here, describing the approach to the Pindaya caves]
... in squares of grass, and in its right corner stands a small garden patch --- a veil surrounded by bushes of gardenia, magnolia, croton, oleander, hibiscus, and rose, restrained as to number but carefully tended so as to produce each a perfect blooming. Within the rectangular monastery building of wood, however, a profusion of ornament in carving, gilding and glass mosaic, reflect the dim religious light. Only at the end window there is bright light, and there the abbot sits with his back to the world. The high wall against the steep hillside prevents sight or sound arising from the road, only the drop down to the plain is in front, a mass of impenetrable green.
This approach up the hill past images fallen from their niches in the rocks, decapitated and detruncated, brings you first to the two lower caves, in the second of which is a huge and gilded image, nothing very out of the ordinary. The last bit of ascent is steep, going up sheer to a small built-up platform which juts out, swept by strong winds. A dog barks at your arrival; the Chinese monk who lives there alone emerges from his cell and calls to his boy to open the door of the cave. These are now the real caves of our imagining, leading into the subterranean worlds and revealing their content to an Open Sesame.
When the boy throws open the gates you see at first only the altar and images, perhaps a dozen, on which the daylight strikes, but he gets a flaming pine torch and leads you in. You see then that the cave is full, but incredibly full of images, fashioned through many centuries, of stone, brass, wood and stucco, recumbent, seated and standing, brought up the long and tedious climb and crammed into every available space, right up to the cavernous heights and down labyrintine passages, down in more caves till even the devout, following the boy with his flaming torch, is forced to brush irreverently against the knees, heads, and shoulders of images and more images pressed and jostled against each other. At last the galaxy thins into dripping caves with stalagmites. The peoples say these lead on to Popa Hill, to Pagan, and no one may dispute them.
Legend connects the caves with the lake below. Seven princesses bathing in the lake took refuge here in a storm and were imprisoned by an enormous spider who blocked the entrance. This spider had once been shot by a prince of Yawnghwe who later married the youngest princess, and he thus became the mortal enemy of the couple through a series of reincarnations. Metamorphosing from gryphon to spider, to carnivorous giant and sorcerer hermit, he continued to separate the pain; no magical bows and arrows, no help given by other beings availed against him; till one day the Princess pushing him into the Zawgyi River and finding in dismay that the water there drained away at his incantations, lifted her longyi and covered his head with it. This laid him out at once. Hurrahs for being the weaker sex, the lower sex, which can by a fling of the contaminating, defiling longyi, dispel all manhood, all mental powers of those vaunted superior beings, the Men!
From Pindaya northwards orange groves line the road to Lawksawk, of which state oranges are indeed the most famous crop. This approach to Lawksawk town is the more commonly used one, but entrance from the other side explains at once the former importance of this now quiet valley as a region of plenty marvelously defended by nature. In the level road there arises suddenly a series of bends, of hillocks and jungle cover, as an outer perimeter of defense. Rounding the last bend the beautiful and fertile rice plain opens out, and across this plain the white towers of the Lawksawk pagodas, giving the illusion that a great city still exists, rise from a walled and wooded prominence which served as the inner defense of the capital town. For the town, built on a prominence has a natural moat. A stream goes meandering round the hillock in an extraordinarily roundabout fashion, and a few diversions sufficed to form a perfect encirclement from which brick walls were built up.
The old Sawbwa of Lawksawk who died in 1943 was of a militant character and stature in keeping with those fortifications. He was really from Tam Hpak, a sub-state which became merged in Hsatung State, and having made himself useful to the British in sorties made during those unsettled years of pacification, he was given Lawksawk State by the recommendation of Sir George Scott when its Sawbwa, a prominent figure in both the Mongnai and Limbin Confederacies, refused to make submission but returned once more to Kengtung in the hope of raising another standard for a Burmese prince, after which he died far away in the mountains bordering China.
Having been given the Sawbwaship of Lawksawk, Sao Khunsuik made short shrift of raiders and attackers. The Padaungs who made forays as far as Lawksawk in those troublous days had their heads cut off and stuck on these walls not so very long ago. But it is said that his fiery temper drove away many settlers also; Lawksawk valley in which an old saying allowed no perch for a visiting crow, is now deserted; but mainly because the high road of commerce running through the Myelat is now well away from it. The State as a whole is very productive, in timber, rice, oranges, groundnut, surface ores, but till a road is built from it to Hsipaw which adjoins it on the north (how tricky these modern car-roads, or rather the roads laid by the British to serve administrative units are). Having driven 262 miles into the southern States through Loilem and Taunggyi in order to get from Hsipaw to Lawksawk, one never realises except by a map or by an extraordinary feeling for compass points that one has traveled back again almost to Hsipaw --- a cart could do it in about 100 miles); till such a road is built, Lawksawk continues to be left severely alone, a smiling valley which waits for the traveler to go out of his way to notice it. A reflection in fact, of its Chief, the son of the militant old stalwart no doubt, but injured from his falling off an elephant in childhood so they say, into losing both stature and pugnaciousness.
Lawksawk was formerly known as Rathawadi. The present name, a corruption of Burmese Yatsauk (built standing), is said to have been given when Narapathi Sithu Min, coming to build a pagoda, sowed the seeds of a jack-fruit with his toes while remaining erect and standing before the pagoda.
The pagodas are still impressive. Especially the one built like a tower and said to date back to the Pagan period. Near it are more common-type zedis, among them one built by the Sawbwa who fled into the Kengtung mountains, another fierce old man. It is said that he caused to be built into it, as guardian spirit, a little girl dressed in all her finery. Sao Hom, who in the fragrance of her name and the innocence of her quiet beauty, infuses into the relationship of niece, a particularly sweet quality, first showed me round these pagodas and said that in her childhood she could still hear the jingle of the little girl's bangles every evening as she cried to be let out. Dear Sao Hom, princess of this enchanted solitude, and dreaming in your retreat, alone among the silver oaks and the jasmine bushes, only waking up to a flurry of housekeeping when a stray visitor makes rude interruption; was it not just the tinkle of the pagoda bells that you heard? Spare your tender heart, the little girl must have died long since, and you yourself have been awakened now finally to a life of mundane matters, of a young wife's busy-ness with write-ups in The Nation and trips to Rangoon ...
The trip southwest from Aungban to Tigit and Pinlaung takes you through a different country. The air is cold and bracing, you race along a stretch of plateau at 4000 feet above sea-level, till a stream coming down and crossing the plain shows you Tigit, all laid out in the palm of your hand as it were, and then 20 miles further on, descending into the narrowest valley, Pinlaung, the capital of Loilong state. From here the road continues to join Loikaw in Karenni 80 miles southward, but this is not to be traversed owing to insurgent fear. In these regions the small bazaars show great numbers of Taungthus and Karen types coming down with sweet limes, tobacco, danyinthi, and fascinating basketware of all designs, but at least of equal interest to the visitor will be the tiny brick bungalows, identical at both places, providing cosy shelter equally in the open prairie and in the narrow valley --- destinations for second or third honeymooning ...
All Rights Reserved. No part of this article may be reproduced or copied without prior written permission of Sao Khai Mong. | http://www.ibiblio.org/obl/docs/MiMiKhaing-Shan.html | CC-MAIN-2015-40 | refinedweb | 39,900 | 60.89 |
SI7021 I2C pin setup (SOLVED)
- nespressif last edited by
Hello everyone, I have tested with an HTU21d sensor that is very similar to the SI7021 and with the SI7021 class I also get the "I2C bus error". However with the code in the main.py, it works perfectly, and without external resistances, I do not understand why I get the error with the class, if everything seems to be fine.
I use this one:
from machine import I2C import time i2c = I2C(0, I2C.MASTER) print(i2c.scan()) #I get [64] is 0x40 i2c.writeto(0x40, 0xf3) #read temp no hold time.sleep_ms(25) temp = i2c.readfrom(0x40, 3) temp2 = temp[0] << 8 temp2 = temp2 | temp[1] print((175.72 * temp2 / 65536) - 46.85)
I hope it helps you, Regards
@eric73 said in SI7021 I2C pin setup:
Single transistor level shifter ?
Yes. there is a standard circuit doing this with single MosFET transistor, used by all cheap level shifter. Principle below. LV is low voltage, HV is high voltage, Lx and Hx are the low & high voltage logic. And you see the pull-up resistors on both sides:
P.S.: You could make a picture of the back side of the sensor, just to clarify @Eric73 's question.
@tttadam Single transistor level shifter ? A single transistor is an inverter gate, your SDA and SCL signal will be inverted. Please note that i2c is an opendrain bus with pull up. Your SI7021 can be powered by +5V (if its identical to the one showed by robert-hh) but have you checked is your board have 5V-3.3V regulator and have you checked what is SDA and SCL voltage level when you just power SI7021? In SI7021 datasheet absolute maximum rating for SDA and SCL is 3.3V, i have doubts that a SI7021 board have +5V pull-up on SDA and SCL....without power any of the two board, please check your wire continuity with multimeter if you can.
@robert-hh Well I just ran the code again(from 5V without resistors), but I got OS error for every baud rate from 1 to 10000. So I think something most be wrong with this sensor.
@tttadam I searched a little bit for a module that looks like yours. I found one, and in the backside pictures I see some resistors, which most likely are 10k pull-up resistors, and a three terminal device, which is according to the print-out a LM6206N3 3.3V voltage regulator. The pull-up resistors seem to be connected to 5V. Being 10k, that should not hurt the pycom device, and you do not need external pull-up resistors. And the 5V were OK for your device.
Edit: I see also a dual level shifter, which is intended to connect a 5V side at the micro to the 3.3 V side of the sensor. It is a single FET transistor level shifter.
@robert-hh Okay, I will get bigger resistors, and replace the sensor.
Thank you for the help.
@tttadam 1K is too low. The usual recommendation is 4.7 k. But that should not change the figure. The question is, whether i2c.scan() returns [64] also in the context of your main code.
If yes, then the port & wires & I2C protocol are OK, and we have to look at the SI7021 module.
@eric73 @tttadam So is it this code:
Form the first glance, it looks Ok and compatible to Pycom's MicroPython.
@eric73 I am using a 1k resistor both on SDA and SCL.
The program takes much more time to run because of the i2c.scan().... But I will write ehen I have the result.
@robert-hh link you looking for is in tilte not ?
@ttadam Have you add pysical pull up resistor on SDA and SCL to 3.3V (4.7K or 1K value) ? Even if you set software pull up to the pin definitions, when you call i2c.init i dont know if pin your specify are not setup as pure opendrain by i2c library, so perhaps a test can with pull up can be done ?
@tttadam That#s strange, especially since i2c.scan() works, which also needs I2c communication. You could try to add an i2c.scan in the test after the i2c.init, just to confirm that it works. And yes, you do not need every baud rate. You can go back to a value like 100000.
I faintly recall a link to the SI7021 driver you are using, but cannot find it any more.
Okay I modified the code as you recomended it.
But I got the same error on every baudrate.
Here is the csv, but nothing intresting in it:
import pycom from machine import I2C, Pin from SI7021 import SI7021 import time expledpin = Pin('G16', mode=Pin.OUT) buttonpin = Pin('G17', mode= Pin.IN, pull=Pin.PULL_UP) i2c = I2C(0, pins=("P9","P10")) start = True while start: if buttonpin() == 0: start = False with open("/sd/data.csv", 'a')as ds: expledpin.value(1) for baud in range(1, 115200): pycom.rgbled(0x0000FF) i2c.init(I2C.MASTER, baudrate=baud) sensor = SI7021(i2c=i2c) try: print(sensor.readTemp()) ds.write("\n\r;;"+str(sensor.readTemp())) pycom.rgbled(0x00FF00) except OSError as er: pycom.rgbled(0xFF0000) expledpin.value(0) ds.write("\n\r"+str(repr(er))+";"+str(baud)+";") expledpin.value(1) time.sleep(0.001) pycom.rgbled(0x000000) ds.close()
@tttadam You do not have to re-create the i2c object. You can call i2c.init() to change the parameters. And I still do not know why you create the Pin objects separately. You just have to name them when creating the I2C object:
bus = I2C(0, I2C.MASTER, baudrate=baud, pins=("P9","P10"))
The init method of i2c will initialize the Pin objects.
I created a small code so it looped through all tha baudrates. Maybe a little overkill.
Off topic, but the code sometimes freezed for a half a minute or so. It was because I was created to much i2c object, and a garbage collector kicked in? Can I prevent that behavior?
Also If you can give any feedback for my code I would appreciate it very much.
Anyway this code was unsuccessful. I was unable to find a the correct baud rate, I got the same I2C bus error always.
import pycom from machine import I2C, Pin from SI7021 import SI7021 import time pin9 = Pin("P9",mode= Pin.OPEN_DRAIN, pull= Pin.PULL_UP) pin10 = Pin("P10",mode= Pin.OPEN_DRAIN, pull= Pin.PULL_UP) expledpin = Pin('G16', mode=Pin.OUT) start = True buttonpin = Pin('G17', mode= Pin.IN, pull=Pin.PULL_UP) while start: if buttonpin() == 0: start = False with open("/sd/data.csv", 'a')as ds: expledpin.value(1) for baud in range(1, 115200): pycom.rgbled(0x0000FF) bus = I2C(0, I2C.MASTER, baudrate=baud, pins=(pin9,pin10)) # bus = I2C(0, I2C.MASTER, baudrate=100000, pins=("P8","P7")) sensor = SI7021(i2c=bus) try: print(sensor.readTemp()) ds.write("\n"+str(sensor.readTemp())) pycom.rgbled(0x00FF00) except OSError as er: pycom.rgbled(0xFF0000) expledpin.value(0) ds.write(str(repr(er))+str(baud)) expledpin.value(1) time.sleep(0.001) pycom.rgbled(0x000000) ds.close()
@tttadam So it means that at least the i2c protocol is now working. 64 or 0x40 ist the proper i2c address of the device. Try to reduce the baud rate.
@robert-hh Yes.
for i2c.scan() i get back this: [64], but I2C bus error for print(sensor.readTemp())
@eric73 Well, you are right. I gave the sensor 5v instead of 3.3. I think I killed it.. well least a learned something. I also tried with 10k resistor but still getting I2C bus error...
Thanks for the help anyway.
@tttadam Definitely Vcc should be 3.3 V. And I cannot tell whether pull-up resistors are present on the board. Adding some with a value of about 4.7 - 10 kOhm should not hurt.
@tttadam Strange things, i have a look to your wire connexion, i hope my eyes are wrong but it seem you power your sensor with VIN (approx 5V), but your device SI7021 have +3.6V maximum power supply voltage so +5V can destroy your device.
If i take time to watch your wire it because typically on a scan i2c your device seem to ACK all address starting by 0x40 (64) and this can be happen in case of bad gnd connexion, please check your power supply +3.3V and GND for your SI7021.
If you have an oscilloscope for probin SDA and SCL this will be very helpfull. | https://forum.pycom.io/topic/3850/si7021-i2c-pin-setup-solved/21?lang=en-US | CC-MAIN-2020-29 | refinedweb | 1,431 | 77.13 |
Issues
ZF2-141: AJAX-ready sessions
Description
Due to asynchronous nature of AJAX requests, it's probable for two requests of same client race each other for a session data. ZendFramework has already included the prefect implementation for JSON-RPC and XML-RPC servers. Any RPC server is useless without exclusive access to session data. I believe the following functionalities is what is missing right now in Zend_Session and/or Zend/Session classes:
- Exclusive inter-request access to each session namespace.
- Specifying the access type prior loading a namespace. Access types include: read-only, read & write. And for namespaces loaded as read-only, changing any part of session should throw an exception. I believe that it's obvious that read-only accesses share their locks while read & write accesses hold an exclusive one.
Suggestions for implementation: One can save each namespace in different file and lock it using flock when sessions are to be saved as files. As for the sessions in database, the database engine should lock the namespace record which MySQL supports.
Please let me know if I can be of any help. I'll be glad to know if my proposal is feasible or not.
Regards, Mehran Ziadloo
Posted by Ralph Schindler (ralph) on 2012-10-08T20:15:34.000+0000
This issue has been closed on Jira and moved to GitHub for issue tracking. To continue following the resolution of this issues, please visit: | http://framework.zend.com/issues/browse/ZF2-141 | CC-MAIN-2015-06 | refinedweb | 238 | 56.66 |
Red Hat Bugzilla – Bug 188378
Review Request: perl-Test-NoWarnings
Last modified: 2011-02-03 12:57:58 EST
Spec Name or Url:
SRPM Name or Url:.
Builds fine in mock (development branch, with dependencies added) and rpmlint is
silent.
Issues:
For grammar's sake, s/modules/module/ in the description.
Review:
* package meets naming and packaging guidelines.
* specfile is properly named, is cleanly written, uses macros consistently and
conforms to the Perl template.
* license field matches the actual license.
* license is open source-compatible. Text of license is included in the package.
* source files match upstream:
702143eab77ffc335a08beccac47dca4 Test-NoWarnings-0.082.tar.gz
702143eab77ffc335a08beccac47dca4 Test-NoWarnings-0.082.tar.gz-srpm
* package builds in mock.
* BuildRequires are proper.
* final provides and requires are sane.
* no shared libraries are present.
* package is not relocatable.
* owns the directories it creates.
*.
* The package owns %{perl_vendorlib}/Test, which is also owned by other modules
in the Test:: namespace. No dependency owns this directory, however, so there's
no alternative.
APPROVED.
Typo fixed in CVS.
Imported in CVS and builds requested.
perl-Test-NoWarnings-0.083-1.el4 has been submitted as an update for Fedora EPEL 4.
perl-Test-NoWarnings-0.083-1.el4 has been pushed to the Fedora EPEL 4 stable repository. If problems still persist, please make note of it in this bug report. | https://bugzilla.redhat.com/show_bug.cgi?id=188378 | CC-MAIN-2017-51 | refinedweb | 224 | 54.69 |
import "github.com/function61/varasto/pkg/stateresolver"
Computes the state of collection at an exact revision. The revision's parent DAG is traversed back to the root to compute all the deltas.
type DirPeekResult struct { Path string Files []stotypes.File ParentDirs []string // doesn't include root SubDirs []string }
func DirPeek(files []stotypes.File, dirToPeek string) *DirPeekResult
given a bunch of files with paths, we can create a directory model that lets us look at one directory at a time, listing its sub- and parent dirs
func ComputeStateAtHead(c stotypes.Collection) (*StateAt, error)
List of files present at this revision
Package stateresolver imports 6 packages (graph) and is imported by 4 packages. Updated 2020-09-27. Refresh now. Tools for package owners. | https://godoc.org/github.com/function61/varasto/pkg/stateresolver | CC-MAIN-2020-50 | refinedweb | 121 | 55.95 |
An instance of the User class represents a user. User instances are unique and comparable. If two instances are equal, then they represent the same user.
The application can access the User instance for the current user by calling the users.get_current_user() function.
from google.appengine.api import users user = users.get_current_user() if not user: # The user is not signed in. else: print "Hello, %s!" % user.nickname(). If you switch authentication options from Google Accounts to OpenID, existing User objects in the datastore are still valid. (Note that the support for OpenID is experimental.)
Using User Values With the Datastore
The user ID:
from google.appengine.api import users from google.appengine.ext import ndb class UserPrefs(ndb.Model): userid = ndb.StringProperty() user = users.get_current_user() if user: q = ndb.gqlQuery("SELECT * FROM UserPrefs WHERE userid = :1", user.user_id()) userprefs = q.get()
You probably don't want to store a
UserProperty, since it is equal to the email address
plus the user's unique ID. If a user changes their email address and you compare their old, stored
User to the new
User value, they won't match. | https://developers.google.com/appengine/docs/python/users/userobjects | CC-MAIN-2014-15 | refinedweb | 187 | 62.54 |
Bart De Smet's on-line blog (0x2B | ~0x2B, that's the question)
While I'm in the mood of writing up those cookbook posts:
let's do another one. Custom actions are a powerful way to extend MSI-based installers with custom code. Maybe you've run into these before when you created for example a managed Windows Service and hooked it up in the setup project (essentially installutil-able components can be added to an installer by means of a custom action). In this post we'll write our own (dummy) custom action and show how to debug it nicely, something that seems to be a barrier for quite some developers to consider writing a custom action.
Step 1 - Create a class library project
Once more, Class Library is your friend:
Step 2 - Add references
Choose Add References from the context menu on the project node in Solution Explorer. In there, select System.Configuration.Install:
Step 3 - Plumbing the wires
Custom actions in managed code are wrapped in Installer-subclasses, so derive your class from Installer:
and import the System.Configuration.Install namespace. In order for the installer class to be picked up at runtime, you need to attribute it with RunInstaller(true):
This is the result:
Step 4 - Add functionality
In order to make the custom action do something, you need to override some methods of the base class. I've indicated the most common ones:
These correspond to the actions taken by MSI. Let's just override Install and Commit and play a little with state that's passed around (let's not go in depth, more information is available in MSDN):
Step 5 - Make it debuggable
Our goal is to attach a debugger but custom actions are launched somewhere in the middle of some MSI process. How can we allow for easy debugging? Here's a way to do it: instrument your code with some wait mechanisms to allow for attaching the debugger. A nice way is to use MessageBox. To do this, you'll need to add System.Windows.Forms to the references of the project (as in step 2) and import the namespace:
By wrapping these in DEBUG #if's we make sure the code doesn't make it to Release builds, which is good.
Step 6 - The setup project
Time to build the setup project. Add a new project to the solution and choose for a Setup Project:
The project will open in File System view. Go to the Application Folder, right-click in the right-hand side pane and choose Add Project Output:
Select Primary Output for the MyCustomAction project created above:
This will add the DLL file to the installation folder:
Now it's time to add the Custom Action to the installer (in technical terms to the to-be-built MSI database). Make sure the setup project is selected in Solution Explorer and select Custom Actions Editor from the toolbar:
Adding the actions is simple:
and select the Primary output from MyCustomAction from above:
Do the same for the Commit node.
Step 7 - Build and debug
That's it. Time for a test run. First, build the MyCustomAction project. Next, right-click the setup project node and choose Build. This is not done when building the solution (since it takes quite some time and you likely do it only sporadically in a bigger solution):
Next, right-click the project again and choose Install:
Here we go. Click your way through the installer and wait. On Vista you'll need to give UAC consent. After a while you'll see:
Don't click OK yet. Switch back to Visual Studio and choose Debug, Attach to Process:
You won't find the Attach debugger here dialog in the list at first sight, that's because the custom action is running under the context of the Installer Service in an msiexec.exe instance running under a different (service account) user. Mark 'Show processes from all users' to see it:
and click Attach. On Vista you might see the following when you didn't start Visual Studio elevated:
Elevation is needed because you're about to debug something with more privileges and rights (running under SYSTEM after all). Choose Restart under different credentials and accept the UAC prompt. Visual Studio will come back in the same project but you'll have to repeat the previous steps to attach the debugger. Notice the user name is now displayed in the dialog:
Set breakpoints on the instructions right below the #if DEBUG section:
and click OK on the dialog:
You'll see the breakpoint being hit:
Woohoo! Feel free to step though the (one) line(s) of the custom action and finally hit F5. Now the commit dialog appears and when dismissing it, we'll end up on the next breakpoint:
notice the state from the install phase was recovered:
Enjoy!
Debug di Custom Actions
MSBuild The custom MSBuild task cookbook [Via: bart ] ASP.NET Simplifying ASP.NET ListView Control...
Link Listing - February 15, 2008
Better to use Debugger.Break() to attach the debugger directly...
Hi Tom,
Thanks for the feedback. The approach you suggest works as well and I guess it's a matter of taste. On Vista, it's an interesting case of how far the system goes to preserve the right isolation boundaries. Actually, what you end up doing is causing a faked failure condition in the Windows Installer process running the custom action (under SYSTEM), so you'll see setup "crash" with the message in the line of "(process) has hit a user-defined breakpoint". The thing I slightly dislike about it is the pause caused by the "search for solutions" before one can hit "Debug" - but that of course is subjective too.
Thanks,
-Bart
There's only one problem with this -- managed code is sticky; once you've loaded one version of the run-time that's it for that process.
Gory details here:
robmensching.com/.../Managed-Code-CustomActions-no-support-on-the-way-and-heres.aspx
Hi Steve,
Sure - this is a general .NET limitation concerning the way the EE is loaded in the process space. The teams are definitely aware of this.
Although this is a real implementation, it shouldn't hit people too much if all you're doing is customizing the application setup with a few CA's which are typically tightly related to the app you're deploying so most likely you're bound to a certain .NET FX release.
Nevertheless this article points out how to debug such a custom action in case you want to go around and create such a thing in managed code, without considering downsides such as the one you bring up. There are btw many places where CA's are used by the platform itself such a for managed service installers, PowerShell snap-ins, etc.
My recent series of "cookbook" posts has been very well-received and coincidentally I got mail | http://community.bartdesmet.net/blogs/bart/archive/2008/02/15/the-managed-installer-custom-actions-cookbook.aspx | crawl-002 | refinedweb | 1,162 | 60.24 |
10952/accessing-environment-variables
import os
print(os.environ['HOME'])
Hii,
Environment variables must be strings, so use
os.environ["DEBUSSY"] ...READ MORE
If you're already normalizing the inputs to ...READ MORE
What i found is that you can use ...READ MORE
Using an additional state variable, such as ...READ MORE
You can also use the random library's ...READ MORE
Syntax :
list. count(value)
Code:
colors = ['red', 'green', ...READ MORE
Enumerate() method adds a counter to an ...READ MORE
You can simply the built-in function in ...READ MORE
Variables in python work differently than they ...READ MORE
OR
At least 1 upper-case and 1 lower-case letter
Minimum 8 characters and Maximum 50 characters
Already have an account? Sign in. | https://www.edureka.co/community/10952/accessing-environment-variables | CC-MAIN-2022-27 | refinedweb | 124 | 62.14 |
You can use the following basic syntax to perform a VLOOKUP (similar to Excel) in pandas:
pd.merge(df1, df2, on ='column_name', how ='left')
The following step-by-step example shows how to use this syntax in practice.
Step 1: Create Two DataFrames
First, let’s import pandas and create two pandas DataFrames:
import pandas as pd #define first DataFrame df1 = pd.DataFrame({'player': ['A', 'B', 'C', 'D', 'E', 'F'], 'team': ['Mavs', 'Mavs', 'Mavs', 'Mavs', 'Nets', 'Nets']}) #define second DataFrame df2 = pd.DataFrame({'player': ['A', 'B', 'C', 'D', 'E', 'F'], 'points': [22, 29, 34, 20, 15, 19]}) #view df1 print(df1) player team 0 A Mavs 1 B Mavs 2 C Mavs 3 D Mavs 4 E Nets 5 F Nets #view df2 print(df2) player points 0 A 22 1 B 29 2 C 34 3 D 20 4 E 15 5 F 19
Step 2: Perform VLOOKUP Function
The VLOOKUP function in Excel allows you to look up a value in a table by matching on a column.
The following code shows how to look up a player’s team by using pd.merge() to match player names between the two tables and return the player’s team:
#perform VLOOKUP joined_df = pd.merge(df1, df2, on ='player', how ='left') #view results joined_df player team points 0 A Mavs 22 1 B Mavs 29 2 C Mavs 34 3 D Mavs 20 4 E Nets 15 5 F Nets 19
Notice that the resulting pandas DataFrame contains information for the player, their team, and their points scored.
You can find the complete online documentation for the pandas merge() function here.
Additional Resources
The following tutorials explain how to perform other common operations in Python:
How to Create Pivot Tables in Python
How to Calculate Correlation in Python
How to Calculate Percentiles in Python | https://www.statology.org/pandas-vlookup/ | CC-MAIN-2021-39 | refinedweb | 304 | 59.16 |
04 November 2011 15:44 [Source: ICIS news]
LONDON (ICIS)--The International Airlines Group (IAG) are confident it will deliver higher year-on-year profitability in the fourth quarter, despite robust jet fuel prices, it said on Friday.
Fuel costs for the nine-month period to 30 September 2011 were up by 28.5% year on year to around €3.75m ($5.21m), the group said.
Furthermore, fuel costs in the third quarter alone were up 23.7% from the same period in 2010, while non-fuel costs were flat.
“Our revenue is up by 2.2% in the quarter, driven primarily by volume. However, high fuel costs continue to have a significant impact on our business,” said Willie Walsh, IAG’s chief executive.
According to ICIS, jet fuel cargoes are currently trading at price levels of $1,024-1,026/tonne CIF (cost insurance freight) NWE (northwest ?xml:namespace>
Outright jet fuel prices - calculated by adding ICE gasoil values to jet fuel differentials - had fallen to levels as low as $949/tonne CIF NWE during early October because of lower ICE gasoil figures on the back of concerns over the eurozone economy.
However, since then prices have climbed as European leaders work to resolve the debt issues in the region, which had led to firmer crude oil and ICE gasoil values.
While the European debt crisis exerts its influence on jet fuel prices, it has further connotations for the aviation industry, notably the possibility of decreased demand for air travel as consumers slash travel budgets.
“The main challenge of 2012 will be to offset increased fuel costs as our hedges unwind, against a background of potentially weaker demand,” Walsh said.
However, IAG remains positive about group profitability during the fourth quarter and for 2011 as a whole.
“Given the disruption and non-recurring accounting items in the fourth quarter of 2010, we are confident of a higher level of profitability [in the fourth quarter of] this year, even after the negative impact of the high fuel price. We expect to deliver a 2011 full-year operating profit of around double the year 2010 profits,” Walsh | http://www.icis.com/Articles/2011/11/04/9505681/iag-confident-of-profitability-in-2011-despite-high-fuel-costs.html | CC-MAIN-2014-52 | refinedweb | 356 | 59.84 |
Bob and Bombs
Bob and Bombs problems: Bob and Khatu are brave soldiers in World War 3(. They have spotted an enemy troop which is planting bombs. They sent message to the command centre containing characters W and B where W represents a wall and B represents a Bomb. They asked command to tell them how many walls will be destroyed if all bombs explode at once. One bomb can destroy 2 walls on both sides.
Input:
First line of input contains number of test cases T. Each test case contains a single string which contains two type of chars ‘W’ and ‘B’.
Output:
For each test case print the total number of destroyed wall.
Constraints:
1 ≤ T ≤ 10
1 ≤ |S| ≤ 105
#include <iostream> using namespace std; int main() { int x, count,j; string s; cin >> x; while(x--) { count=0; cin >> s; j=0; while(j<s.length()) { if((s[j]=='W') && ((j>0 && s[j-1]=='B') || (j>1 && s[j-2]=='B') || (j<s.length()-1 && s[j+1]=='B') || (j<s.length()-2 && s[j+2]=='B')) ) count++; j++; } cout << count << endl; } return 0; }
Competitive coding
Hackerearth problem
| https://coderinme.com/bob-and-bombs-hackerearth-problem-coderinme/ | CC-MAIN-2018-47 | refinedweb | 192 | 83.15 |
Use Red Hat Quay
Use Red Hat Quay
Abstract
Preface
Whether you deployed your own Red Hat Quay service or are using the Quay.io registry, follow descriptions here to start using your Quay repository to store and work with images.
Chapter 1. Creating a repository
There are two ways to create a repository in Quay: via a
docker push and via the Quay UI. These are essentially the same, whether you are using Quay.io or your own instance of Red Hat Quay.
1.1. Creating an image repository via the UI
To create a repository in the Quay UI, click the
+ icon in the top right of the header on any Quay page and choose
New Repository. Select
Container Image Repository on the next page, choose a namespace (only applies to organizations), enter a repository name and then click the
Create Repository button. The repository will start out empty unless a
Dockerfile is uploaded as well.
1.2. Creating an image repository via docker
First, tag the repository. Here are examples for pushing images to Quay.io or your own Red Hat Quay setup (for example, reg.example.com).
# docker tag 0u123imageid quay.io/namespace/repo_name # docker tag 0u123imageid reg.example.com/namespace/repo_name
Then push to the appropriate Quay registry. For example:
# docker push quay.io/namespace/repo_name # docker push reg.example.com/namespace/repo_name
1.3. Creating an application repository via the UI
To create a repository in the Quay UI, click the
+ icon in the top right of the header on any Quay page and choose
New Repository. Select
Application Repository on the next page, choose a namespace (only applies to organizations), enter a repository name and then click the
Create Repository button. The repository will start out empty.
Chapter 3. Setting up a Custom Git Trigger
A Custom Git Trigger is a generic way for any git server to act as a build trigger. It relies solely on SSH keys and webhook endpoints; everything else is left to the user to implement.
3.1. Creating a Trigger
Creating a Custom Git Trigger is similar to the creation of any other trigger with a few subtle differences:
- It is not possible for Quay to automatically detect the proper robot account to use with the trigger. This must be done manually in the creation process.
- There are extra steps after the creation of the trigger that must be done in order to use the trigger. These steps are detailed below.
3.2. Post trigger-creation setup
Once a trigger has been created, there are 2 additional steps required before the trigger can be used:
- Provide read access to the SSH public key generated when creating the trigger.
- Setup a webhook that POSTs to the Quay endpoint to trigger a build.
The key and the URL are both available at all times by selecting
View Credentials from the gear located in the trigger listing.
3.2.1. SSH public key access
Depending on the Git server setup, there are various ways to install the SSH public key that.
3.2.2. } } }
This request requires a
Content-Type header containing
application/json in order to be valid.
Once again, this can be accomplished in various ways depending on the server setup, but for most cases can be done via a post-receive git hook.
Chapter 4. Skipping a source control-triggered build
To specify that a commit should be ignored by the Quay build system, add the text
[skip build] or
[build skip] anywhere in the commit message.
Chapter 5..
Adding notifications requires repository admin permission.
The following are examples of repository events.
5.1. Repository Events
5.1.1. Repository Push
A successful push of one or more images was made to the repository:
{ "name": "repository", "repository": "dgangaia/test", "namespace": "dgangaia", "docker_url": "quay.io/dgangaia/test", "homepage": "", "updated_tags": [ "latest" ] }
5.1.2. Dockerfile Build Queued
A Dockerfile build has been queued into the build system:
{ " ], ": { "url": "", "date": "2019-03-06T12:48:24+11:00", "message": "adding 5", "author": { "username": "dgangaia", "url": "", "avatar_url": "" }, "committer": { "username": "web-flow", "url": "", "avatar_url": "" } } }, "is_manual": false, "manual_user": null, "homepage": "" }
5.1.3. Dockerfile Build Started
A Dockerfile build has been started by the build system
{ "build_id": "a8cc247a-a662-4fee-8dcb-7d7e822b71ba", ": "50bc599", "trigger_metadata": { "commit": "50bc5996d4587fd4b2d8edc4af652d4cec293c42", "ref": "refs/heads/master", "default_branch": "master", "git_url": "git@github.com:dgangaia/test.git", "commit_info": { "url": "", "date": "2019-03-06T14:10:14+11:00", "message": "test build", "committer": { "username": "web-flow", "url": "", "avatar_url": "" }, "author": { "username": "dgangaia", "url": "", "avatar_url": "" } } }, "homepage": "" }
5.1.4. Dockerfile Build Successfully Completed
A Dockerfile build has been successfully completed by the build system
This event will occur simultaneously with a Repository Push event for the built image(s)
{ ": ": { "url": "", "date": "2019-03-06T12:48:24+11:00", "message": "adding 5", "committer": { "username": "web-flow", "url": "", "avatar_url": "" }, "author": { "username": "dgangaia", "url": "", "avatar_url": "" } } }, " ] }
5.1.5. Dockerfile Build Failed
A Dockerfile build has failed
{ "build_id": "5346a21d-3434-4764-85be-5be1296f293c", "trigger_kind": "github", ", "docker_tags": [ "master", "latest" ], "build_name": "6ae9a86", "trigger_metadata": { "commit": "6ae9a86930fc73dd07b02e4c5bf63ee60be180ad", "ref": "refs/heads/master", "default_branch": "master", "git_url": "git@github.com:dgangaia/test.git", "commit_info": { "url": "", "date": "2019-03-06T14:18:16+11:00", "message": "failed build test", "committer": { "username": "web-flow", "url": "", "avatar_url": "" }, "author": { "username": "dgangaia", "url": "", "avatar_url": "" } } }, "homepage": "" }
5.1.6. Dockerfile Build Cancelled
A Dockerfile build was cancelled
{ "build_id": "cbd534c5-f1c0-4816-b4e3-55446b851e70", ": ": "" }
5.1.7. } }
5.2. Notification Actions
5.2.1..
5.2.2. E-mail
An e-mail will be sent to the specified address describing the event that occurred.
All e-mail addresses will have to be verified on a per-repository basis
5.2.3..
5.2.4. Flowdock Notification
Posts a message to Flowdock.
5.2.5. Hipchat Notification
Posts a message to HipChat.
5.2.6. Slack Notification
Posts a message to Slack.
Chapter 6. Building Dockerfiles
Quay.io supports the ability to build Dockerfiles on our build fleet and push the resulting image to the repository.
6.1. Viewing and managing builds
Repository Builds can be viewed and managed by clicking the Builds tab in the
Repository View.
6.2. Manually starting a build
To manually start a repository build, click the
+ icon in the top right of the header on any repository page and choose
New Dockerfile Build. An uploaded
Dockerfile,
.tar.gz, or an HTTP URL to either can be used for the build.
You will not be able to specify the Docker build context when manually starting a build.
6.3. Build Triggers
Repository builds can also be automatically triggered by events such as a push to an SCM (GitHub, BitBucket or GitLab) or via a call to a webhook.
6.3.1. Creating a new build trigger
To setup a build trigger, click the
Create Build Trigger button on the Builds view page and follow the instructions of the dialog. You will need to grant Quay.io access to your repositories in order to setup the trigger and your account requires admin access on the SCM repository.
6.3.2. Manually triggering a build trigger
To trigger a build trigger manually, click the icon next to the build trigger and choose
Run Now.
6.3.3. Build Contexts
When building an image with Docker, a directory is specified to become the build context. This holds true for both manual builds and build triggers because the builds conducted by Quay.io are no different from running
docker build on your own machine.
Quay.io build contexts are always the specified subdirectory from the build setup and fallback to the root of the build source if none is specified. When a build is triggered, Quay.io Quay. Thus, it must not appear in the
.dockerignore file.
Chapter 7. Set up GitHub build triggers
Red Hat Quay supports using GitHub or GitHub Enterprise as a trigger to building images.
- Initial setup: If you have not yet done so, please enable build support in Red Hat Quay.
Create an OAuth application in GitHub: Following the instructions at Create a GitHub Application.Note
This application must be different from that used for GitHub Authentication.
- Visit the Red Hat Quay config UI: Start up the Red Hat Quay config UI.
Enable GitHub triggers:
- Scroll down to the section entitled GitHub (Enterprise) Build Triggers.
- Check the "Enable GitHub Triggers" box
- Fill in the credentials from the application created above
- Click "Save Configuration Changes"
- Deploy the changes to your Red Hat Quay application.
Chapter 8. Automatially build Dockerfiles with build workers
Red Hat Quay.
8.1. Enable building
- Visit the management panel: Sign in to a superuser account and visit view the management panel:
Enable Dockerfile Build Support:
- Click the configuration tab and scroll down to the section entitled Dockerfile Build Support.
- Check the "Enable Dockerfile Build" box
- Click "Save Configuration Changes"
- Restart the container (you will be prompted)
8.2. Set up the build workers
One or more build workers will communicate with Red Hat Quay to build new containers when triggered. The machines must have Docker installed and must not be used for any other work. The following procedure needs to be done every time a new worker needs to be added, but it can be automated fairly easily.
8.2.1. Pull the build worker image
Pull down the latest copy of the image. Make sure to pull the version tagged matching your Red Hat Quay version.
# docker pull quay.io/coreos/quay-builder:v2.9.5
8.2.2. Run the build worker image Red Hat Quay is accessible:
Here’s what the full command looks like:
# docker run --restart on-failure \ -e SERVER=ws://myquayenterprise \ -v /var/run/docker.sock:/var/run/docker.sock \ quay.io/coreos/quay-builder:v2.9 found at the host’s /path/to/ssl/rootCA.pem looks like:
# docker run --restart on-failure \ -e SERVER=wss://myquayenterprise \ -v /path/to/ssl/rootCA.pem:/usr/local/share/ca-certificates/rootCA.pem \ -v /var/run/docker.sock:/var/run/docker.sock \ --entrypoint /bin/sh \ quay.io/coreos/quay-builder:v2.9.3 \ -c '/usr/sbin/update-ca-certificates && quay-builder'
8.3. Set up GitHub build (optional)
If your organization plans to have builds be conducted via pushes to GitHub (or GitHub Enterprise), please continue with the Setting up GitHub Build.
Chapter 9. Creating an OAuth application in GitHub
You can authorize your registry to access a GitHub account and its repositories by registering it as a GitHub OAuth application.
9.1. Create new GitHub application
- Log into GitHub (Enterprise)
- Visit the Applications page under your organization’s settings.
- Click Register New Application. The
Register a new OAuth applicationconfiguration screen is displayed:
Set Homepage URL: Enter the Quay Enterprise URL as the
Homepage URLNote
If using public GitHub, the Homepage URL entered must be accessible by your users. It can still be an internal URL.
- Set Authorization callback URL: Enter https://{$RED_HAT_QUAY_URL}/oauth2/github/callback as the Authorization callback URL.
- Save your settings by clicking the Register application button. The new new application’s summary is shown:
- Record the Client ID and Client Secret shown for the new application.
Chapter 10. Downloading Squashed Docker Images
Docker images are composed of image layers which include all of the intermediary data used to reach their current state. When iterating on a solution locally on a developer’s machine, layers provide an efficient workflow.
There are scenarios, however, in which the layers cease to be efficient. For example, when deploying software to an ephemeral machine, that machine doesn’t care about the whole layer history, it just needs the end state of the image. This is why Quay.io supports Squashed Images.
10.1. Downloading a Squashed Image
To download a squashed image:
- Navigate to the
Tagstab of a Quay
Repository View. For an organization named
abcsalesand a repo named
myweb, the URL would be) on Quay.io. For a Red Hat Quay registry, replace
quay.iowith your registry name.
- On the left side of the table, click on the Fetch Tag icon for the tag you want to download. A modal dialog appears with a dropdown for specifying the desired format of the download.
Squashed Docker Imagefrom the dropdown and then select a robot that has read permission to be able to pull the repository.
- Click on the
Copy Commandbutton.
- Paste this command into a shell on the machine where you have a Docker service running.
- Type
docker imagesto see that the image is loaded and read to use.
10.2. Caveats & Warnings
10.2.1. Prime the cache!
When the first pull of a squashed image occurs, the registry streams the image as it is being flattened in real time. Afterwards, the end result is cached and served directly. Thus, it is recommended to pull the first squashed image on a developer machine before deploying, so that all of the production machines can pull the cached result.
10.2.2. Isn’t piping curl insecure?
You may be familiar with installers that pipe curl into bash (
curl website.com/installer | /bin/bash). These scripts are insecure because they allow arbitrary code execution. The Quay script to download squashed images uses
curl to download a tarball that is streamed into
docker load. This is just as secure as running
docker pull because it never executes anything we’ve downloaded from the internet. | https://access.redhat.com/documentation/en-us/red_hat_quay/2.9/html-single/use_red_hat_quay/index | CC-MAIN-2020-24 | refinedweb | 2,218 | 55.34 |
details: Embedded technology and Linux programming. Joining date: Trainer: Location: Company: Duration: Timing: Contact: D-108 Sec-2 Noida. (0120) 4310313. Noida. ATC CMC Ltd. 6 Months.
2,000+ experts in technologies & domain for Application Development Practice 700.
History:CMC was incorporated on December 26, 1975, as the 'Computer Maintenance Corporation Private Limited'. The Government of India held 100 per cent of the equity share capital. On August 19, 1977, it was converted into a public limited company. In 1978, when IBM wound up its operations in India, CMC took over the maintenance of IBM installations at over 800 locations around India and, subsequently, maintenance of computers supplied by other foreign manufacturers as well. Taking over the activities of IBM in India, including many of its employees, helped the company to imbibe a serviceoriented.
C Programming language. Microcontroller 8051 Programming. Linux Internals. System Programming. Project.
C Language Programming
Introduction. Application. Control flow. Conditional & decision statement. Functions. MACROS. Pointers Structures Union File handling. Link list. Stack & ques. Trees. Programs.
C language programming:
Introduction:C language is widely used in the development of operating systems. An Operating System(OS) is a software(collection of programs) that controls the various functions of a computer. Also it makes other programs on your computer work. For example, you cannot work with a word processor program, such as Microsoft Word, if there is no operating system installed on your computer. Windows, Unix, Linux, Solaris, and MacOS are some of the popular operating systems.
Where is C useful?Cs ability to communicate directly with hardware makes it a powerful choice for system programmers. In fact, popular operating systems such as Unix and Linux are written entirely in C. Additionally, even compilers and interpreters for other languages such as FORTRAN, Pascal, and BASIC are written in C. However, Cs scope is not just limited to developing system programs. It is also used to develop any kind of application, including complex business ones. The following is a partial list of areas where C language is used:
Embedded Systems Systems Programming Artificial Intelligence Industrial Automation Computer Graphics Space Research Image Processing Game Programming
Control Flow:
In computer science, control flow (or alternatively, flow of control) refers to the order in which the individual statements, instructions, or function calls of an imperative or a declarativeprogram:).
If-then(-else)The if-then construct (sometimes called if-then-else) is common across many programming languages. Although the syntax varies quite a bit from language to language, the basic structure (in pseudocode form) looks like this: (The example is actually perfectly valid Visual Basic or QuickBASIC syntax.)
Else ifBy language:
If expressionsMany languages support if expressions, which are similar to if statements, but return a value as a result. Thus, they are true expressions (which evaluate to a value), not statements (which just perform an action). As a ternary operator Main article: ?: In C and C-like languages conditional expressions take the form of a ternary operator called the conditional expression operator, ?:, which follows this template: (condition)?(evaluate if condition was true):(evaluate if condition was false)
Functions:Functions are used in c for the following reasons, Function definition, Types of functions, Functions with no arguments and no return values, Functions with arguments but no return values, Functions with arguments and return values, Return value data type of function and Void functions.
Types of functions:A function may belong to any one of the following categories: 1. Functions with no arguments and no return values. 2. Functions with arguments and no return values. 3. Functions with arguments and return values.
MACROS.
Pointers:In C language, a pointer is a variable that points to or references a memory location in which data is stored. Each memory cell in the computer has an address which can be used to access its location. A pointer variable points to a memory location. By making use of pointer, we can access and change the contents of the memory location.
Pointer declaration:A pointer variable contains the memory location of another variable. You begin the declaration of a pointer by specifying the type of data stored in the location identified by the pointer. The asterisk tells the compiler that you are creating a pointer variable. Finally you give the name of the pointer variable. The pointer declaration syntax is as shown below. type * variable name Example: int *ptr; float *string;
Address operator:Once we declare a pointer variable, we point the variable to another variable. We can do this by assigning the address of the variable to the pointer as in the following example: ptr=# The above declaration places the memory address of num variable into the pointer variable ptr. If num is stored in memory 21260 address then the pointer variable ptr will contain the memory address value 21260.. Strings are characters arrays and here last element is arrays and pointers to char arrays can be used to perform a number of string functions.
incremented by one it is made to pint to next record ie item[1]. The following statement will print the values of members of all the elements of the product array.
Pointers on pointer:While pointers provide enormous power and flexibility to the programmers, they may use cause manufactures if it not properly handled. Consider the following precautions.
Arrays of structure:
It is possible to define a array of structures for example if we are maintaining information of all the students in the college and if 100 students are studying in the college. We need to use an array than single variables. An array of structures can be assigned initial values just as any other array can. Remember that each element is a structure that must be assigned corresponding initial values . conserve memory. They are useful for application involving multiple members. Where values need not be assigned to all the members at any one time. Like structures union can be declared using the keyword union are all valid member variables. During accessing we should make sure that we are accessing the member whose value is currently stored.
File handling:In any programming language it is vital to learn file handling techniques. Many applications will at some point involve accessing folders and files on the hard drive. In C, a stream is associated with a file. Special functions have been designed for handling file operations. Some of them will be discussed in this chapter. The header file stdio.h is required for using these functions.
Opening a file:Before we perform any operations on a file, we need to identify the file to the system and open it. We do this by using a file pointer. The type FILE defined in stdio.h allows us to define a file pointer. Then you use the function fopen() for opening a file. Once this is done one can read or write to the file using the fread() or fwrite() functions, respectively. The fclose() function is used to explicitly close any opened file.
In this section, we introduce two closely-related data types for manipulating arbitrarily large collections of objects: the stackamount.
1.
Linked list implementation. Program Queue.java implements a FIFO queue of strings using a linked list. Like Stack, we maintain a referencefirst to the least-recently added Node on the queue. For efficiency, we also maintain a reference last to the least-recently added Node on the queue.
2.
Array implementation. Similar to array implementation of stack, but a little trickier since need to wrap-around. Program DoublingQueue.javaimplements the queue interface. The array is dynamically resized using repeated doubling.
Treestree .
Height of B-TreesFor n greater than or equal to one, the height of an n-key b-tree T of height h with a minimum degree t greater than or equal to 2,
int main() { int n = 0, remainder, sum = 0, i = 0, noDigits = 0, isArm = 0; char ch[60] = {0}; printf("Find the Arm Strong Numbers between 1 to N"); scanf("%d", &n); for(i = 1; i<n; i++) { isArm = i; itoa(isArm, ch, 10); noDigits = strlen(ch); while(isArm) { remainder = isArm%10; isArm=isArm/10; sum= sum+pow(remainder, noDigits); } if(sum == i) printf("\nArm Strong Nos are %d\n", i); sum = noDigits = 0; } } 2. /*Program using array.*/ #include <stdio.h> char input[1000]; float temp; int num_count; float total; float average; int main() { printf("I will find the average of however many numbers you enter.\n"); printf("Enter number now (00 to quit): ");
fgets(input, sizeof(input), stdin); temp = atof(input); num_count = 0; total = 0.0; average = 0.0; while ( temp != 00.0 ) { ++num_count; total += temp; printf("Enter next number now (00 to quit): "); fgets(input, sizeof(input), stdin); temp = atof(input); } average = ( total / num_count ); printf("You entered %d numbers. The average of those numbers is %f.\n", num_count, average); return 0; }
3.
#include<stdio.h> Int i,j,m; : \n") ; for ( i = 0 ; i < col ; i++ ) { for ( j = 0 ; j < lig ; j++ ) { printf("%d", MatA[i][j]) ; } printf("\n") ; }
4.
{ int i,fact=1,n; printf("\nEnter the no of terms ="); scanf("%d",&n); for(i=1;i<=n;i++) fact*=i; printf("\nFactorial value for %d terms = %d",n,fact); getch(); } 5. /*Program using function.*/
#include<stdio.h> int fabo(int); void main() { int result=0,a=1,b=1,c; printf("enter upto which you want to generate the series"); scanf("%d",&c); result=fabo(c); printf("%d\n%d\n",a,b); printf("the fabonnaci series is %d\n",result); getch(); } int fabo(int n) { if (n==1);
6. /*Program using function.*/ #include<stdio.h> void main() { int a=2,b=3; swap(a,b); printf("%d%d",a,b); getch() } swap(int *x,int *y) { int t; t=*x; *x=*y; *y=t; printf("%d%d",x,y); } 7. /*Program to find palindrome.*/
#include<stdio.h> #include<conio.h> void main() { int first,last,flag=1; char str[100]; clrscr(); printf("Enter number to get to check wheather palindrome or not"); gets(str); first=0; last=strlen(str)-1; printf("%d",first); printf("%d",last); while(first<=last)
{ if(str[first]!=str[last]) flag=0; first++; last--; } if(flag==1) { clrscr(); printf("this is palindrome"); getch(); } else { clrscr(); printf("sorry this is not a palindrome"); getch(); } } 8. /*Program using pointer.*/
#include<stdio.h> #include<conio.h> void main() { int i,p, *no,factorial,summ; int fact(int p); int sum(int p); int fib(int p); clrscr(); printf("\n Enter The Number:"); scanf("%d",no); printf("\n The Fibonnacci series: \n"); for(i=0;i<*no;i++) printf("%d\n",fib(i)); factorial=fact(*no); printf("\n The factorial of %d: %d\n", *no,factorial); summ=sum(*no);printf("\nThe summation of %d: %d\n", *no,summ); getch(); }int fib(int p) { if(p==0) return(0); if(p>=1&&p<=2) return(1);
else return(fib(p-1)+fib(p-2)); }int fact(int p) { if(p==0) return(1); else return(p*fact(p-1)); }int sum(int p) { if(p==0) return(0); else return(p+sum(p-1))
9.
#include<stdio.h> #include<conio.h> void bubblesort(int*[],int); void main() { int i,n,a[100]; clrscr(); printf("\n Enter the number of elements:"); scanf("%d",&n); printf("\n Enter the array elements"); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("\nUNSORTED ARRAY ELEMENTS"); for(i=0;i<n;i++) printf("\t%d",a[i]); bubblesort(a,n); printf("\nSORTED ARRAY"); for(i=0;i<n;i++) printf("\t%d",*(a+i)); getch(); }void bubblesort(int* b[],int n) { int i,j,t; for(i=0;i<n;i++) { for(j=i+1;j<n;j++) {
10.
#include<stdio.h> #include<conio.h> char string(char str2[10]); void main() { int i; char str1[10]; clrscr(); printf("\n\nEnter the string\t"); for(i=0;i<=9;i++) { scanf("%c",&str1[i]); }string(str1); getch(); }char string(char str2[10]) { int j; printf("\n\nThe string is\t"); for(j=0;j<=9;j++) { printf("%c",str2[j]); }return 1; } 11. Program to accept a string and display in reverse using functions/arrays and pointers*/
char reverse(char *p); void main() { int i; char str[10]; clrscr(); printf("\n\nEnter the String\t"); gets(str); reverse(str); getch(); } char reverse(char *p) { int j,l; l=strlen(p); printf("\n\nString in reverse is \t"); for(j=l-1;j>=0;j--) { printf("%c",p[j]); }return 1; }
12.
#include <stdio.h> /* User defined types */ enum deptcode {sales,personnel,packing,engineering}; typedef enum deptcode DEPT; struct person { int age, salary; DEPT department; char name[12]; char address[6][20]; }; typedef struct person EMPLOYEE; void read_line(char Str[]) { int i = 0; char next; while ((next=getchar())!='\n') { Str[i] = next; i++; } Str[i] = 0; /* Set the null char at the end */ } void print_employee(EMPLOYEE Emp) { int i; printf(" %d %d %d\n",Emp.age,Emp.salary,Emp.department); printf("%s\n",Emp.name); for (i=0;i<=5;i++) printf("%s\n",Emp.address[i]); } void main () { EMPLOYEE This_Employee; int i; scanf("%d",&This_Employee.age); scanf("%d",&This_Employee.salary); scanf("%d\n",&This_Employee.department); read_line(This_Employee.name); for (i=0; i<=5; i++) read_line(This_Employee.address[i]); print_employee(This_Employee); }
13.
#include "stdio.h" #include "conio.h" struct adress { char ct[10]; char dist[10],state[5]; long int pin; }; struct emp { char name[10]; int age,sal; struct adress a; }; void main() { struct emp e[2]; int i; clrscr(); for(i=0;i<=1;i++) { printf("Enter [%d]st Employee's Name,Age,salary :: ", i); scanf("%s%d%d",e[i].name,&e[i].age,&e[i].sal); printf("\nEnter city, district,state & pincode ::"); scanf("%s%s%s%ld",e[i].a.ct,e[i].a.dist,e[i].a.state,&e[i].a.pin); } for(i=0;i<=1;i++) { printf("\n[%d]st Employee's Name :: %s",i,e[i].name); printf("\n[%d]st Employee's Age :: %d ",i,e[i].age); printf("\n[%d]st Employee's Salary :: %d",i,e[i].sal); printf("\n[%d]st Employee's City :: %s ",i,e[i].a.ct); printf("\n[%d]st Employee's District :: %s",i,e[i].a.dist); printf("\n[%d]st Employee's State :: %s",i,e[i].a.state); printf("\n[%d]st Employee's Pin :: %ld",i,e[i].a.pin); } getch(); } 14. /*Program using structure.*/; }
15.
/*Program using union.*/ typedef union { float coords[3]; char about[20]; } assocdata;
typedef struct { char *descript; int un_type; assocdata alsostuff; } leaf; int main() { leaf oak[3]; int i; printf ("Hello World\n"); for (i=0; i<3; i++) { oak[i].descript = "A Greeting"; oak[i].un_type = 1; oak[i].alsostuff.coords[0] = 3.14; } oak[2].alsostuff.about[2] = 'X'; for (i=0; i<3; i++) { printf("%s\n",oak[i].descript); printf("%5.2f\n",oak[i].alsostuff.coords[0]); } } 16. /*Program using link list.*/
typedef struct nd { int info; struct nd*link; } node; /* AFTER CREATING LINK LIST */ node*reverse(node *h)
{ node *H=NULL *p; while(h!=NULL) { p=h; /* insert value of 1st node into p */ h=h->next; p->next=H; /* insert p->next =NULL because H is equals to NULL (1st time) */ H=p; /* insert address of p into H */ } return H; } 17. /*Program using link list.*/ #include<stdio.h> #include<stdlib.h> struct list { int month; struct list *next; }; typedef struct list node; void init(node* record) { record->next=NULL; } void addnode(node* record int d) { node* fresh; fresh=(node *)malloc(sizeof(node)); fresh->month=d; fresh->next=record->next; record->next=fresh; } void print(node *record)
{ node* temp; temp=(node *)malloc(sizeof(node)); for(temp=record->next;temp;temp=temp->next) printf(" d" temp->month); } node* reverse_recurse(node* cur node* start)/*reverse linked list recursively*/ { if(cur->next==NULL) { start->next=cur; return cur; } else { reverse_recurse(cur->next start)->next=cur; } return cur; } int main(void) { node* start; start=(node *)malloc(sizeof(node)); init(start); int i=0; for(i=20;i>=0;i--) addnode(start i);
Instruction set:
The 8051 controller has six hardware interrupts of which five are available to the programmer. These are as follows:
1. RESET interrupt - This is also known as Power on Reset (POR). When the RESET interrupt is received, the controller restarts executing code from 0000H location. This is an interrupt which is not available to or, better to say, need not be available to the programmer. 2. Timer interrupts - Each Timer is associated with a Timer interrupt. A timer interrupt notifies the microcontroller that the corresponding Timer has finished counting. 3.. 4. Serial interrupt - This interrupt is used for serial communication. When enabled, it notifies the controller whether a byte has been received or transmitted. How is an interrupt serviced? Every interrupt is assigned a fixed memory area inside the processor/controller. The Interrupt Vector Table (IVT) holds the starting address of the memory area assigned to it (corresponding to every interrupt). When an interrupt is received, the controller stops after executing the current instruction. It transfers the content of program counter into stack. It also stores the current status of the interrupts internally but not on stack. After this, it jumps to the memory location specified by Interrupt Vector Table (IVT). After that the code written on that memory area gets executed. This code is known as the Interrupt Service Routine (ISR) or interrupt handler. ISR is a code written by the programmer to handle or service the interrupt.. 2. Programming External Interrupts. The TCON register has following trig-
1. 2.
ger interrupt (low) at INTx pin must be four machine cycles long and not greater than or smaller than this. Following are the steps for using external interrupt : Enable external interrupt by configuring IE register. Write routine for external interrupt. The interrupt number is 0 for EX0 and 2 for EX1 respectively. 3. Programming Serial Interrupt To use the serial interrupt the ES bit along with the EA bit is set. Whenever one byte of data is sent or received, the serial interrupt is generated and the TI or RI flag goes high. Here, the TI or RI flag needs to be cleared explicitly in the interrupt routine (written for the Serial Interrupt). The programming of the Serial Interrupt involves the following steps: Enable the Serial Interrupt (configure the IE register). Configure SCON register. Write routine or function for the Serial Interrupt. The interrupt number is 4. Clear the RI or TI flag within the routine. Programming multiple interrupts Multiple interrupts can be enabled by setting more than one interrupts in the IE register. If more than one interrupts occur at the same time, the interrupts will be serviced in order of their priority. By default the interrupts have the following priorities in descending order: The priority of the interrupts can be changed by programming the bits of Interrupt Priority (IP) register. The IP register has the following bit configuration: First two MSBs are reserved. The remaining bits are the priority bits for the available interrupts. Setting a particular bit in IP register makes the corresponding interrupt of the higher priority. For example, IP = 0x08; will make Timer1 priority higher. So the interrupt priority order will change as follows (in descending order): More than one bit in IP register can also be set. In such a case, the higher priority interrupts will follow the sequence as they follow in default case. For example, IP = 0x0A; will make Timer0 and Timer1 priorities higher. So the interrupt priority order will change as follows (in descending order):
1. 2. 3. 4.. However, when the pieces of software that need to communicate are located on different processors, you have to figure out how to bundle the information into a packet and pass it across some sort of link. In this article, we'll look at two standard protocols, SPI and CAN, that can be used to communicate between processors, and also at some of the issues that arise in designing ad hoc protocols for small systems. Controller Area Network (CAN) Controller Area Network (CAN)ret secret. The CAN standards are not a ticket in; you still need the manufacturer's cooperation.
Keil PK51 is a complete software development environment for classic and extended 8051 microcontrollers. Like all Keil tools, it is easy to learn and use.
The Keil 8051 Development Tools are designed to solve the complex problems facing embedded software developers. 1) When starting a new project, simply select the microcontroller you use from the Device Database and the Vision IDE sets all compiler, assembler, linker, and memory options for you. 2) Numerous example programs are included to help you get started with the most popular embedded 8051 devices. 3) The Keil Vision Debugger accurately simulates on-chip peripherals (IC,. 4).
Topview Simulator gives an excellent simulation environment for the industry's most popular 8 bit Microcontroller family, MCS 51. It gives required facilities to enable the system designers to start projects right from the scratch and finish them with ease and confidence.
It is the total simulation solution giving many state of art features meeting the needs of the designers possessing different levels of expertise. If you are a beginner, then you can learn about 8051 based embedded solutions without any hardware. If you are an experienced designer, you may find most of the required facilities built in the simulator that enabling you to complete your next project without waiting for the target hardware. The features of the simulator is briefly tabulated here for your reference: Finished Real Time Projects. Project - 8 Channel Sequential Controller with LED Displays.
Device Selection A wide range of device selection, including Generic 8031 devices and Atmel's AT89CXX series 8051 microcontrollers. Program Editing Powerful editing feature for generating your programs both in C and Assembly level and the facility to call an external Compiler / Assembler (Keil / SDCC Compilers). Simulation Facilities Powerful simulation facilities are incorporated for I/O lines, Interrupt lines, Clocks meant for Timers / Counters. Many external interfacing possibilities can be simulated:
Range of Plain Point LEDs and Seven Segment LED options. LCD modules in many configurations. Momentary ON keys. A variety of keypads upto 4 X 8 key matrix. Toggle switches. All modes of onchip serial port communication facility. I2C components including RTC, EEPROMs. SPI Bus based EEPROM devices.
Code Generation Facilities Powerful and versatile Code Generating facility enables you to generate the exact and compact assembly code / C Source code for many possible application oriented interfacing options. You can simply define your exact needs and get the target assembly code / C Source code at a press of button at anywhere in your program flow. The code gets embedded into your application program automatically. You are assured of trouble free working of final code in the real time. 1)2)
3) 4)
All modes of the serial port. Interfacing I2C/SPI Bus devices. Range of keypads. Many LED/LCD interfacing possibilities.
/*programming of 8051 interfacing with DC motor*/ ;L293D A - Positive of Motor ;L293D B - Negative of Motor ;L293D E - Enable pin of IC
L293D_A equ P2.0 L293D_B equ P2.1 L293D_E equ P2.2 org 0H Main: acall rotate_f acall delay acall break acall delay acall rotate_b acall delay acall break acall delay sjmp Main rotate_f: setb L293D_A clr L293D_B setb L293D_E ret rotate_b: clr L293D_A setb L293D_B setb L293D_E ret
;Rotate motor forward ;Let the motor rotate ;Stop the motor ;Wait for some time ;Rotate motor backward ;Let the motor rotate ;Stop the motor ;Wait for some time ;Do this in loop
;Make Positive of motor 1 ;Make negative of motor 0 ;Enable to run the motor
;Make positive of motor 0 ;Make negative of motor 1 ;Enable to run the motor
break: clr L293D_A clr L293D_B clr L293D_E ret delay: ;Make Positive of motor 0 ;Make negative of motor 0 ;Disable the o/p
mov r7,#20H back: mov r6,#FFH back1: mov r5,#FFH here: djnz r5, here djnz r6, back1 djnz r7, back ret 2. /* programming of 8051 interfacing with stepper motor*/
#include <REG2051.H>. #define stepper P1 void delay(); void main(){ while(1){ stepper = 0x0C; delay(); stepper = 0x06; delay(); stepper = 0x03; delay(); stepper = 0x09; delay(); }
} void delay(){ unsigned char i,j,k; for(i=0;i<6;i++) for(j=0;j<255;j++) for(k=0;k<255;k++); } 3. /* programming of 8051 interfacing with keyboaed*/ start: mov a,#00h mov p1,a mov a,#0fh mov p1,a press: mov a,p2 jz press ;making all rows of port p1 zero ;making all rows of port p1 high ;check until any key is pressed
after making sure that any key is pressed mov a,#01h mov r4,a mov r3,#00h next: mov a,r4 mov p1,a mov a,p2 jnz colscan mov a,r4 rl a mov r4,a mov a,r3 add a,#08h mov r3,a sjmp next ;make one row high at a time ;initiating counter ;making one row high at a time ;taking input from port A ;after getting the row jump to check column ;rotate left to check next row ;increment counter by 08 count
;decimal adjust the contents of counter before display ;repeat for check next key
/* programming of 8051 interfacing with seven segment*/ #include<reg51.h> #include<7seg.h> /* 7 segment display decode data */ main() { while(1) { P1 = ZERO; /* To Display "0" in 7 segment display*/ delay(1000); /* 1 second time delay*/ P1 = ONE ; delay(1000); P1 = TWO; delay(1000); P1 = THREE; delay(1000); P1 = FOUR; delay(1000); P1 = FIVE; delay(1000); P1 = SIX; delay(1000); P1 = SEVEN; delay(1000); P1 = EIGHT; delay(1000); P1 = NINE; delay(1000); } } <strong>7seg.h </strong> #define #define #define ZERO ONE TWO 0x0C0 0x0F9 0x0A4
void delay(unsigned int ms); /* Function for delay routine */ void delayms(); /* function for 1 ms delay*/ void delay(unsigned int ms) { while(ms--) { delayms(); /* call the 1 ms delay function for multiple routine*/ } } void delayms() /* 1 ms delay function for 20MHz clock frequency - this Values are calculated using "TIME8051.exe". */ { _asm MOV R2,#4 MOV R1,#57 TT1: DJNZ R1,TT1 DJNZ R2,TT1 _endasm }
5.
WRITE_TEXT: SETB RS MOV DATA,A SETB EN CLR EN LCALL WAIT_LCD RET LCALL INIT_LCD LCALL CLEAR_LCD MOV A,#'H' LCALL WRITE_TEXT MOV A,#'E'
LCALL WRITE_TEXT MOV A,#'L' LCALL WRITE_TEXT MOV A,#'L' LCALL WRITE_TEXT MOV A,#'O' LCALL WRITE_TEXT MOV A,#' ' LCALL WRITE_TEXT MOV A,#'W' LCALL WRITE_TEXT MOV A,#'O' LCALL WRITE_TEXT MOV A,#'R' LCALL WRITE_TEXT MOV A,#'L' LCALL WRITE_TEXT MOV A,#'D' LCALL WRITE_TEXT END
Linux InternalsStarting Date: Completing Date: Topics covered: Inter process communication(IPC) Signals and signal handling. Processes Socket Pipes & named pipes. Semaphores Shared memory. Message queue. Programs.
Linux Internals:Linux Operating SystemLinux throughout the world.
Advantages of LinuxLow cost: There is no need to spend time and huge amount money to obtain licenses since Linux and much of its software come with the GNU General Public License. There is no need to worry about any software's that you use in Linux. Stability: Linux has high stability compared with other operating systems. There is no need to reboot the Linux system to maintain performance levels. Rarely it freeze up or slow down. It has a continuous up-times of hundreds of days or more. Performance: Linux provides high performance on various networks. It has the ability to handle large numbers of users simultaneously. Networking: Linux provides a strong support for network functionality; client and server systems can be easily set up on any computer running Linux. It can perform tasks like network backup more faster than other operating systems. Flexibility: Linux is very flexible. Linux can be used for high performance server applications, desktop applications, and embedded systems. You can install only the needed components for a particular use. You can also restrict the use of specific computers. Compatibility: It runs all common Unix software packages and can process all common file formats. Wider Choice: There is a large number of Linux distributions which gives you a wider choice. Each organization develop and support different distribution. You can pick the one you like best; the core function's are the same. Fast and easy installation: Linux distributions come with user-friendly installation.
Better use of hard disk: Linux uses its resources well enough even when the hard disk is almost full. Multitasking: Linux is a multitasking operating system. It can handle many things at the same time. Security: Linux is one of the most secure operating systems. File ownership and permissions make linux more secure. Open source: Linux is an Open source operating systems. You can easily get the source code for linux and edit it to develop your personal operating system. Today, Linux is widely used for both basic home and office uses. It is the main operating system used for high performance business and in web servers. Linux has made a high impact in this world. Inter process communication (IPC):: 1) SIGHUP 5) SIGTRAP 9) SIGKILL 13) SIGPIPE 18) SIGCONT 22) SIGTTOU 26) SIGVTALRM 30) SIGPWR 2) SIGINT 6) SIGIOT 10) SIGUSR1 14) SIGALRM 19) SIGSTOP 23) SIGURG 27) SIGPROF 3) SIGQUIT 7) SIGBUS 11) SIGSEGV 15) SIGTERM 20) SIGTSTP 24) SIGXCPU 28) SIGWINCH 4) SIGILL 8) SIGFPE 12) SIGUSR2 17) SIGCHLD 21) SIGTTIN 25) SIGXFSZ 29) SIGIO
PipesT which sets up these temporary pipes between the processes.
In Linux, a pipe is implemented using two file data structures which both point at the same temporary VFS inode which itself points at a physical page within memory.'s's woken by the reader when there is enough room for the write data or when the pipe is unlocked. When the data has been written, the pipe's VFS inode is unlocked and any waiting readers sleeping on the inode's wait queue will themselves be woken up. Reading data from the pipe is a very similar process to writing to it. Processes are allowed to do non-blocking reads (it depends on the mode in which they opened the file or pipe) and, in this case, if there is no data to be read or if the pipe is locked, an error will be returned. This means that the process can continue to run. The alternative is to wait on the pipe inode's wait queue until the write process has finished. When both processes have finished with the pipe, the pipe inode is discarded along with the shared data page.
SocketsSockets.
Diagram of client-server socket connection via xinetd. Note that the client communicates by reading and writing the socket, but the server program communicates via stdin and stdout..
System V IPC Mechanisms Linux supports three types of interprocess communication mechanisms that first appeared in Unix TM process's.
Message QueuesMessage queues allow one or more processes to write messages, which will be read by one or more reading processes. Linux maintains a list of message queues, the msgque vector; each element of which points to a msqid_ds data structure that fully describes the message queue. When message queues are created a new msqid_ds data structure is allocated from system memory and inserted into the vector. message's woken up when one or more messages have been read from this message queue.
Reading from the queue is a similar process. Again, the processes woken up and run again.
Sem woken and this time its attempt to increment the semaphore will succeed.sem mem-
bers woken. There is a problem with semaphores, deadlocks. These occur when one process has altered the semaphores's's's's task_struct but the semaphore array identifier is made invalid. In this case the semaphore clean up code simply discards the sem_undo data structure.
Shared Memory. They must rely on other mechanisms, for example System V semaphores, to synchronize access to the mem-
ory goes or it can let Linux choose a free area large enough. The new vm_area_struct structure is put into the list of vm_area_structpointed at by the shmid_ds. The vm_next_shared and vm_prev_shared pointers are used to link them together. The virtual memory is not actually created during the attach;. As well as going into the current process's page tables, this entry is saved in the shmid_ds. This means that used to share..
PROGRAMS:1. /*program using ipc.*/ #include<stdio.h> #include<sys/types.h> //#include "ourhdr.h" main() { int pid , status;
if((pid=fork()<0)) printf("fork error \n"); else if(pid==0) exit(7); if(wait(&status)!=pid) printf("wait error \n"); _exit(status); if((pid=fork()<0)) printf("fork error \n"); else if(pid==0) abort(); if(wait(&status)!=pid) printf("wait error \n"); _exit(status); if((pid=fork()<0)) printf("Fork error \n"); else if(pid==0) status/=0; if(wait(&status)!=pid) printf(" Wait error \n"); _exit(status); exit(0); }
2. /*A message queue program that shows a client server implementation this is the reciever program using Message Queues.*/ #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> struct my_msg_st { long int my_msg_type; char some_text[BUFSIZ]; }; int main(void) { int running = 1; int msgid;
struct my_msg_st some_data; long int msg_to_recieve = 0; /* Let us set up the message queue */ msgid = msgget((key_t)1234, 0666 | IPC_CREAT); if (msgid == -1) { perror("msgget failed with error"); exit(EXIT_FAILURE); } /* Then the messages are retrieved from the queue, until an end message is * encountered. lastly the message queue is deleted*/ while(running) { if (msgrcv(msgid, (void *)&some_data, BUFSIZ, msg_to_recieve, 0) == -1) { perror("msgcrv failed with error"); exit(EXIT_FAILURE); } printf("You wrote: %s", some_data.some_text); if (strncmp(some_data.some_text, "end", 3) == 0) { running = 0; } } if (msgctl(msgid, IPC_RMID, 0) == -1) { perror("msgctl(IPC_RMID) failed"); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); }
#include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #define KEY (1492) void main() { int id;
struct sembuf operations[1]; int retval; id = semget(KEY, 1, 0666); if(id < 0) { fprintf(stderr, "Program sema cannot find semaphore, exiting.\n"); exit(0); } /* Do a semaphore V-operation. */ printf("Program sema about to do a V-operation. \n");.\n"); } else { printf("sema: V-operation did not succeed.\n"); perror("REASON"); }
4./*Program using shared memory. */ () */ (void) fprintf(stderr, "All numeric input is expected to follow C conventions:\n"); (void) fprintf(stderr, "\t0x... is interpreted as hexadecimal,\n"); (void) fprintf(stderr, "\t0... is interpreted as octal,\n"); (void) fprintf(stderr, "\totherwise, decimal.\n"); /* Get the); (void) fprintf(stderr, "\towner read =\t%#8.8o\n", 0400); (void) fprintf(stderr, "\towner write =\t%#8.8o\n", 0200); (void) fprintf(stderr, "\tgroup read =\t%#8.8o\n", 040); (void) fprintf(stderr, "\tgroup write =\t%#8.8o\n", 020); (void) fprintf(stderr, "\tother read =\t%#8.8o\n", 04); (void) fprintf(stderr, "\tother write =\t%#8.8o\n", 02); (void) fprintf(stderr, "Enter shmflg: "); (void) scanf("%i", &shmflg); /* Make the call and report the results. */ (void) fprintf(stderr, "shmget: Calling shmget(%#lx, %d, %#o)\n",); } }
5. /* program using socket.*/ #include <stdio.h> #include <string.h> #include <netdb.h> #include <linux/in.h> #include <sys/socket.h> #include <unistd.h> #define buflen 512 unsigned int portno = 3333; char hostname[] = "192.168.100.2"; char *buf[buflen]; /* declare global to avoid stack */
void dia(char *sz) { printf("Dia %s\n", sz); } int printFromSocket(int sd, char *buf) { int len = buflen+1; int continueflag=1; while((len >= buflen)&&(continueflag)) /* quit b4 U read an empty socket */ { len = read(sd, buf, buflen); write(1,buf,len); buf[buflen-1]='\0'; /* Note bug if "Finished" ends the buffer */ continueflag=(strstr(buf, "Finished")==NULL); /* terminate if server says "Finished" */ } return(continueflag); }
main() { int sd = socket(AF_INET, SOCK_STREAM, 0); /* init socket descriptor */ struct sockaddr_in sin; struct hostent *host = gethostbyname(hostname); char buf[buflen]; int len; /*** PLACE DATA IN sockaddr_in struct ***/ memcpy(&sin.sin_addr.s_addr, host->h_addr, host->h_length); sin.sin_family = AF_INET; sin.sin_port = htons(portno); /*** CONNECT SOCKET TO THE SERVICE DESCRIBED BY sockaddr_in struct ***/ if (connect(sd, (struct sockaddr *)&sin, sizeof(sin)) < 0) { perror("connecting"); exit(1); } sleep(1); /* give server time to reply */ while(1) { printf("\n\n"); if(!printFromSocket(sd, buf)) break; fgets(buf, buflen, stdin); /* remember, fgets appends the newline */ write(sd, buf, strlen(buf)); sleep(1); /* give server time to reply */ } close(sd);
6. /* program using thread.*/ #include <stdio.h> #include <pthread.h> #include <stdlib.h> void * thread1() { while(1){ printf("Hello!!\n"); } } void * thread2() { while(1){
printf("How are you?\n"); } } int main() { int status; pthread_t tid1,tid2; pthread_create(&tid1,NULL,thread1,NULL); pthread_create(&tid2,NULL,thread2,NULL); pthread_join(tid1,NULL); pthread_join(tid2,NULL); return. | https://it.scribd.com/document/98854447/Synopsis | CC-MAIN-2020-45 | refinedweb | 6,110 | 56.15 |
Population Count
January 28, 2011
Scheme doesn’t have the concept of the size of a number, but if you are working in a language like C, you should consider finding the population count of integers of the native size for your machine.
We begin with the naive solution: index through the bits of the number, counting those that are set, using bit operations instead of arithmetic (
ash is arithmetic-shift, where a negative argument is a right-shift):
(define (pop-count n)
(let loop ((n n) (count 0))
(if (zero? n) count
(loop (ash n -1) (+ count (logand n 1))))))
If you have space available, you can count the bits k at a time instead of one at a time; here is the case for k=4, but you may wish to use k=8, or even k=32, which makes
pop-count a constant-time operation:
(define (pop-count n)
(let ((bits #(0 1 1 2 1 2 2 3 1 2 2 3 2 3 3 4)))
(let loop ((n n) (count 0))
(if (zero? n) count
(loop (ash n -4) (+ count (vector-ref bits (logand n #xF))))))))
If you know that the bitstring is sparse, it is faster to count only the 1-bits and ignore the 0-bits; this technique was described by Peter Wegner in 1960 (CACM, Volume 3, Number 5, May 1960, Page 322) and takes one loop per 1-bit instead of one loop per bit:
(define (pop-count n)
(let loop ((n n) (count 0))
(if (zero? n) count
(loop (logand n (- n 1)) (+ count 1)))))
Our last version comes from HAKMEM 169 by Bill Gosper and is specific to 32-bit unsigned integers; we’ll leave to you the pleasure of figuring out how it works:
(define (pop-count n)
(let ((count n))
(set! count (- count (logand (ash n -1) #o33333333333)))
(set! count (- count (logand (ash n -2) #o11111111111)))
(set! count (logand (+ count (ash count -3)) #o30707070707))
(modulo count 63)))
There are other ways to perform the population count; hopefully we’ll see some of the possibilities in the comments below.
We used the
ash and
logand operators from the Standard Prelude. You can run the program at.
My solution (Haskell):
[...] today’s Programming Praxis, our task is to count the active bits in a number. Let’s get started, [...]
My Haskell solution (see for a version with comments):
My Python versions, in increasing speed. The dictionary used in pop4 has been
abbreviated here, but the full version is available on.
(Note: I didn’t run this code on codepad, because it has some Python 2.6 or
greater specific features, e.g.
bin()and
format().)
Gosper’s algorithm, and many similar ones, can be found in “Hacker’s delight” by Henry Warren; it’s a great book!
Extending my lookup-in-dictionary
pop4to arbitrarily large unsigned integers:
While certainly not memory efficient, this is rather speedy for large numbers (especially with
repeated calls).
I`m a somewhat recent user of this website, but I just love it because it can help me improve my codes and thinking.
Here`s my somewhat naive solution:
/* Bruno Oliveira – This program determines the number of set-bits (1 bit) in a bitstring,
representing a decimal number. */
#include
#include
#include
using namespace std;
int hamming(unsigned long long int n)
{
vector v;
int res = 0;
while(n > 0)
{
v.push_back(n%2);
n = n/2;
}
for(int x = v.size()-1; x >= 0; x–)
{
if(v[x] == 1)
res++;
}
return res;
}
int main()
{
int s = hamming(23);
cout << s;
return 0;
}
;; Should work properly.
(define (make-bit-count table-size)
(let ((v (make-vector table-size)))
(let loop ((i 0))
(if (= table-size i)
(lambda (idx) (vector-ref v idx))
(begin
;; I know, I’m cheating here because I use gambit
;; But the table isn’t hard to compute and could even
;; be hard-coded.
(vector-set! v i (bit-count i))
(loop (+ i 1)))))))
(define (my-bit-count n #!optional (size 8))
(let* ((s (expt 2 size))
(b-c (make-bit-count s))
(t-s-b (- s 1)))
(let loop ((n n) (bc 0))
(if (> n t-s-b)
(loop (arithmetic-shift n (- size))
(+ bc (b-c (bitwise-and n t-s-b))))
(+ bc (b-c n))))))
I`d now like to ask, if any of you knows how to manipulate large integers in C++, without using any external libraries?
I`d like to perform only the 4 basic arithmetic operations on them: Sum, divide, subtract, multiply; I`d also like to assign them to variables and manipulate them as I do with normal integers.
Hope that it`s okay to ask it here ;)
Thanks in advance,
Bruno
This work?
Groovy(/Java):
def getPop(num) {
def pop = rem = 0
while(num != 0) {
(num,rem) = num.divideAndRemainder(2)
pop += rem
}
return pop
}
println “Enter a number: ”
def num = null
System.in.withReader {
num = it.readLine()
}
assert num.isBigInteger()
println “Population is: ${getPop(num.toBigInteger())}”
[...] Little bit of J language fun at programmingpraxis: [...]
def hamming_weight(number):
“””docstring for get_bit_string_pop_count”””
count = 0
if number == 1:
return 1
elif number == 0:
return 0
count += hamming_weight(number/2)
count += number % 2
return count
#include
#include
long int hamming(long a)
{long n=a;
const long int m1= 0x55555555;
const long int m2=0x33333333;
const long int m4=0x0f0f0f0f;
const long int m8=0x00ff00ff;
const long int m16=0x0000ffff;
n=(n+(n>>1))&m1;
n=(n+(n>>2))&m2;
n=(n+(n>>4))&m4;
n=(n+(n>>8))&m8;
n=(n+(n>>16))&m16;
return n;
}
int main()
{
long int n;
printf(“%ld”,hamming(100));
getch();
return 0;
}
Simple C function:
int pop_count (unsigned bitstring){
int i;
int population_count = 0;
for (i=0; i> 1)){
if (bitstring & 0x1){
population_count ++;
}
}
return population_count;
}
hello ramakrishna
can you please give full function with main()
Sorry.. for some reason it “paste didn’t work properly.
The function with a sample main is below:
int pop_count (unsigned);
int pop_count (unsigned bitstring){
int i;
int population_count = 0;
for(i=0;i> 1;
}
return population_count;
}
int main () {
unsigned input = 0xf3f3;
unsigned result = 0;
result = pop_count(input);
printf(“\n population count is %d”, result);
return 1;
}
It seems I need to paste html.
Link to code is as below
In Python:
Sorry, It ostensibly is supposed to be “return i”, not “return n”.
great cemper you are awesome ,what a great post.
My try in REXX
Solution in C:
#include
int population(int num)
{
int pop = 0;
while (num)
{
++pop;
num &= (num – 1);
}
return pop;
}
int main(int argc, char *argv[])
{
int num;
printf(“Enter val:”);
scanf(“%d”, &num);
printf(“Population of %d = %d\n”, num, population(num));
}
good answer siva
#
My implementation on C++ :
–
— Haskell popCount that can handle very large integers. The one above uses logbase which converts n to a float
— and hence cannot handle bignum integers larger than 2^2048.
—
—
module Main (main) where
import Data.Bits
import Data.Word
import Data.List
two30 = 1073741824 — 2^30
—
— Count the one bits in the binary representation of a 32 bit int
—
ones :: Word32 -> Word32
ones n =
case n – ((n `shiftR` 1) .&. 0x55555555) of
x -> case (x .&. 0x33333333) + ((x `shiftR` 2) .&. 0x33333333) of
y -> case (y + (y `shiftR` 4)) .&. 0x0F0F0F0F of
z -> case z + (z `shiftR` 8) of
a -> case a + (a `shiftR` 16) of
b -> b .&. 0x3F
—
— Get all the one bits sets for an bignum Integer
—
allOnes::Integer->Integer
allOnes b = sum ( allOneList b )
—
— From a bignum Integer, get a list of Integers [Integer]
allOneList b | b == 0 = []
allOneList b = [ fromIntegral (ones ( fromIntegral ( b `mod` two30 ))) ] ++ allOneList (b `shiftR` 30)
main = print $ show $ allOnes ((2^131)-1)
FORTH version | http://programmingpraxis.com/2011/01/28/population-count/2/ | CC-MAIN-2014-42 | refinedweb | 1,276 | 66.27 |
[solved] Touch Screen Corsi Task - Borrowing a little code!!
Hi I have recently begun my PhD and I'm quite new to programming / code etc. I used the below piece of code which I found in another stream as I am developing what I hope will be a touch screen Corsi task. In this participants are required to watch a block sequence and then tap this out on screen in the same order. Sequence lengths vary from 2 to 9. I'm doing it forwards and then backwards, harder than it sounds believe me.
Therefore I need opensesame to regcognise a touch response within the square and not anywhere else on screen and then log the co-ordinate of the touch. To be more specific I need it to do this for each tough, so if the sequence is 5 blocks long, I need SPSS to record 5 taps, whether correct / incorrect and coordinates. I also want reaction time but I'm not sure if this is a later question I might have to post. I used the below code therefore and I think I have it working, of sorts, but I was just wondering if anyone knew, for write up / understanding purposes how exactly the code calculates acceptable distance, how far is too far in essense from the square to be considered correct? I'm sorry if this is completely out of context from the original post as well, I'm relatively new to forums also.
Thank you , Katherine.
from math import sqrt # The maximum error from the target center maxClickErr = 100 # Use Pythagoras to determine the click error and set # the variable `correct` to 1 (correct) or 0 (incorrect) # depending on whether the click error is small enough. # Because the cursor coordinates have 0,0 at the top-left # and the sketchpad coordinates have 0,0 at the center, # we need to compensate for the display size. xc = self.get('width') / 2 yc = self.get('height') / 2 # Determine x and y error dx = self.get('cursor_x')- xc - self.get('xTarget') dy = self.get('cursor_y')- yc - self.get('yTarget') # Determine error clickErr = sqrt(dx**2 + dy**2) # Determine `correct` variable if clickErr <= maxClickErr: exp.set('correct', 1) else: exp.set('correct', 0)
Hi Katherine,
Welcome to the forum!
The variable
maxClickErrin this script indicates the maximum distance in pixels that a touch can be from a specific target point, indicated by
xTargetand
yTarget. So the acceptable area is a circle around the target point with a radius of
maxClickErrpixels.
Does that answer your question?
Cheers,
Sebastiaan
There's much bigger issues in the world, I know. But I first have to take care of the world I know.
cogsci.nl/smathot
Thank you, yes of sorts, I think my problem is that I've used this code thinking it would be appropriate for my task. Basically the corsi blocks task uses squares as targets. To this extent I've used the above code so that now it draws an acceptable target circle around the square which is largely fine as the margin for error is so small outside of the target, but is there a way that I could adapt the above code specifically for squares?
Thank you,
Katherine.
Hi Katherina,
Sure, the
dxand
dyvariables indicate respectively the horizontal and vertical deviation from the target center. So defining an acceptable square would be something like this:
Update: Corrected script
Cheers,
Sebastiaan
There's much bigger issues in the world, I know. But I first have to take care of the world I know.
cogsci.nl/smathot
Hi Sebastiann,
thank you for your help so far. I now might need a little more though, I've changed my design slightly so that it uses rectangles as stimuli which are 151 x 117 pixels in size and like before I need them to be targets for the touchscreen version. I'm currently trying to adapt the first piece of code on this thread to use rectangles, trying to work it out considering that you explained how I would make it relevant for squares. However I am yet as able to do that. I was wondering if you would be able to give me the full code for using rectangles as targets? Would I need to remove the square root part of the original code in this thread?
Sorry,
Thank you,
Katherine x
Hi Katherine,
I now notice that there is a mistake in my previous post. You should not compare
clickErragainst the horizontal (
dx) and vertical (
dy) deviation, but
maxClickErr. And if you want to use a rectangle instead of a square, you need to use different maximum errors for the horizontal and vertical. For example like so:
Update: Corrected script
So you basically just check if the horizontal and vertical deviation are smaller than or equal to the maximum click error. Pretty straightforward, really. Does that make sense?
Cheers,
Sebastiaan
There's much bigger issues in the world, I know. But I first have to take care of the world I know.
cogsci.nl/smathot
Hi Sebastiaan,
thank you for your help, I pasted that code in t replace what I had before and changed the 115 to 151 because that's the width of my rectangle, but it now isn't registering any clicks as correct at all. I'm not sure why. No matter how close to the centre the results just keep registering 0 correct. I will continue to have a look at this, any ideas though?
Thank you again for your help,
Katherine.
Also what does abs stand for? The rest I think I understand. Thank you, Katherine.
Wait I think I may have done it, the arrows should be the other way around? >=abs(dx)?
thankyou
Hi Katherine,
The function
abs()is to calculate the absolute value of a number. This is defined as the square root of the square of the original number, which basically comes down to the same number as you put in, but without the minus sign. Examples:
abs(3) == 3, and
abs(-3) == 3
.
It seems the "smaller than or equal" sign should have indeed been a "greater than or equal". Sorry about that!
Oops 8-}
There's much bigger issues in the world, I know. But I first have to take care of the world I know.
cogsci.nl/smathot
Its o.k, thank you both lots, you've been a massive help and I think I'm one step closer now to understanding programming, she sais
. . I think I finally have my Corsi task up and running though, stopping rule and touch screen response working, thank you. I will spread the word!!!!
thanks, kat x | http://forum.cogsci.nl/index.php?p=/discussion/758/solved-touch-screen-corsi-task-borrowing-a-little-code | CC-MAIN-2019-09 | refinedweb | 1,117 | 72.76 |
Use Stopwatch to Measure Code Execution Time
One of the most common tasks when analyzing performance and optimizing code is measuring the time it takes to execute the code in question. Before .NET 2.0 you had to develop your own high resolution timer for the job by wrapping the unmanaged calls to
QueryPerformanceCounter and
QueryPerformanceFrequency.
I kept using the same class in .NET 2.0 but just the other day I stumbled across the
Stopwatch class in the
System.Diagnostics namespace. It implements the same high resolution timer functionality out of the box, so there's no need to use unmanaged calls to achieve it anymore.
And the basic usage couldn't be simpler:
using System.Diagnostics; // ... Stopwatch sw = new Stopwatch(); sw.Start(); // do some processing here sw.Stop(); Debug.WriteLine("Time elapsed:" + sw.ElapsedMilliseconds.ToString());
One wonders what other hidden treasures lie in the class library yet to be discovered. | http://www.damirscorner.com/blog/posts/20060228-UseStopwatchToMeasureCodeExecutionTime.html | CC-MAIN-2018-51 | refinedweb | 152 | 57.27 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.