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
The Dow’s new high Rally drivers There’s froth in the equity markets, but not a bubble IT SEEMS like a moment for uncorking, if not a vintage champagne, then a nice bottle of Californian pinot noir. The Dow Jones Industrial Average, America’s most-cited equity benchmark, has finally surpassed the high it reached back in October 2007. Other developed-world stockmarkets have been surging too; Tokyo has managed a double-digit gain this year. Wall Street’s rally is caused only partly by the performance of the domestic economy, which is forecast to grow by a modest 2.0% this year. Since March 2009 the Dow has more than doubled while the American economy has grown by a cumulative 7% in real terms. Over the same period, the Chinese economy has grown by 41% but the Shanghai stockmarket is less than half its 2007 peak. The equity markets have been booming as a result of a deliberate strategy of central banks: by forcing down bond yields, they hope to persuade investors to buy risky assets and thus restore confidence to both businesses and consumers. In much of the developed world, therefore, government bond yields are close to record lows despite the high levels of public debt, while investors get a negative return (after inflation) from holding cash. Equities look like the best bet. The central banks are pursuing the right policy for a weak world economy, but it has risks. When central banks intervene to boost confidence, they are in danger of encouraging excessive risk-taking—as they did through the long bull market of the 1980s and 1990s. This time round, there are some tentative signs of excessive exuberance in the credit markets, as Jeremy Stein, a Federal Reserve governor, noted in a thoughtful speech last month (see Buttonwood). The kind of high-risk securities that marked the credit bubble are starting to reappear. And there are reasons to worry that stocks may be overvalued. American companies’ profits—thanks to their booming overseas subsidiaries—are at a post-1945 high relative to GDP. That suggests it will be difficult for them to rise much further. And indeed, profits growth has been slowing in recent months. For the current quarter, ending March 31st, profits of S&P 500 companies are expected to be only 1.2% higher than the previous year—and only 0.1% if financial companies are excluded from the total. All that leaves American shares looking off-puttingly expensive, with valuations around 40-50% above the long-term average (see article). As yet, however, the excesses are not on the scale of the last two bull markets; indeed, the American public is only just regaining its appetite for equity mutual funds. So central banks can be excused for sitting back and enjoying the bull run, especially as any action they could plausibly take to halt it would damage a still-fragile economy. A different paradox of thrift Nevertheless, equity investors should keep a level head. In particular, American pension funds should be aware that, with bond yields low and equity valuations high, future investment returns are likely to be low. They need to contribute more if pension deficits are to be reduced. Similarly, employees who are responsible for their own pensions via plans such as 401(k)s need to stump up more if they are to retire in comfort. But here is the paradox. To rescue economies from the doldrums, central banks want companies and employees to save less in the short term, not more. Balancing the desire for short-term consumption and the need for long-term thrift is one of the trickiest issues for rich countries as they navigate their way out of the crisis. Perhaps the Dow will resolve that paradox by continuing to soar. More likely, it will not. From the print edition: Leaders Excerpts from the print edition & blogs » Editor's Highlights, The World This Week, and more »
http://www.economist.com/news/leaders/21573123-theres-froth-equity-markets-not-bubble-rally-drivers
CC-MAIN-2014-35
refinedweb
660
61.06
Can I run one or more of the Solaris hosts in the cluster as highly available NFS servers with other Solaris hosts host. The cluster file system caches files in more cases than does NFS. For example, the cluster file system caches files when a file is being accessed from multiple nodes for read, write, file locks, asynchronous I/O. The cluster file system is built to exploit future fast cluster interconnects that provide remote DMA and zero-copy functions. If you change the attributes on a file (using chmod, systems are not intended for general use. While they are global, these file systems are never accessed in a global manner. Each node only accesses its own global device namespace. If a node is down, other nodes cannot access this namespace for the node that is down. These file systems are not highly available. These file systems should not be used to store data that needs to be globally accessible or highly available.
http://docs.oracle.com/cd/E19575-01/821-0259/cbadbfei/index.html
CC-MAIN-2017-04
refinedweb
163
72.05
# Python3 program to find largest subtree # sum in a given binary tree. # Function to create new tree node. class newNode: def __init__(self, key): self.key = key self.left = self.right = None # Helper function to find largest # subtree sum recursively. def findLargestSubtreeSumUtil(root, ans): # If current node is None then # return 0 to parent node. if (root == None): return 0 # Subtree sum rooted at current node. currSum = (root.key + findLargestSubtreeSumUtil(root.left, ans) + findLargestSubtreeSumUtil(root.right, ans)) # Update answer if current subtree # sum is greater than answer so far. ans[0] = max(ans[0], currSum) # Return current subtree sum to # its parent node. return currSum # Function to find largest subtree sum. def findLargestSubtreeSum(root): # If tree does not exist, # then answer is 0. if (root == None): return 0 # Variable to store maximum subtree sum. ans = [-999999999999] # Call to recursive function to # find maximum subtree sum. findLargestSubtreeSumUtil(root, ans) return ans[0] # Driver Code if __name__ == ‘__main__’: # # 1 # / # / # -2 3 # / / # / / # 4 5 -6 2 root = newNode(1) root.left = newNode(-2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.left = newNode(-6) root.right.right = newNode(2) print(findLargestSubtreeSum(root)) # This code is contributed by PranchalK C# 7 Time Complexity: O(n), where n is number of nodes. Auxiliary Space: O(n), function call stack size.
https://tutorialspoint.dev/data-structure/binary-tree-data-structure/find-largest-subtree-sum-tree
CC-MAIN-2020-16
refinedweb
223
62.85
Custom ComponentsSeglespaan Apr 23, 2009 1:33 PM Hi, Say i have a flex application called a.mxml and inside the components folder i have a component called b.mxml a.mxml containts a textInput box called input, and b contains a textArea called echoInput. how do I get echoInput to have the same value as Input. I've tried this but to no avail <mx:TextArea I have set up my namespace as follows xmlns:comp="components.*" and the component is recognised within the main app, but just can't seem to get it to work! Cheers 1. Re: Custom ComponentsSeglespaan Apr 23, 2009 1:36 PM (in response to Seglespaan) while I'm at it, if i have ten combo boxes populated by ten different arrays, can I save all my arrays in an arrays file and still use them as data providers for comboboxes within my components! spot the newb! lol 2. Re: Custom ComponentsMichael Borbor Apr 23, 2009 1:43 PM (in response to Seglespaan) Lets say you add your component to your main app and do this <comps:b <mx:TextArea Yes you can store in a single file all your arrays and use them at your discretion 3. Re: Custom ComponentsSeglespaan Apr 23, 2009 2:01 PM (in response to Michael Borbor) when u put it like that is seems so easy, and well it makes alot more sense, as you may have 20 of the same component on screen each with different ids thus being able to manipulate 20 different other things. Rather than my train of thought in which the component would always only effect one thing! Awesome. As for the arrays, is it essentially identical? i.e. have a component called arrays, in which theres 5 arrays with different ids, then in the main app I have to use <comp:array1 then use dataprovider = {array1} is that the best way of doing it, is there another way that doesn't require you to add the array to the main app? 4. Re: Custom ComponentsMichael Borbor Apr 23, 2009 2:11 PM (in response to Seglespaan) I'll say that it'll be better if you create an actionscript file with all your arrays and the import that actionscript file into your main app or components. 5. Re: Custom ComponentsSeglespaan Apr 23, 2009 2:43 PM (in response to Michael Borbor) Cheers, thanks for you help 6. Re: Custom ComponentsMichael Borbor Apr 23, 2009 2:47 PM (in response to Seglespaan) You're welcome, glad I was able to help. Please don't forget to close the thread. 7. Re: Custom Componentsntsiii Apr 23, 2009 4:04 PM (in response to Michael Borbor) This might be a good place to step in with the suggestion to look into using a data model. Rather than wirirng individual ui components to each other, you woulod have a central location, a component, where you keep all of your shared data elements. You make that class or the individual properties [Bindable] and then bind you UI elements to the appropriate property. Often the "singleton" pattern is used for this. I find it very useful and easy to work with. So in component "b", yo might write: ...text="{MyModel.getInstance().mySharedData}" 8. Re: Custom ComponentsSeglespaan Apr 23, 2009 4:12 PM (in response to ntsiii) Ok, so from what you've said ntsiii, rather than creating ten custom components I create one large component that contains the ten. Obviously the point of creating components in the first place is to be able to re-use the component over and over withought having to recode it. but for large projects would this method not get rather messy, and lead to an absolutley massive central location file. Is this method faster? less resource hungry?? 9. Re: Custom Componentsntsiii Apr 23, 2009 4:24 PM (in response to Seglespaan) You have a single model component for *shared* or global data, that is data that need to be read or written from different places in your application. You still code you UI elements however you wish. The benefit is maintainability. If your data is stored in a model, and you later add a component that needs to access that data, you will know where it is. further if you find you need to "clear" that data, or modify it from somewhere not forseen, like on log-out, then you can simply set the data in the model and all ui elements will reflect it. 10. Re: Custom ComponentsSeglespaan Apr 23, 2009 4:45 PM (in response to ntsiii) so essentially this is what michael suggeted in his second last post with the actionscript file, thus if I wanted to populate a comboBox from a table in a database, a section of the data Model would collect this data which i could then use within my application, rather than having to collect this data each time i wanted to use it i would just reference that part of my data model?
https://forums.adobe.com/thread/423657
CC-MAIN-2017-30
refinedweb
839
64.44
Like. The key process in quickSort. Pseudo Code for recursive QuickSort function : /* } } Partition Algorithm There can be many ways to do partition, following pseudo code adopts the method given in CLRS book. The logic is simple, we start from the leftmost element and keep track of index of smaller (or equal to) elements as i. While traversing, if we find a smaller element, we swap current element with arr[i]. Otherwise we ignore current element. /* } } Pseudo code for partition() /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ partition (arr[], low, high) { // pivot (Element to be placed at right position) pivot = arr[high]; i = (low - 1) // Index of smaller element for (j = low; j <= high- 1; j++) { // If current element is smaller than or // equal to pivot if (arr[j] <= pivot) { i++; // increment index of smaller element swap arr[i] and arr[j] } } swap arr[i + 1] and arr[high]) return (i + 1) } Illustration of partition() : arr[] = {10, 80, 30, 90, 40, 50, 70} Indexes: 0 1 2 3 4 5 6 low = 0, high = 6, pivot = arr[h] = 70 Initialize index of smaller element, i = -1 Traverse elements from j = low to high-1 j = 0 : Since arr[j] <= pivot, do i++ and swap(arr[i], arr[j]) i = 0 arr[] = {10, 80, 30, 90, 40, 50, 70} // No change as i and j // are same j = 1 : Since arr[j] > pivot, do nothing // No change in i and arr[] j = 2 : Since arr[j] <= pivot, do i++ and swap(arr[i], arr[j]) i = 1 arr[] = {10, 30, 80, 90, 40, 50, 70} // We swap 80 and 30 j = 3 : Since arr[j] > pivot, do nothing // No change in i and arr[] j = 4 : Since arr[j] <= pivot, do i++ and swap(arr[i], arr[j]) i = 2 arr[] = {10, 30, 40, 90, 80, 50, 70} // 80 and 40 Swapped j = 5 : Since arr[j] <= pivot, do i++ and swap arr[i] with arr[j] i = 3 arr[] = {10, 30, 40, 50, 80, 90, 70} // 90 and 50 Swapped We come out of loop because j is now equal to high-1. Finally we place pivot at correct position by swapping arr[i+1] and arr[high] (or pivot) arr[] = {10, 30, 40, 50, 70, 90, 80} // 80 and 70 Swapped Now 70 is at its correct place. All elements smaller than 70 are before it and all elements greater than 70 are after it. Implementation: Following are C++, Java and Python implementations of QuickSort. C/C++ Java Python C# Output: Sorted array: 1 5 7 8 9 10 Analysis of QuickSort Time taken by QuickSort in general can be written as following. T(n) = T(k) + T(n-k-1) + (n)(n) The first two terms are for two recursive calls, the last term is for the partition process. k is the number of elements which are smaller than pivot. The time taken by QuickSort). It can be solved using case 2 of Master Theorem.) Although the worst case time complexity of QuickSort is O(n2) which is more than many other sorting algorithms like Merge Sort and Heap Sort, QuickSort is faster in practice, because its inner loop can be efficiently implemented on most architectures, and in most real-world data. QuickSort can be implemented in different ways by changing the choice of pivot, so that the worst case rarely occurs for a given type of data. However, merge sort is generally considered better when data is huge and stored in external storage. Is QuickSort stable? The default implementation is not stable. However any sorting algorithm can be made stable by considering indexes as comparison parameter. Is QuickSort In-place? As per the broad definition of in-place algorithm it qualifies as an in-place sorting algorithm as it uses extra space only for storing recursive function calls but not for manipulating the input. What is 3-Way QuickSort? recursively process remaining occurrences. In 3 Way QuickSort, an array arr[l..r] is divided in 3 parts: a) arr[l..i] elements less than pivot. b) arr[i+1..j-1] elements equal to pivot. c) arr[j..r] elements greater than pivot. See this for implementation. How to implement QuickSort for Linked Lists? QuickSort on Singly Linked List QuickSort on Doubly Linked List Can we implement QuickSort Iteratively? Yes, please refer Iterative Quick Sort. Why Quick Sort is preferred over MergeSort for sorting MergeSort is preferred over QuickSort for Linked Lists?. How to optimize QuickSort so that it takes O(Log n) extra space in worst case? Please see QuickSort Tail Call Optimization (Reducing worst case space to Log n ) References: Other Sorting Algorithms on GeeksforGeeks/GeeksQuiz: Selection Sort, Bubble Sort, Insertion Sort, Merge Sort, Heap Sort, QuickSort, Radix Sort, Counting Sort, Bucket Sort, ShellSort, Comb Sort, Pigeonhole Sort Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
https://tutorialspoint.dev/language/c-and-cpp-programs/quick-sort
CC-MAIN-2021-25
refinedweb
852
57.5
Hello. I have a task and I need programming a small program like this; The program will count in a string text area how many used the same word. Example text " A dog run out of home.When dog... Type: Posts; User: mockingbird Hello. I have a task and I need programming a small program like this; The program will count in a string text area how many used the same word. Example text " A dog run out of home.When dog... Norm thank u too much problem has been solved. Decompiler error all is this Here I did like u wrote anArray[row][column] = inputUser.nextInt(); But it doesnt work. On this 14. line there is error as But already above of the code I definited it as int. Okay here the full code. import java.util.Scanner; public class keke { public static void main(String[] args) { Scanner inputUser = new Scanner(System.in); int theSize = 3; I begin to understand somethings there is written "anArray" is not an Array.I wrote [] too but dont know why.Code and error below. import java.util.Scanner; public class inversematrix{... Code and explains are below. int theSize = <inputUser>; */ Multiple markers at this line - Syntax error on token(s), misplaced I puted your code but I got error cause of I did something wrong I think. You said " define int array with thesize number of elements" but already I want the size is will be depend to that matrix... Okay I edited my post.So int theSize = <inputUser>; ... // this part is what I didnt get int[] anArray = new int[theSize]; will be like this? Could you explain some more ? Hello. I have a inverse matrix task.Teacher said us that we have to create little a program which is finds inverse of the matrix which is given in code. I did something like this and when I gave...
http://www.javaprogrammingforums.com/search.php?s=c7cc92091e9741639f3ce84692896a15&searchid=1665923
CC-MAIN-2015-32
refinedweb
315
76.82
avg_pool1d¶ - paddle.nn.functional. avg_pool1d ( x, kernel_size, stride=None, padding=0, exclusive=True, ceil_mode=False, name=None ) [source] This API implements average pooling 1d operation, See more details in api_nn_pooling_AvgPool1d . - Parameters x (Tensor) – The input tensor of pooling operator which is a 3-D tensor with shape [N, C, L]. where N is batch size, C is the number of channels, L is the length of the feature. The data type is float32 or float64. kernel_size (int|list|tuple) – The pool kernel size. If pool kernel size is a tuple or list, it must contain an integer. stride (int|list|tuple) – The pool stride size. If pool stride size is a tuple or list, it must contain an integer. padding (string|int|list|tuple) – 1, which means the feature map is zero padded by the size of padding[0] on every sides. 4. A list[int] or tuple(int) whose length is 2. It has the form [pad_before, pad_after]. 5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], …]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0). The default value is 0. exclusive (bool) – Whether to exclude padding points in average pooling mode, default is True. ceil_mode (bool) – ${ceil_mode_comment}Whether to use the ceil function to calculate output height and width. If it is set to False, the floor function will be used. The default value is False. name (str, optional) – For detailed information, please refer to Name. Usually name is no need to set and None by default. - Returns The output tensor of pooling result. The data type is same as input tensor. - Return type Tensor - Raises ValueError – If padding is a string, but not “SAME” or “VALID”. ValueError – If padding is “VALID”, but ceil_mode is True. ValueError – If padding is a list or tuple but its length is greater than 1. ShapeError – If the input is not a 3-D tensor. ShapeError – If the output’s shape calculated is not greater than 0. Examples import paddle import paddle.nn.functional as F import numpy as np data = paddle.to_tensor(np.random.uniform(-1, 1, [1, 3, 32]).astype(np.float32)) out = F.avg_pool1d(data, kernel_size=2, stride=2, padding=0) # out shape: [1, 3, 16]
https://www.paddlepaddle.org.cn/documentation/docs/en/api/paddle/nn/functional/avg_pool1d_en.html
CC-MAIN-2022-05
refinedweb
381
69.38
Previous Versions of ASP.NET Previous versions of ASP.NET supported two types of routing: convention-based routing and attribute-based routing. When using convention-based routing, you could define your routes in your application RouteConfig.cs file like this: public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } The code above defines a Default route that maps a request like “/products/details” to the ProductsController.Details() action. ASP.NET MVC 5 introduced support for attribute-based routing. The primary advantage of attribute-based routing is that it allowed you to define your routes in the same file as your controller. For example, here’s an example of creating a ProductsController that includes both a [RoutePrefix] and [Route] attribute used for routing: [RoutePrefix("Products")] public class ProductsController : Controller { [Route("Index")] public ActionResult Index() { return View(); } } Regardless of whether you used convention-based routing or attribute-based routing, all of your routes ended up in a static collection located at RouteTable.Routes. If you used the ASP.NET Web API then routing worked in a similar way. You could define convention-based routes in the WebApiConfig.cs file and add attribute-based routes to your Web API controller classes. However, there were two important differences between routing in MVC and the Web API. First, the Web API supported RESTful routes by default. If you gave a Web API controller action a name that started with Get, Post, Put, Delete then you could invoke the action by performing an HTTP GET, POST, PUT, or DELETE request. For example, you could invoke a Web API action named PostMovie() simply by performing an HTTP POST. The other important difference between MVC and the Web API was subtler. Behind the scenes, MVC and the Web API did not share the same routing framework. Routing in MVC and the Web API followed similar patterns, but routing was implemented with different code (originally written by different Microsoft teams). Everything in ASP.NET 5 and MVC 6 has been rewritten from the ground up. This includes the routing framework used by both MVC and the Web API. There are several important changes to routing that I discuss in this blog post. First, in ASP.NET 5, there is no longer a distinction between MVC and Web API controllers. Both MVC and Web API controllers derive from the very same Controller base class. This means that the same routing framework is used for both MVC and the Web API. With ASP.NET 5, anything that is true of routing for MVC is also true for the Web API. Second, unlike earlier versions of MVC, default routes are created for you automatically. You don’t need to configure anything to route a request to a controller action. A set of default routes is created for you automatically. Third and finally, in MVC 6, you are provided with a rich set of inline constraints and parameter options that you can use with both convention-based and attributed-based routing. For example, you can constrain the data type of your route parameters, mark a parameter as optional, and provide default values for your parameters right within your route templates. Creating Routes Let’s start with the very basics. I’m going to show you the minimal amount of code that you need to use routing in an ASP.NET 5 application. I won’t even assume that you are using MVC. Here’s my Startup class: using System; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.AspNet.Routing; using Microsoft.AspNet.Routing.Template; using Microsoft.Framework.DependencyInjection; namespace RoutePlay { public class Startup { public void Configure(IApplicationBuilder app) { RouteCollection routes = new RouteCollection(); routes.Add(new TemplateRoute(new DebuggerRouteHandler("RouteHandlerA"), "test/{a}/{b}", null)); routes.Add(new TemplateRoute(new DebuggerRouteHandler("RouteHandlerB"), "test2", null)); app.UseRouter(routes); } } } In the code above, I’ve created a Configure() method that I use to configure routing. I create a Route collection that contains two routes. Finally, I pass the Route collection to the ApplicationBuilder.UseRouter() method to enable the routes. The routes are created with the TemplateRoute class. The TemplateRoute class is initialized with a Route Handler and a URL template. The first route – named RouteHandlerA — matches URLs with the pattern “test/{a}/{b}” and the second route – named RouteHandlerB – matches URLs with the pattern “test2”. The essence of routing is mapping an incoming browser request to a Route Handler. In the code above, requests are mapped to a custom handler that I created named DebuggerRouteHandler. Here’s the code for the DebuggerRouteHandler: using Microsoft.AspNet.Http; using Microsoft.AspNet.Routing; using System; using System.Threading.Tasks; namespace RoutePlay { public class DebuggerRouteHandler : IRouter { private string _name; public DebuggerRouteHandler(string name) { _name = name; } public string GetVirtualPath(VirtualPathContext context) { throw new NotImplementedException(); } public async Task RouteAsync(RouteContext context) { var routeValues = string.Join("", context.RouteData.Values); var message = String.Format("{0} Values={1} ", _name, routeValues); await context.HttpContext.Response.WriteAsync(message); context.IsHandled = true; } } } The DebuggerRouteHandler simply displays the name of the route and any route values extracted from the URL template. For example, if you enter the URL “test/apple/orange” into the address bar of your browser then you get the following response: Creating Routes with MVC 6 When using MVC 6, you don’t create your Route collection yourself. Instead, you let MVC create the route collection for you. Here’s a Startup class that is configured to use MVC 6: used to register MVC with the Dependency Injection framework built into ASP.NET 5. The Configure() method is used to register MVC with OWIN. Here’s what my MVC 6 ProductsController looks like: using Microsoft.AspNet.Mvc; namespace RoutePlay.Controllers { public class ProductsController : Controller { public IActionResult Index() { return Content("It Works!"); } } } Notice that I have not configured any routes. I have not used either convention-based or attribute-based routing, but I don’t need to do this. If I enter the request “/products/index” into my browser address bar then I get the response “It Works!”: When you call ApplicationBuilder.UseMvc() in the Startup class, the MVC framework adds routes for you automatically. Here. Thank you CreateAttributeMegaRoute() — you are going to save me tons of work! Convention-Based Routing You can use convention-based routing with ASP.NET MVC 5 by defining the routes in your project’s Startup class. For example, here is how you would map the requests /Super and /Awesome to the ProductsController.Index() action:" } ); }); } } } If you squint your eyes really hard then the code above in the Configure() method for setting up the routes looks similar to the code in a RouteConfig.cs file. Attribute-Based Routing You also can use attribute-based routing with MVC 6. Here’s how you can modify the ProductsController Index() action so you can invoke it with the “/Things/All” request: using Microsoft.AspNet.Mvc; namespace RoutePlay.Controllers { [Route("Things")] public class ProductsController : Controller { [Route("All")] public IActionResult Index() { return Content("It Works!"); } } } Notice that both the ProductsController class and the Index() action are decorated with a [Route] attribute. The combination of the two attributes enables you to invoke the Index() method by requesting “/Things/All”. Here’s what a Web API controller looks like in MVC 6: using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNet.Mvc; namespace RoutePlay.Controllers.Api.Controllers { [Route("api/[controller]")] public class Movies) { } } } Notice that a Web API controller, just like an MVC controller, derives from the base Controller class. That’s because there is no difference between a Web API controller and MVC controller in MVC 6 – they are the exact same thing. You also should notice that the Web API controller in the code above is decorated with a [Route] attribute that enables you to invoke the Movies controller with the request “/api/movies”. The special [controller] and [action] tokens are new to MVC 6 and they allow you to easily refer to the controller and action names in your route templates. If you mix convention-based and attribute-based routing then attribute-based routing wins. Furthermore, both convention-based and attribute-based routing win over the default routes. Creating Restful Routes You can use RESTful style routing with both MVC and Web API controllers. Consider the following controller (a mixed MVC and Web API controller): using Microsoft.AspNet.Mvc; using Microsoft.AspNet.WebUtilities.Collections; namespace RoutePlay.Controllers { [Route("[controller]")] public class MyController : Controller { // GET: /my/show [HttpGet("Show")] public IActionResult Show() { return View(); } // GET: /my [HttpGet] public IActionResult Get() { return Content("Get Invoked"); } // POST: /my [HttpPost] public IActionResult Post() { return Content("Post Invoked"); } // POST: /my/stuff [HttpPost("Stuff")] public IActionResult Post([FromBody]string firstName) { return Content("Post Stuff Invoked"); } } } The MyController has the following four actions: - Show() – Invoked with an HTTP GET request for “/my/show” - Get() – Invoked with an HTTP GET request for “/my” - Post() – Invoked with an HTTP POST request for “/my” - Post([fromBody]string firstName) – Invoked with an HTTP POST request for “/my/stuff” Notice that the controller is decorated with a [Route(“[controller]”)] attribute and each action is decorated with a [HttpGet] or [HttpPost] attribute. If you just use the [HttpPost] attribute on an action then you can invoke the action without using the action name (for example, “/my”). If you use an attribute such as [HttpPost(“stuff”)] that includes a template parameter then you must include the action name when invoking the action (for example, “/my/stuff”). The Show() action returns the following view: <p> <a href="/my">GET</a> </p> <form method="post" action="/my"> <input type="submit" value="POST" /> </form> <form method="post" action="/my/stuff"> <input name="firstname" /> <input type="submit" value="POST STUFF" /> </form> If you click the GET link then the Get() action is invoked. If you post the first form then the first Post() action is invoked and if you post the second form then the second Post() action is invoked. Creating Route Constraints You can use constraints to constrain the types of values that can be passed to a controller action. For example, if you have a controller action that displays product details for a particular product given a particular product id, then you might want to constrain the product id to be an integer: using Microsoft.AspNet.Mvc; namespace RoutePlay.Controllers { [Route("[controller]")] public class ProductsController : Controller { [HttpGet("details/{id:int}")] public IActionResult Details(int id) { return View(); } } } Notice that the Details() action is decorated with an [HttpGet] attribute that uses the template “details/{0:int}” to constrain the id passed to the action to be an integer. There are plenty of other inline constraints that you use such as alpha, minlength, and regex. ASP.NET 5 introduces support for optional parameters. You can use a question mark ? in a template to mark a parameter as optional like this: [HttpGet("details/{id:int?}")] public IActionResult Details(int id) { return View(); } You can invoke the Details() action in the controller above using a URL like “/products/details/8” or a URL that leaves out the id like “/products/details” (in that case, id has the value 0). Finally, ASP.NET 5 introduces support for default parameter values. If you don’t supply a value for the id parameter then the parameter gets the value 99 automatically: [HttpGet("details/{id:int=99}")] public IActionResult Details(int id) { return View(); } Summary ASP.NET 5 (and ASP.NET MVC 6) includes a new routing framework rewritten from the ground up. In this blog post, I’ve provided a deep dive into how this new framework works. First, I discussed how routing works independently of MVC 6. I explained how you can create a new Route collection in the Startup class. Next, I demonstrated how you can use MVC 6 default routes, convention-based routes, and attribute routes. I also elaborated on how you can create controllers that follow RESTful conventions. Finally, I discussed how you can take advantage of inline constraints, optional parameters, and default parameter values. If you want to dig more deeply into routing then I recommend taking a look at the following two GitHub aspnet repositories: A small thing, but the comments in the second code block in the Attribute Based Routing section are wrong, they should be api/movies not api/values. Hopefully most people would figure it out quickly, but I’m sure you’re going to get a lot of views on this post so always good to get it right 🙂 PS I’m enjoying your coverage of ASP.NET 5 stuff so far, you seem to be one of the few people covering it in any detail… Great set of blogs! Keep them coming. I have been able to get the movie app running but have not found a way to debug the non-optimized code. Is there a way to run the application against the code in the scripts folder not the wwwroot files? This is fairly typical behavior in yeoman, or applications you manually scaffold, that use the grunt/gulp infrastructure. For example you can either run the non-optimized or optimized code using grunt-contrib-connect task. You can debug either of them in the browser’s debugger. I would like to use the Visual Studio debugger on optimized and non-optimized code if possible. @Andy – One suggestion would be to create 2 different GruntJS tasks named ReleaseBuild and DebugBuild. In the DebugBuild task, you could tell UglifyJS to combine but not minify the Javascript files. UglifyJS supports a Boolean compress option, see Looks good – MVC and WebAPI being totally different frameworks but being made to look the same can be a bit confusing. However, personally I’d seriously question the use of the term “controller” when building HTTP services, RESTful or otherwise. A “controller” is a something which is responsible for receiving user input, delegating any work to the appropriate component, and then displaying the correct view. The term shouldn’t be used when building a service. ASP.NET isn’t the only framework which makes this mistake, but it is a mistake.
http://stephenwalther.com/archive/2015/02/07/asp-net-5-deep-dive-routing
CC-MAIN-2017-43
refinedweb
2,363
56.05
Write in front The linked list, stack and queue mentioned earlier are linear storage structures, which are one-to-one relationships. Tree is a data structure with one to many relationship. For example, we often say that a class diagram in Wuhan, Hubei Province and Changsha, Hunan Province is similar to an inverted tree. What is a tree Tree is a kind of data structure, which is a finite set with hierarchical relationship composed of n nodes. Basic terms of trees Node: every data element in the tree is A node (A, B...) Degree of node: number of subtrees of node (subtrees of A are B and C) Degree of tree: the maximum degree of all nodes in the tree (the degrees of tree A and tree C are both 2) Leaf node: node with degree 0 (D, E, F) Node hierarchy: starting from the root of the tree, the layer where the tree root is located is the first layer, and the layer where the root's child nodes are located is the second layer (A first layer, BC second layer) Height of tree: the maximum level of all nodes in the tree is the height of the tree Ordered tree and unordered tree: the subtree can be divided into left and right order (for example, the one on the left is less than the one on the right), otherwise it is an unordered tree Characteristics of trees - Subtrees are disjoint - In addition to the root node, each node has one and only one parent node - A tree composed of N nodes has only N-1 edges What is a binary tree An ordered tree in which the degree of nodes in the tree does not exceed 2. Characteristics of binary tree: In the binary tree, the maximum number of nodes in layer I is 2i-1 A binary tree with a depth of K can have up to 2k-1 nodes For any binary tree, if the number of terminal nodes (number of leaf nodes) is n0 and the number of nodes with degree 2 is n2, then n0=n2+1, That is, node n0 with degree 0 is always one more than node n2 with degree 2. It is proved that there are n0 nodes with degree 0, n1 nodes with degree 1 and n2 nodes with degree 2, a total of n nodes, Because the degree of all nodes of the binary tree is not greater than 2, so: n = n0 + n1 + n2 ① In addition, since nodes with 0 degrees have no children, nodes with 1 degree have one child, and nodes with 2 degrees have two children, the total number of children is: 0 * n0 + 1 * n1 + 2 * n2. In addition, the root node (the node of the first layer) is not the child of any node, so Total nodes = total number of children + root node, i.e n = n1 + 2n2 + 1 ② ② - ① simplification n0 = n2 + 1 Full binary tree In a binary tree, except for leaf nodes, the degree of each node is 2, then the binary tree is a full binary tree. The depth of a full binary tree with n nodes is log2(n+1) Complete binary tree If the nodes of the full binary tree are numbered, the Convention number starts from the root node, from top to bottom, from left to right. A binary tree with depth k and n nodes is called a complete binary tree if and only if each node corresponds to the nodes numbered from 1 to n in the full binary tree with depth k. Features: leaf nodes can only appear in the lowest layer and sub lower layer, and the leaf nodes at the lowest layer are concentrated on the left of the tree. It should be noted that a full binary tree must be a complete binary tree, and a complete binary tree is not necessarily a full binary tree. Huffman tree (optimal binary tree) If a binary tree is given as follows: Path: the path from one node to another in a tree is called a path. As shown in the figure above, the path from the root node to a. Path length: in a path, the path length is increased by 1 for each node. As shown in the figure above, the path length from the root node to node c is 3. Node weight: each node is given a new value. If a's right is 7, b's right is 5. Weighted road strength length of a node: the product of the path length from the root node to the node and the weight of the node. For example, the weighted path length of b is 2 * 5 = 10. Weighted path length of tree: the sum of weighted path lengths of all leaf nodes in the tree. Usually referred to as "WPL". As shown in the figure, the weighted path length of this tree is: WPL = 7 * 1 + 5 * 2 + 2 * 3 + 4 * 3 What is Huffman tree Construct a binary tree (each node is a leaf node and has its own weight). The weighted path length of the tree reaches the minimum, which is called the optimal binary tree, also known as Huffman tree Coding problem Scenario: a given string contains 58 characters and is composed of the following 7 characters: A, B, C, D, e, F and g. the frequency of these 7 characters is different. How to encode these 7 characters and how to encode the string to minimize the encoding storage space of the string? If standard equal length ASCII encoding is used: 58 × 8 = 464 bits Coding with binary tree If you use 0 and 1 to represent the left and right branches, take out the above four characters with the highest frequency, and you can get the following tree: As can be seen from the above figure, there are three possible situations for characters represented by 0100. Therefore, the distribution of the above nodes is ambiguous. How to avoid ambiguity? Just make each node a leaf node. Huffman tree diagram construction In the above way, we combine the above characters in pairs according to frequency, and they are leaf nodes. The final structure diagram is as follows: Therefore, we found that each node is a leaf node, and the last code of the character is: Therefore, the encoding length is: 10x3 + 15x2 + 12x2 + 3x5 + 4x4 + 13x2 + 1x5 = 146 bits Code construction public class HuffmanTree { //node public static class Node<E> { //Data, such as a,b,c,d... E data; //weight int weight; //Left child node Node leftChild; //you child node Node rightChild; public Node(E data, int weight) { this.data = data; this.weight = weight; } public String toString() { return "Node[" + weight + ",data=" + data + "]"; } } public static Node createHuffmanTree(List<Node> nodeList) { //When the node is greater than 1 while (nodeList.size() > 1) { //First sort the list according to the weight sort(nodeList); //After sorting, the first node is the node with the smallest weight, and the second node is the node with the second smallest weight Node left = nodeList.get(0); Node right = nodeList.get(1); //Generate a new parent node, similar to step 1, but the parent node has no data and only weights Node<Node> parent = new Node<>(null, left.weight + right.weight); //Child and parent node links parent.leftChild = left; parent.rightChild = right; //Delete the smallest node nodeList.remove(0); //Delete the second smallest nodeList.remove(0); //Add to list nodeList.add(parent); } //Finally, a tree is returned to the root node return nodeList.get(0); } /** * Fake sort * * @param nodeList */ public static void sort(List<Node> nodeList) { if (nodeList.size() <= 1) { return; } for (int i = 0; i < nodeList.size(); i++) { for (int j = 0; j < nodeList.size() - 1; j++) { //If the preceding number is greater than the following number, it will be exchanged if (nodeList.get(j + 1).weight < nodeList.get(j).weight) { Node temp = nodeList.get(j + 1); nodeList.set(j + 1, nodeList.get(j)); nodeList.set(j, temp); } } } } /** * Print Huffman tree from left to right * That is, the left node of the child node is printed first from the root node, and the right node is printed * @param root Root node tree */ public static void printTree(Node root) { if (root.leftChild != null) { System.out.println("Left child node:" + root.leftChild); printTree(root.leftChild); } if (root.rightChild != null) { System.out.println("Right child node:" + root.rightChild); printTree(root.rightChild); } } //test public static void main(String[] args) { List<Node> nodes = new ArrayList<Node>(); //Add nodes to the list nodes.add(new Node("a", 10)); nodes.add(new Node("b", 15)); nodes.add(new Node("c", 12)); nodes.add(new Node("d", 3)); nodes.add(new Node("e", 4)); nodes.add(new Node("f", 13)); nodes.add(new Node("g", 1)); Node root = createHuffmanTree(nodes); printTree(root); } } test result Left child node: Node[25,data=null] Left child node: Node[12,data=c] Right child node: Node[13,data=f] Right child node: Node[33,data=null] Left child node: Node[15,data=b] Right child node: Node[18,data=null] Left child node: Node[8,data=null] Left child node: Node[4,data=e] Right child node: Node[4,data=null] Left child node: Node[1,data=g] Right child node: Node[3,data=d] Right child node: Node[10,data=a] summary This chapter is mainly about the basic concept of tree and understanding the characteristics of common trees. Later, we will continue to talk about binary sorting tree and binary balanced tree. The data structure is relatively boring, but we will gain if we stick to it. It will greatly improve both the algorithm and the source code.
https://programmer.group/what-is-huffman-tree.html
CC-MAIN-2022-27
refinedweb
1,621
66.27
Years ago, I could recall lots of phone numbers from memory. Now? It’d be tough to come up with more than two. There’s so many ways to contact each person that I know (phone, email(s), Twitter, WhatsApp, etc) and I depend heavily on my address book. As you start using microservices in your architecture, you’ll discover that you also need a good address book to find services at runtime. But unlike classic solutions such as configuration management databases or UDDI registries, a modern “address book” is different. Why? As microservices get deployed, scaled, and updated, their “address” is fluid. To account for that, any modern address book cannot have stale references. Enter Eureka from Netflix. While baked into Spring Cloud for Java users, Eureka isn’t easily available to .NET microservices. That changed with the OSS Steeltoe library, and I thought I’d show that off here. Building a Eureka Server Thanks to Spring Cloud, it’s easy to set up a Eureka registry for your services to talk to. First, I used Spring Tool Suite to build a new Spring Boot app. In the app creation wizard, I chose the “Eureka Server” package dependency (spring-cloud-starter-eureka-server). If you aren’t using Spring Tool Suite, check out the awesome web-based Spring Intializr to generate project scaffolding to import into any Java IDE. Next up, there was a LOT of code to write to bring up a Eureka server. @EnableEurekaServer @SpringBootApplication public class PsPlaceholderEurekaServerApplication { public static void main(String[] args) { SpringApplication.run(PsPlaceholderEurekaServerApplication.class, args); } } Seriously, that’s it. Bonkers. All that remained was adding a few properties. I set a couple of cosmetic properties (“datacenter” and “environment”), and then told Eureka to NOT register itself with the server, and to NOT retrieve a copy of the registry. server.port=8761 # value used for AWS, here can be anything eureka.datacenter=seattle eureka.environment=prod # no need to register the server with the server eureka.client.register-with-eureka=false # don't need a local copy of the registry eureka.client.fetch-registry=false I started up the app, navigated to the right URL, and saw the Eureka Server dashboard. There was a bunch of system status info, and an (empty) list of registered servers. Note that Eureka stores its registry in memory. The registry is a live look at the environment because services send a heartbeat to state that they’re online. No need to persist anything to disk. Building a Eureka Server (Alternative, No-Java Way) Now you might say “I don’t know Java and don’t want to learn it.” Fair enough. If you’re a Pivotal customer, than you’re in luck. Spring Cloud Services bundles up key Spring Cloud projects and runs them “as a service” in your Cloud Foundry environment. One such service is the Eureka Service Registry. You can try this out for free in Pivotal Web Services. After clicking a couple buttons, and waiting about 30 seconds, I had a registry! No Java required. Registering a Java Service Great, I had a registry. Now what? I wanted to add a Java and .NET service to my local registry. First up, Java. I created a new Spring Boot application, and chose the “Eureka Discovery” package dependency (spring-cloud-starter-eureka). I set up a super awesome REST service that says “hello from Spring Boot.” What about registering with Eureka? It took a single @EnableEurekaClient annotation in my code. @EnableEurekaClient @RestController @SpringBootApplication public class PsPlaceholderEurekaServiceApplication { public static void main(String[] args) { SpringApplication.run(PsPlaceholderEurekaServiceApplication.class, args); } @RequestMapping("/") public String SayHello() { return "hello from Spring Boot!"; } } In the bootstrap.properties file, I set the “spring.application.name” property. This told Eureka what to label my service in the registry. In my application.properties file, I specified that I should register with Eureka, and to send health data along with my service’s heartbeat. eureka.client.register-with-eureka=true eureka.client.fetch-registry=false #can intentionally set the host name eureka.instance.hostname=localhost eureka.client.healthcheck.enabled=true With this in place, I started up my Java service, and sure enough, saw it in the Eureka registry. Cool! Registering a .NET Service .NET developers, rejoice! We can enjoy all kinds of microservices goodness by using libraries like Steeltoe. And it works with .NET Framework and .NET Core apps. In this example, I chose to use .NET Core. Here’s my sequence of commands in the wicked .NET Core CLI: dotnet new webapi dotnet add package Steeltoe.Discovery.Client -v 1.0.0-rc2 dotnet restore dotnet build dotnet run Just running those commands gave me a Web API project with a dependency on Steeltoe’s discovery package. The latter two commands built and ran the app itself. The “webapi” project shell sets up a default REST controller, and for this demo, I just kept that. The only necessary code changes occurred in the Startup.cs class. Here, I added a using directive for “Steeltoe.Discovery.Client”, and updated the ConfigureServices and Configure operations to each include references to the discovery client. // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); services.AddDiscoveryClient(Configuration); } //(); app.UseDiscoveryClient(); } Finally, I added a few entries to the appsettings.json file. First I set a “spring.application.name” value, just like I did with my Spring Boot app. This tells the registry what to label my service. Then I have a block of Eureka settings including the registry URL, whether I should register with Eureka (yes!), pull a local copy of the registry (no!), and how to find my instance. { "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning", "System": "Information", "Microsoft": "Information" } }, "spring": { "application": { "name": "dotnet-demo-service" } }, "eureka": { "client": { "serviceUrl": "", "shouldRegisterWithEureka": true, "shouldFetchRegistry": false }, "instance": { "hostname": "localhost", "port": 5000 } } } When I ran the “dotnet build” and “dotnet run” commands, I saw my .NET service show up in the Eureka registry. BAM! Performing Discovery From a Java App It’s all nice and good to have an up-to-date address book, but it’s kinda worthless if nobody ever calls you! How would I yank service information from the registry for a Java app? It’s easy. First, I created a new Spring Boot project, and used the same “Eureka Discovery” package dependency (spring-cloud-starter-eureka) as before. In the application properties file, I specified that I *do* want a local copy of the registry, but do *not* need to register the client app as an available service. I’m just a client here, so no need to do register or give heartbeats. server.port=8081 eureka.client.register-with-eureka=false eureka.client.fetch-registry=true eureka.client.healthcheck.enabled=false In my application code, I annotated my main class with @EnableDiscoveryClient, created a load balanced RestTemplate bean, autowired a variable to it, and then defined an operation that used it. @EnableDiscoveryClient @SpringBootApplication public class PsPlaceholderEurekaServiceConsumerApplication { public static void main(String[] args) { SpringApplication.run(PsPlaceholderEurekaServiceConsumerApplication.class, args); } @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } } @RestController @Component class ConsumerController { //available now with load balanced bean @Autowired private RestTemplate restTemplate; @RequestMapping("/service-instancesrt") public String GetServiceInstancesRt() { String response = restTemplate.getForObject("", String.class); return response; } } What’s pretty cool is that RestTemplate object is injected with enough smarts to replace the service name from the registry (“dotnet-demo-service”) with the actual URL when it makes the API call. When I invoked my local endpoint, it passed through the request to the microservice it looked up in the registry, and returned the result. Performing Discovery From a .NET App Finally, let’s see how a .NET app would pull a reference from the Eureka registry and use it. I created a new project based on the ASP.NET Core MVC template. And then I added the Steeltoe package for service discovery. dotnet new mvc dotnet add package Steeltoe.Discovery.Client -v 1.0.0-rc2 dotnet restore With this MVC template, I got some basic scaffolding for a sample website. I just extended this by adding a new view (called “Demo”) and controller method. No content in the method right away. Just like before, I updated the Startup.cs class by first adding a reference to “Steeltoe.Discovery.Client” and updating the “ConfigureServices” and “Configure” methods. ASP.NET Core offers some nice dependency injection stuff. So with the code update above, I now had a “DiscoveryClient” object available for any controller or service to use. So, back in the controller, I added a variable for DiscoveryHttpClientHandler. Then I instantiated that object in the controller constructor, and used it in the new controller method to call a Eureka-registered Java service. Note once again that I only needed the registered service name, and the client libraries flipped this to the address/port of my actual service. public class HomeController : Controller { //added for demonstration DiscoveryHttpClientHandler _handler; public HomeController(IDiscoveryClient client) { _handler = new DiscoveryHttpClientHandler(client); } public IActionResult Demo() { HttpClient c = new HttpClient(_handler, false); //call service using registered alias string s = c.GetStringAsync("").Result; ViewData["Message"] = "Service result is: " + s; return View(); } } Finally, I added a few things to my appsettings.json file so that the Steeltoe client library knew how to behave. I gave the application a name, and told it to *not* register itself with Eureka, but only to fetch the registry and cache it locally. { "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } }, "spring": { "application": { "name": "dotnet-demo-service-client" } }, "eureka": { "client": { "serviceUrl": "", "shouldRegisterWithEureka": false, "shouldFetchRegistry": true }, "instance": { "hostname": "localhost", "port": 5001 } } } After that, I started up by ASP.NET Core app, hit the webpage, and saw a result from my Spring Boot service. That was fun! Some sort of service registry is extremely helpful when adopting a microservices architecture. Instead of using hard-coding references or stale data stores, an always-accurate registry gives you the best chance of surviving in a fluid microservices environment. Now, thanks to Steeltoe, you can use the same registry for your Java, .NET (and even Node.js) services. Categories: .NET, ASP.NET Web API, Cloud, Cloud Foundry, Microservices, OSS Thanks Richard, another great article and that we can now easily register/integrate .Net services is very attractive. I had a quick search but couldnt see anyone offering a SaaS Eureka service which might be nice rather than self-hosted/containered etc. Anyone thought of provisioning a hyper-scale Eureka for public API endpoints, and a general pattern of self-registration plus a standard security/usage contract for clients..? That would be funky… Will stop getting ahead of myself and see if we can adopt this for our internal endpoints :). ok my bad.. “eureka” = 0 results in Pivotal, “registry” as per screenshot = winner 🙂 Wow this is great stuff! I’m currently looking into microservices and therefore service discovery! Let me know what you think Finding the right service could be accomplished using DNS. Let’s say we have an order service, it will be order.mycompany.com, we have a customer service, it will be customer.mycompany.com What’s the advantage of using a registry? At first glance it seems more complicated. There are definitely cases where DNS is sufficient. But DNS isn’t really set up for this sort of environment. A few examples: you’d have to set up an aggressive DNS cache invalidation strategy to account for service address changes, need to leave the service host to resolve DNS requests vs using a local registry cache, and DNS users don’t have the benefit of a “smart” resolution that uses service health and other metrics to return addresses. So DNS can work, but it’s not always ideal for cloud-like systems! You made my day! Thank you so much for the information, I’ve been looking for a quick an easy example for a while. Steeltoe example has to much stuff in it and it’s very difficult to understand. They mix everything in there and I got lost.
https://seroter.wordpress.com/2017/03/27/yes-you-can-use-a-single-service-registry-for-net-and-java-microservices/
CC-MAIN-2019-26
refinedweb
2,015
58.08
- Warning message? - Stroke Style in AS? - AE import - Educational CDROM - Flash8/Director or Flash CS3 - Overlapping Menus in Flash CS3 - Problem that I can't Figure Out - I need a way to know that the frame for my game actions has completely loaded! - Reusable endmovie detector. Isn't there a better way? - Focus on Actions Panel - Flash CS3 Easter Egg - missing fl.controls - mouseWheel - Scrolling Text is smeared and unreadable, why? - Help with Database - Multiple Images Dynamically - Help: add BACK/FORWARD buttons to Sliding Menu? - So the stop script doesn't even seem to work - Restrict Back actions - dynamic text field height - Whats the reccomended size of the stage for fullscreen? - MYSPACE XML Music Player - AS3.0 Scroller with graphics - Can't import EPS files - Flash cs3 compile error 1017--package namespace? - Photo Gallery - captions not working, but photos are - Var and function scope headache - Datagrid as2 - Compiler Error - E-Magazine Component not working after reSize! - Batch Publishing - Print Multiple External Files - CPU Usage - Multi zone stage, zoom in, and load external movie - Modify the source code of components - Article: Creating ActionScript 3.0 components in Flash CS3 - setRGB in AS3 - Difference between Flash Player 8 & 9 for AS2 movie ? - Possible to load all external .swf files at once ? - Creating links - flash.geom.ColorTransform. - Weird component behaviour... - XML and flash photogallery - Hide Code in FLA - Detecting character key strokes. - need help with scrollbars.. - Calendar Help - External Text "Quotes" Questions - Rofl? - N-Serier view all product effects - Adding a child of a custom class? - problems wiv cs3 - Vista and OSX CS3 trouble - CS3 two-computer activation limit a fiasco - error handling - AIR beta extension on PPC Mac - disable workspace animation? - How to select all the children of a DisplayObjectContainer - need help about buttons with as - Preloader - FLV code for triggering event - getting flash to play after creating object in Javascript - AC_RunActiveContent.js VS defined popup dimensions - drop down menu over top of html - prevent child from scaling - Load MC between images xml gallery - event.target ? - dynamicly export first frame of flv as image? - Rollover button with AS2 - Loader component problem - mini flash applications - ActionScript, Folder Contents, and XML - WARNING! Flash AutoFormat has messed up my code. - Whats the best way to approach this? - Problem with _root.choose - As 3.0 Asp.net Sql Server 2005 - As 3.0 Asp.net Sql Server 2005 - DisplayObject, DisplayObjectContainer and the Stage! - as2: colorTransform not permanent - Duplicate Loader content - simple component parameter problem with Inspectables - bufferTime Listener? - SoundSpectrum with volume & preloader - First frame too large - Flash video encoder and Vista rant - Need help Loading pages - How Can I minimize the size of my work - movie clip help - Help with floating movie clips - banner peel away - 3d flash tutorial ... converting as2 tutorial into as3 ... - Tween problem - ACTIONSCRIPT 3 Help convince me to make the switch - getBytesLoaded and getBytesTotal isnt getting! Please help - Internet Explorer/Javascript/Flash PopUp problem - Flash navigation displayed over html - create a MC like quicktime - pan image, randomize - in ur forum, seeking ur knowledge (flash/php/mysql) - Basic AS3 question... - External .swf - timeline preloader works, but not online - the * of death (.fla*) - Depth Level - dynamic text field = no Alpha? CS3 - trouble with thumbnails for photo gallery - zoom in and out - button - page flip - music component? - WARNING! CS3 + Components + Frames = NIGHTMARE! - combo box sound - challenge: rolling ball - Save current swf as a png? - flv / A.S. 3.0 issues - Pop Up inside Flash - "Stopping" the Image Panning Tutorial - trying to pass vars to random function! - mouse follower - Powers of Actionscript? - E-comm in Flash? - Sync FLV with Keyframe animation - Controlling external SWF's with an array? - [AS3] Engine Revving Sound Imitation - alpha trouble - Strange question... - Adding Thumbnails - pop up control ("I'm here") - AS3 and flex components - help to replicate 3 issues - AIR: use swf in AIR-app. (HTML based) - I need help opening popups from popups... please read - Expansible web banner - make a movie play the closer the mouse is. help please - FLV video getting stuck while playing - Best tutorial? - page flip - Flash and Javascript problem (intel imac) - SoundSync - Fade In Probllem - Check for the loaded URL? - Advanced Button Problems - projector files in macintosh - photo gallery image inserts into xml and flash - 360 degree virtual tour - Menu Problems - Faster way of scaling/rotating/alpha of movieclips? - Online store in flash CS3 / Music player - contolling an externally loaded timeline - contolling an externally loaded timeline - Pausing ALL tweens, sounds, and functions in a movie - Button Problem - circle movement - (Flash CS3 bug?) Tweens on publish cache messed up - Slide show - Reference To Frame Number - Undefined Variable HOW???? - pause between scripts - SlideshowPro - Movieclip Actionscript - gotoAndPlay.......... - Help with Creating a Vertical Shooter - Is it a Flash Bug?? - as3 scrollbar tutorial - as3 scrollbar tutorial - overlapping event type constants? - Adobe AIR or Flex? - Draw a bitmap line or a bitmap polygon - same mc tells different mcs to play once completed - problems with a menu - music in flash - Cue to the next frame after FLV video ends - XML Gallery photo Loop w/out Slideshow - Hover captions - Passing variables to flash (from php) and readin text file - Display on stage from subclass - buttons created in a loop - Mouse Event Problems - having problems with transparency, yes.. transparency. - a little help with arrays and such... - Beginner help please! - URGENT help in Contact Form with PHP Plzz - removeMovieClip(this) in AS3 ? - Urgent DataGrid! - testing CS3 - 3 General Flash questions - Buttons do not work on the Server - Tiltviewer!!! - Suggestions? FLV files won't progressively download. - Copy to clipboard - make a url link to text file...? - Button to next frame - CS3 UIScrollBar Component not working - Imported Images becomes choppy after resizing - Function Help - Smooth photo zoom - Help adding "ENTER" key in code please. - Progressively Slow Flash - FLVPlaybackCaptioning trouble - FLV's in a row - Flash Snow 3.0 Layering - URGENT: I need help linking an external video - Need to find a Looping Road Image Please Help - URGENT: Need help randomizing - Anyone knows how to create Collapsible Menu like this sampe!!! - Button Targetting MC Issue - Animating player.. - Animating a Bomb Fuse Need some help - Actionscript Slideshow with animated button above!?!? - Why i install - TextFieldType.INPUT bug? - SWF Library - URGENT: associative multidimsional array - removeChild issues - flash crashing on publish URGENT HELP NEEDED - Adding Thumbnails-Tutorial mod - How do you know if it's a memory leak? - Newsletter (fla+php) with autoresponder - color with AS3 - Reload AS from within movie? - Flash CMS - Coordinate origin screwed up? - dimensional distortion - Survey Flash file - how is this done? - newbie conundrum, flash & frames - zoom menu - Download complete flash web site - Flash and HTML alignment issue - I want the video embedded in my FLA - Help with scrollbar issue - Chat Application (PHP/mySQL/Flash) - Default Parameter Values - Can't instantiate classes as defaults - The Weirdest Thing Happens... - Full Path - Loading external swf doesn't work when uploaded to website until page is refreshed - Snowglobe - Drawing board? - Navigating betwee scenes - unintentionally changing tools, editing as while testing swf - Problems with FLVs in AS3 - Drag and Drop Interface - > customized window - Exceed Maximum MovieClip Height? - the scope of this - New Ver of Flash player in html files - The class or interface 'StyleSheet' could not be loaded!!!! - button under rollover button problem.. need help urgent.. - newbie question re. flash photo gallery + XML/PHP/MySQL
http://www.kirupa.com/forum/archive/index.php/f-140-p-5.html
crawl-002
refinedweb
1,203
57.57
This document describes the various rules, guidelines and advice for those wishing to contribute to the source code of Parrot, in such areas as code structure, naming conventions, comments etc. Not applicable. One of the criticisms of Perl 5 is that its source code is impenetrable to newcomers, due to such things as inconsistent or obscure variable naming conventions, lack of comments in the source code, and so on. We don't intend to make the same mistake when writing Parrot. Hence this document. We define three classes of conventions: Items labelled must are mandatory; and code will not be accepted (apart from in exceptional circumstances) unless it obeys them. Items labelled should are strong guidelines that should normally be followed unless there is a sensible reason to do otherwise. Items labelled may are tentative suggestions to be used at your discretion. Note that since Parrot is substantially implemented in C, these rules apply to C language source code unless otherwise specified. In addition, C code may assume that any pointer value can be coerced to an integral type (no smaller than typedef INTVAL in Parrot), then back to its original type, without loss. Also C code may assume that there is a single NULL pointer representation and that it consists of a number, usually 4 or 8, of '\0' chars in memory. C code that makes assumptions beyond these must depend on the configuration system, either to not compile an entire non-portable source where it will not work, or to provide an appropriate #ifdef macro. Perl code may use features not available in Perl 5.8.0 only if it is not vital to Parrot, and if it uses $^O and $] to degrade or fail gracefully when it is run where the features it depends on are not available. The following must apply: }that closes an ifmust line up with the if. elses are forbidden: i.e. avoid } else {. #define POBJ_FLAG(n) ((UINTVAL)1 << (n)) The following should apply: Interp *foo, but not Interp* foo. return (x+y)*2. There should be no space between a function name and the following open parenthesis, e.g. z = foo(x+y)*2 .and ->) should have at least one space on either side; there should be no space between unary operators and their operands; parentheses should not have space immediately after the opening parenthesis nor immediately before the closing parenthesis; commas should have at least one space after, but not before; e.g.: x = (a-- + b) * f(c, d / e.f) foo = 1 + 100; x = 100 + 1; whatever = 100 + 100; ... to this (good): foo = 1 + 100; x = 100 + 1; whatever = 100 + 100; (Note that formatting consistency trumps this rule. For example, a long if/ else if chain is easier to read if all (or none) of the conditional code is in blocks.) if (a && (b = c)) ...or if ((a = b)) .... something_long_here = something_very_long + something_else_also_long - something_which_also_could_be_long; z = foo(bar + baz(something_very_long_here * something_else_very_long), corge); The following must apply: /* comment */. (Not all C compilers handle C++-style comments.) PARROT_, followed by unique and descriptive text identifying the header file (usually the directory path and filename), and end with a _GUARDsuffix. The matching #endifmust have the guard macro name in a comment, to prevent confusion. For example, a file named parrot/foo.h might look like: #ifndef PARROT_FOO_H_GUARD #define PARROT_FOO_H_GUARD #include "parrot/config.h" #ifdef PARROT_HAS_FEATURE_FOO # define FOO_TYPE bar typedef struct foo { ... } foo_t; #endif /* PARROT_HAS_FEATURE_FOO */ #endif /* PARROT_FOO_H_GUARD */ The following should apply typedef struct Foo { ... } Foo; #ifndef NO_FEATURE_FOO. if (!foo) .... However, the sense of the expression being checked must be a boolean. Specifically, strcmp() and its brethren are three-state returns. if ( !strcmp(x,y) ) # BAD, checks for if x and y match, but looks # like it is checking that they do NOT match. if ( strcmp(x,y) == 0 ) # GOOD, checks proper return value if ( STREQ(x,y) ) # GOOD, uses boolean wrapper macro (Note: PMC * values should be checked for nullity with the PMC_IS_NULL macro, unfortunately leading to violations of the double-negative rule.) All developers using Emacs must ensure that their Emacs instances load the elisp source file editor/parrot.el before opening Parrot source files. See "README.pod" in editor for instructions. All source files must end with an editor instruction coda: /* * Local variables: * c-file-style: "parrot" * End: * vim: expandtab shiftwidth=4: */ # Local Variables: # mode: makefile # End: # vim: ft=make: # Local Variables: # mode: cperl # cperl-indent-level: 4 # fill-column: 100 # End: # vim: expandtab shiftwidth=4: Exception: Files with __END__ or __DATA__ blocks do not require the coda. This is at least until there is some consensus as to how solve the issue of using editor hints in files with such blocks. # Local Variables: # mode: pir # fill-column: 100 # End: # vim: expandtab shiftwidth=4 ft=pir: {{ XXX - Proper formatting and syntax coloring of C code under Emacs requires that Emacs know about typedefs. We should provide a simple script to update a list of typedefs, and parrot.el should read it or contain it. }} Parrot runs on many, many platforms, and will no doubt be ported to ever more bizarre and obscure ones over time. You should never assume an operating system, processor architecture, endian-ness, size of standard type, or anything else that varies from system to system. Since most of Parrot's development uses GNU C, you might accidentally depend on a GNU feature without noticing. To avoid this, know what features of gcc are GNU extensions, and use them only when they're protected by #ifdefs. C arrays, including strings, are very sharp tools without safety guards, and Parrot is a large program maintained by many people. Therefore: Don't use a char * when a Parrot STRING would suffice. Don't use a C array when a Parrot array PMC would suffice. If you do use a char * or C array, check and recheck your code for even the slightest possibility of buffer overflow or memory leak. Note that efficiency of some low-level operations may be a reason to break this rule. Be prepared to justify your choices to a jury of your peers. unsigned charto isxxx()and toxxx() Pass only values in the range of unsigned char (and the special value -1, a.k.a. EOF) to the isxxx() and toxxx() library functions. Passing signed characters to these functions is a very common error and leads to incorrect behavior at best and crashes at worst. And under most of the compilers Parrot targets, char is signed. constkeyword on arguments Use the const keyword as often as possible on pointers. It lets the compiler know when you intend to modify the contents of something. For example, take this definition: int strlen(const char *p); The const qualifier tells the compiler that the argument will not be modified. The compiler can then tell you that this is an uninitialized variable: char *p; int n = strlen(p); Without the const, the compiler has to assume that strlen() is actually initializing the contents of p. constkeyword on variables If you're declaring a temporary pointer, declare it const, with the const to the right of the *, to indicate that the pointer should not be modified. Wango * const w = get_current_wango(); w->min = 0; w->max = 14; w->name = "Ted"; This prevents you from modifying w inadvertently. new_wango = w++; /* Error */ If you're not going to modify the target of the pointer, put a const to the left of the type, as in: const Wango * const w = get_current_wango(); if (n < wango->min || n > wango->max) { /* do something */ } Declare variables in the innermost scope possible. if (foo) { int i; for (i = 0; i < n; i++) do_something(i); } Don't reuse unrelated variables. Localize as much as possible, even if the variables happen to have the same names. if (foo) { int i; for (i = 0; i < n; i++) do_something(i); } else { int i; for (i = 14; i > 0; i--) do_something_else(i * i); } You could hoist the int i; outside the test, but then you'd have an i that's visible after it's used, which is confusing at best. Filenames must be assumed to be case-insensitive, in the sense that you may not have two different files called Foo and foo. Normal source-code filenames should be all lower-case; filenames with upper-case letters in them are reserved for notice-me-first files such as README.pod, and for files which need some sort of pre-processing applied to them or which do the preprocessing - e.g. a script foo.SH might read foo.TEMPLATE and output foo.c. The characters making up filenames must be chosen from the ASCII set A-Z,a-z,0-9 plus .-_ An underscore should be used to separate words rather than a hyphen (-). A file should not normally have more than a single '.' in it, and this should be used to denote a suffix of some description. The filename must still be unique if the main part is truncated to 8 characters and any suffix truncated to 3 characters. Ideally, filenames should restricted to 8.3 in the first place, but this is not essential. Each subsystem foo should supply the following files. This arrangement is based on the assumption that each subsystem will -- as far as is practical -- present an opaque interface to all other subsystems within the core, as well as to extensions and embeddings. foo.h This contains all the declarations needed for external users of that API (and nothing more), i.e. it defines the API. It is permissible for the API to include different or extra functionality when used by other parts of the core, compared with its use in extensions and embeddings. In this case, the extra stuff within the file is enabled by testing for the macro PARROT_IN_CORE. foo_private.h This contains declarations used internally by that subsystem, and which must only be included within source files associated the subsystem. This file defines the macro PARROT_IN_FOO so that code knows when it is being used within that subsystem. The file will also contain all the 'convenience' macros used to define shorter working names for functions without the perl prefix (see below). foo_globals.h This file contains the declaration of a single structure containing the private global variables used by the subsystem (see the section on globals below for more details). foo_bar.[ch]etc. All other source files associated with the subsystem will have the prefix foo_. Code entities such as variables, functions, macros etc. (apart from strictly local ones) should all follow these general guidelines. new_foo_barrather than NewFooBaror (gasp) newfoobar. create_foo_from_bar()in preference to ct_foo_bar(). Avoid cryptic abbreviations wherever possible. pmc_foo(), struct io_bar. Parrot_foo, and should only use typedefs with external visibility (or types defined in C89). Generally these functions should not be used inside the core, but this is not a hard and fast rule. pmc_foo. Foo_bar. The exception to this is when the first component is a short abbreviation, in which case the whole first component may be made uppercase for readability purposes, e.g. IO_foorather than Io_foo. Structures should generally be typedefed. PMC_foo_FLAG, PMC_bar_FLAG, .... _FLAG, e.g. PMC_readonly_FLAG(although you probably want to use an enuminstead.) _TEST, e.g. if (PMC_readonly_TEST(foo)) ... _SET, e.g. PMC_readonly_SET(foo); _CLEAR, e.g. PMC_readonly_CLEAR(foo); _MASK, e.g. foo &= ~PMC_STATUS_MASK(but see notes on extensibility below). _SETALL, _CLEARALL, _TESTALLor _TESTANYsuffixes as appropriate, to indicate aggregate bits, e.g. PMC_valid_CLEARALL(foo). HAS_, e.g. HAS_BROKEN_FLOCK, HAS_EBCDIC. IN_, e.g. PARROT_IN_CORE, PARROT_IN_PMC, PARROT_IN_X2P. Individual include file visitations should be marked with PARROT_IN_FOO_Hfor file foo.h USE_, e.g. PARROT_USE_STDIO, USE_MULTIPLICITY. DECL_, e.g. DECL_SAVE_STACK. Note that macros which implicitly declare and then use variables are strongly discouraged, unless it is essential for portability or extensibility. The following are in decreasing preference style-wise, but increasing preference extensibility-wise. { Stack sp = GETSTACK; x = POPSTACK(sp) ... /* sp is an auto variable */ { DECL_STACK(sp); x = POPSTACK(sp); ... /* sp may or may not be auto */ { DECL_STACK; x = POPSTACK; ... /* anybody's guess */ Global variables must never be accessed directly outside the subsystem in which they are used. Some other method, such as accessor functions, must be provided by that subsystem's API. (For efficiency the 'accessor functions' may occasionally actually be macros, but then the rule still applies in spirit at least). All global variables needed for the internal use of a particular subsystem should all be declared within a single struct called foo_globals for subsystem foo. This structure's declaration is placed in the file foo_globals.h. Then somewhere a single compound structure will be declared which has as members the individual structures from each subsystem. Instances of this structure are then defined as a one-off global variable, or as per-thread instances, or whatever is required. [Actually, three separate structures may be required, for global, per-interpreter and per-thread variables.] Within an individual subsystem, macros are defined for each global variable of the form GLOBAL_foo (the name being deliberately clunky). So we might for example have the following macros: /* perl_core.h or similar */ #ifdef HAS_THREADS # define GLOBALS_BASE (aTHX_->globals) #else # define GLOBALS_BASE (Parrot_globals) #endif /* pmc_private.h */ #define GLOBAL_foo GLOBALS_BASE.pmc.foo #define GLOBAL_bar GLOBALS_BASE.pmc.bar ... etc ... The importance of good code documentation cannot be stressed enough. To make your code understandable by others (and indeed by yourself when you come to make changes a year later), the following conventions apply to all source files. Each source file (e.g. a foo.c, foo.h pair), should contain inline Pod documentation containing information on the implementation decisions associated with the source file. (Note that this is in contrast to PDDs, which describe design decisions). In addition, more discussive documentation can be placed in *.pod files in the docs/dev directory. This is the place for mini-essays on how to avoid overflows in unsigned arithmetic, or on the pros and cons of differing hash algorithms, and why the current one was chosen, and how it works. In principle, someone coming to a particular source file for the first time should be able to read the inline documentation file and gain an immediate overview of what the source file is for, the algorithms it implements, etc. The Pod documentation should follow the layout: =head1 Foo When appropriate, some simple examples of usage. A description of the contents of the file, how the implementation works, data structures and algorithms, and anything that may be of interest to your successors, e.g. benchmarks of differing hash algorithms, essays on how to do integer arithmetic. Links to pages and books that may contain useful information relevant to the stuff going on in the code -- e.g. the book you stole the hash function from. Don't include author information in individual files. Author information can be added to the CREDITS file. (Languages are an exception to this rule, and may follow whatever convention they choose.) Don't include Pod sections for License or Copyright in individual files. If there is a collection of functions, structures or whatever which are grouped together and have a common theme or purpose, there should be a general comment at the start of the section briefly explaining their overall purpose. (Detailed essays should be left to the developer file). If there is really only one section, then the top-of-file comment already satisfies this requirement. Every non-local named entity, be it a function, variable, structure, macro or whatever, must have an accompanying comment explaining its purpose. This comment must be in the special format described below, in order to allow automatic extraction by tools - for example, to generate per API man pages, perldoc -f style utilities and so on. Often the comment need only be a single line explaining its purpose, but sometimes more explanation may be needed. For example, "return an Integer Foo to its allocation pool" may be enough to demystify the function del_I_foo() Each comment should be of the form /* =item C<function(arguments)> Description. =cut */ This inline Pod documentation is transformed to HTML with: $ make html Whenever code has deliberately been written in an odd way for performance reasons, you should point this out - if nothing else, to avoid some poor schmuck trying subsequently to replace it with something 'cleaner'. /* The loop is partially unrolled here as it makes it a lot faster. * See the file in docs/dev for the full details */ While there is no need to go mad commenting every line of code, it is immensely helpful to provide a "running commentary" every 10 lines or so if nothing else, this makes it easy to quickly locate a specific chunk of code. Such comments are particularly useful at the top of each major branch, e.g. if (FOO_bar_BAZ(**p+*q) <= (r-s[FOZ & FAZ_MASK]) || FLOP_2(z99)) { /* we're in foo mode: clean up lexicals */ ... (20 lines of gibberish) ... } else if (...) { /* we're in bar mode: clean up globals */ ... (20 more lines of gibberish) ... } else { /* we're in baz mode: self-destruct */ .... } The first line of every file (or the second line if the first line is a shebang line such as #!/usr/bin/perl) should be a copyright notice, in the comment style appropriate to the file type. It should list the first year the file was created and the last year the file was modified. (This isn't necessarily the current year, the file might not have been modified this year.) For files that were newly added this year, just list the current year. Over the lifetime of Parrot, the source code will undergo many major changes never envisaged by its original authors. To this end, your code should balance out the assumptions that make things possible, fast or small, with the assumptions that make it difficult to change things in future. This is especially important for parts of the code which are exposed through APIs -- the requirements of source or binary compatibility for such things as extensions can make it very hard to change things later on. For example, if you define suitable macros to set/test flags in a struct, then you can later add a second word of flags to the struct without breaking source compatibility. (Although you might still break binary compatibility if you're not careful.) Of the following two methods of setting a common combination of flags, the second doesn't assume that all the flags are contained within a single field: foo->flags |= (FOO_int_FLAG | FOO_num_FLAG | FOO_str_FLAG); FOO_valid_value_SETALL(foo); Similarly, avoid using a char* (or {char*,length}) if it is feasible to later use a PMC * at the same point: c.f. UTF-8 hash keys in Perl 5. Of course, private code hidden behind an API can play more fast and loose than code which gets exposed. We want Parrot to be fast. Very fast. But we also want it to be portable and extensible. Based on the 90/10 principle, (or 80/20, or 95/5, depending on who you speak to), most performance is gained or lost in a few small but critical areas of code. Concentrate your optimization efforts there. Note that the most overwhelmingly important factor in performance is in choosing the correct algorithms and data structures in the first place. Any subsequent tweaking of code is secondary to this. Also, any tweaking that is done should as far as possible be platform independent, or at least likely to cause speed-ups in a wide variety of environments, and do no harm elsewhere. If you do put an optimization in, time it on as many architectures as you can, and be suspicious of it if it slows down on any of them! Perhaps it will be slow on other architectures too (current and future). Perhaps it wasn't so clever after all? If the optimization is platform specific, you should probably put it in a platform-specific function in a platform-specific file, rather than cluttering the main source with zillions of #ifdefs. And remember to document it. Not all files can strictly fall under these guidelines as they are automatically generated by other tools, or are external files included in the Parrot repository for convenience. Such files include the C header and source files automatically generated by (f)lex and yacc/bison, and some of the Perl modules under the lib/ directory. To exempt a file (or directory of files) from checking by the coding standards tests, one must edit the appropriate exemption list within lib/Parrot/Distribution.pm (in either of the methods is_c_exemption() or is_perl_exemption()). One can use wildcards in the list to exempt, for example, all files under a given directory. None.
http://search.cpan.org/~mstrout/Rakudo-Star-2012.08_001/rakudo-star/parrot/docs/pdds/pdd07_codingstd.pod
CC-MAIN-2013-48
refinedweb
3,436
54.42
zeam.form.ztk 1.2.3 Zope Toolkit support for zeam.form zeam.form.ztk help you to integrate zeam.form.base with the Zope Tool Kit. It provides: - Form fields generation out of zope.schema fields, and zope.schema fields listed in a Zope interface, - Widgets for those fields, - Default action to Add, Edit a content, Cancel a current action by returning on the default view of a content. Like zeam.form.base the focus is to have an API usable by the developer, not a support of theorical use-cases that you don’t need. Contents Example Let’s create a form to edit a content. Here we have an interface for our content: from zope import schema, interface class IClan(interface.Interface): pass class IPerson(interface.Interface): first_name = schema.TextLine(title=u"First Name") last_name = schema.TextLine(title=u"Last Name") age = schema.Int(title=u"Age", required=False) single = schema.Bool(title=u"Is single ?", default=True) We assume that a Person is in a Clan. We can implement a Person: from persistence import Persistent class Person(Persistent): interface.implements(IPerson) first_name = None last_name = None age = None single = True Add form You can add a new Person in a clan like this: import zeam.form.ztk as form class Add(form.Form): form.context(IClan) label = u"New person" fields = form.Fields(IPerson) actions = form.Actions( form.AddAction("Add", factory=Person), form.CancelAction("Cancel")) actions['add'].fieldName = 'last_name' API All the API of zeam.form.base is exported as well. Actions - AddAction - Action which take an extra parameter, factory, to create an object stored on the content object. The created object is added with the help of INameChooser to get its identifier. The option fieldName will be used to lookup a value in the form data to give as potential identifier to INameChooser. Afterwards the created object is edited (like EditAction does) with the form data. - EditAction - Action which use the form data to change values on the content object, designated by the form fields, after validation of the form submission. - CancelAction - Simple action which return on default view of the content without validating the form submission. Fields Currently supported fields: - Date, Datetime: generate a text line input and parse/display the date using the locale, - TextLine, Text, Boolean, URI, and numbers (Int, Float …), - Choice: generate a select or a radio boxes (widget mode radio), - Object, - Collections: List, Set, Tuple in input and display mode: - Collection of choices: generate a widget with a list of checkboxes, - Collection of objects: generate a table to edit multiple objects, - Other collection: generate a widget with generic add an remove actions. For more documentation, please report to the doctests included in the code. Changelog 1.2.3 (2012/09/24) - Update API to use zeam.form.base 1.2.3. 1.2.2 (2012/07/25) - Adjust CheckboxWidgetExtractor to convert False input to bool False. 1.2.1 (2012/04/27) - Improve choice widgets, to make possible to customize the source of it. Add support for a IFormSourceBinder, that works like a IContextSourceBinder except it takes the form as parameter instead of the context (thus giving access to request as well for instance). - Add a method delete to the data manager. - Now use grokcore.chameleon instead of megrok.chameleon. 1.2 (2011/11/08) - Improve error reporting in collection widgets. Thanks to Novareto for the sponsorship. - Add an validation option in collection widgets while adding and removing values from it. Thanks to Novareto for the sponsorship. - Improve Javascript for collection widgets. Add an extra with fanstatic to automatically require required files. - If a collection widget is required, it will by default display one empty item in the collection when it is empty. That prevent an extra click to add it. - Various fixes in InvariantsValidator. - SchemaWidgetExtractor and SchemaField now catch Invalid exceptions. - Add support for the HTML 5 attribute required in every template. Use the attribute novalidate on the form tag to disable it. - Add a display widget for object and uri fields. - Add an option valueLength to the date widgets. Any Zope formatter size can be use (short, medium …). 1.0 (2010/10/19) - Add a multiselect widget for multiple choices. - Add a readonly widget. - Add a display widget for booleans and collections. - Add HTML5 widgets for URIs. - Schema field can be adapted now, even if they don’t have a interface (if they provide an attribute __name__). - Add more tests, fix issues in collection widgets, and invariant validator. - Translations are all located in zeam.form.base. - Update to use the last version of zeam.form.base. 1.0rc2 (2010/07/16) - Add radio widget for choices. - Add a display widgets for multiple choices. - All fields have the field CSS class. - Multiple choices widgets now properly respect the value of a vocabulary term. 1.0rc1 (2010/07/05) - Updated entry points registrations to be compatible with latest zeam.form.base. 1.0b3 (2010/06/22) - Field wrapper registration is now made thanks to an entry point. - Added invariants validation. - Added A generic adaptive datamanager that can adapt the form content to one or several interfaces. 1.0b2 (2010/05/13) - Improve widget initialization, and testing layer support. - Fix choice widgets when they are used with vocabulary factories. 1.0b1 (2010/05/03) - Initial release, with not all the widgets. - Author: Sylvain Viollon - Keywords: zeam form zope schema edit content - License: BSD - Categories - Package Index Owner: thefunny42, trollfot - DOAP record: zeam.form.ztk-1.2.3.xml
https://pypi.python.org/pypi/zeam.form.ztk/1.2.3
CC-MAIN-2017-09
refinedweb
916
51.85
. my @l = <a bb c d e f g h>; while @l.munch(3) -> $_ { .say } [download] I'd have thought the idiomatic Perl solution would splice: sub chunky { my ($n, @strs) = @_; my $str = ''; $str .= join (' ', splice @strs, 0, $n) . "\n" while @strs; return length $str ? $str : "\n"; } [download]. sub TIESCALAR{bless[0,$_[1]],$_[0]} sub FETCH{${$_[0]}[0]++%${$_[0]}[1]?" ":"\n"}; sub chunk_array{tie local$",'main',shift;"@_\n";} [download] Looks good, Can you explain how it works? This seems to work. knoppix@Microknoppix:~$ perl -E ' > @l = qw{ a bb c d e f g h }; > say sub { join q{ }, @_ }->( > grep defined, map shift @l, 1 .. 3 > ) while @l;' a bb c d e f g h knoppix@Microknoppix:~$ [download] I also piped the output through hexdump to check that there were no trailing spaces (which you do get without the grep). Update: Using List::Util::min() to remove the need for the grep. knoppix@Microknoppix:~$ perl -MList::Util=min -E ' > @l = qw{ a bb c d e f g h }; > say sub { join q{ }, @_ }->( > map shift @l, 1 .. min( 3, scalar @l ) > ) while @l;' a bb c d e f g h knoppix@Microknoppix:~$ [download] Cheers, JohnGG ;-) ] >>> def formatter(data, chunksize=3): return ''.join( (' ' if i % chunksize else '\n') + d for i, d in enumerate(data))[1:] >>> print formatter(("a", "bb", "c", "d", "e", "f", "g", "h"), 3) a bb c d e f g h [download] m] ] def chunk_array(n, vals): return "\n".join(" ".join(vals[i:i+n]) for i in range(0, len(vals), n)) [download] sub] #lang scheme (require scheme/string) (define (chunky li sz [str ""]) (let ([graft (lambda (s l) (string-append s (string-join l " ") "\n"))]) (if [<= (length li) sz] (graft str li) (let-values ([(x y) (split-at li sz)]) (chunky y sz (graft str x)))))) (display (chunky '("a" "bb" "c" "d" "e" "f" "g" "h") 3)) [download] +% mzscheme chunky.ss a bb c d e f g.
http://www.perlmonks.org/index.pl/jacques?node_id=861938
CC-MAIN-2016-40
refinedweb
334
78.69
Vue.js Routing With vue-router Subscribe On YouTube DemoCode haven’t installed Vue CLI on your system yet you need to complete the installation first by using the following command: $ npm install -g vue-cli Having executed the installation successfully a new command vue becomes available. You can use this command the initiate a new Vue project in the following way: $ vue init webpack vue-router-01 You’re being asked a few questions on the command line to complete the creation of the project. One question asks if you want to add vue-router to the project. Answer with Y (yes) to make sure the the Vue router package is added to the initial project setup. Next you need to change into the newly created project folder: $ cd vue-router-01 and complete the installation of dependencies by executing the following command: $ npm install Now the development web server can be started by entering: $ npm run dev Installing vue-router Package If you’re configuring your project with Vue CLI like shown before the vue-router package is added to your project automatically. If you would like to add the vue-router package manually to your project later, you can do so by using the npm command in the following way: $ npm install vue-router —save Add vue-router To Our Application If you’ve followed the recent steps and added vue-router to the initial configuration by using Vue CLI, routing is activated by default. The activation is taking place in file src/router/index.js: import Vue from 'vue' import Router from 'vue-router' import Hello from '@/components/Hello' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'Hello', component: Hello } ] }) First Router is imported from the vue-router package via import statement. Next you need to call to make sure that Router is added as a middleware to our Vue project. Vue.use(Router) Setting Up Routes A default route configuration is already included in file src/router/index.js. The route configuration is a JavaScript object consisting of three properties path, name and component. The configuration object is added to an array. The array needs to be assigned to the routes property of the object which is passed to the constructor of Router. As you can see in the listing above the Router instance is created and exported. To activate the Router configuration the Router instance is imported in file src/main.js: import router from './router' The Router instance is then used to create Vue application instance, as you can see in the following: new Vue({ el: '#app', router, template: '<App/>', components: { App } }) Standard Routes Standard routes are easy to define. The default route configuration is a typical example of a standard route: { path: '/', name: 'Hello', component: Hello } The route path is defined by using the path property. Setting the value of that property to ‘/’ means that this is the default route of your application. If the application is running on localhost:8080 for example the default route is activated when the user accesses in the browser. Routes With Parameters Let’s add a second route configuration object to the array: export default new Router({ routes: [ { path: '/', name: 'Hello', component: Hello }, { path: '/firstroute/:name', name: 'FirstRoute', component: FirstRoute } ] }) For the new route configuration the path value ‘/firstroute/:name’ is used. The last part of the path string is defining a routing parameter: name. The routing parameter enables us to pass a value to the routes component via URL, e.g.: In this case the value of the name routing parameter is bob. The parameter can be accessed in the route component FirstRoute. Let’s create a new file src/components/FirstRoute.vue and insert the code: <template> <div> <h1>{{ msg }}</h1> Hello {{ $route.params.name }} </div> </template> <script> export default { name: 'firstroute', data () { return { msg: 'FirstRoute' } } } </script> Embedding Routes Output If a certain route is accessed the assigned Vue component is called and rendering it’s HTML output based on the component’s template code. The HTML output of the route components needs to be part of the browser output. The following placeholder element is used to define the place in the HTML page where the route component output should be inserted: <router-view></router-view> In our Vue application this element is already placed in the template code of App component (in file src/App.vue), as you can see in the following: <template> <div id="app"> <img src="./assets/logo.png"> <router-view></router-view> </div> </template> If you now try to access FirstRoute in the browser you should see the output of component FirstRoute. Child Routes It’s also possible to define child routes. Let’s take a look at the following extended router configuration: export default new Router({ routes: [ { path: '/', name: 'Hello', component: Hello }, { path: '/firstroute/:name', name: 'FirstRoute', component: FirstRoute, children: [ { path: 'child', component: FirstRouteChild } ] } ] }) The property children has been added to the configuration object of FirstRoute. The property gets assigned an array with is containing another routes configuration object for route FirstRouteChild. Let’s implement FirstRouteChild as well. Create a new file FirstRouteChild.vue in folder src/components and insert the following code: <template> <div> <h1>{{ msg }}</h1> </div> </template> <script> export default { name: 'firstroutechild', data () { return { msg: 'FirstRouteChild' } } } </script> Linking To Routes The user is able to access a route by entering the corresponding URL in the browser directly. If you would like to add links to route URLs you can make use of the <router-link> element to generate a HTML link automatically: <router-linkLink to route one, child one</router-link> The to attribute contains the path to the route. You can also use the a colon before the to attribute to be able to assign a dynamic expression: <router-link :Link to dynamic route</router-link> To link to the three routes which are available in our application we’re changing the implementation of App component in file App.vue: <template> <div id="app"> <img src="./assets/logo.png"> <div> <ul> <li><router-linkHome</router-link></li> <li><router-linkFirstRoute</router-link></li> <li><router-linkFirstRouteChild</router-link></li> </ul> </div> <router-view><; } ul { list-style-type: none; padding: 0; } li { display: inline-block; margin: 0 10px; } a { color: #42b983; } </style> Now the final result should look like the following: By clicking on the link FirstRoute the view changes to include the output of FirstRoute component without reloading the page: A click on link FirstRouteChild changes the view to also contain the output of component FirstRouteChild in addition to the output of FirstRoute component: ONLINE COURSE: Vue.js: From Beginner To Professional Check out the great Vue.js online course by Bo Andersen with more than 15 hours of video content. Vue.js: From Beginner To Professional - Understand the theory of Vue.js and how it works under the hood - How to manage state in large Vue applications with Vuex - Use modern tools for developing and building Vue applications (e.g. webpack)
https://codingthesmartway.com/vue-js-routing-with-vue-router/
CC-MAIN-2020-40
refinedweb
1,170
56.89
Blog Tales Introduction to Excel XML Brian Jones. By default, Office documents will be open and accessible, as they will use standard ZIP and XML technologies with full documentation made available under a royalty-free license. These technologies are an improvement on the existing XML formats that shipped with Microsoft Office 2003 Editions, but those existing Office 2003 XML Reference Schemas can be used today to implement solutions that work with the document data and they provide a great way to gain an understanding of what developing with the new default formats will entail. The SpreadsheetML format in Microsoft Excel is fairly easy to work with, as it was designed especially to be human readable and editable. But many of you probably haven’t had a chance to take a look at the XML support in Excel. Once you get a handle on how it works, though, you’ll realize you have plenty of uses for the XML features, from converting data between databases and Web pages to sharing files among disparate applications. To get you started, I’ll build a sample in XML that will illustrate how it all works. As you follow along, you can use Office XP or Office 2003 for this example since both support SpreadsheetML in their versions of Excel. Using a text editor, I’m going to create a very simple table that looks like Figure 1, outlining seven steps to create an XML file that represents an Excel worksheet. Figure 1 The Table Example 1. Create the XML File To begin, create a new file in Notepad, and call it test.xml. Then follow the steps outlined here. First type the following: <?xml version="1.0"?> This declares that the file is an XML document adhering to the 1.0 version of the XML spec. It should always be found at the top of all your XML files. Next add the root element for the document. XML files always have one and only one root element that contains the rest of the document. For SpreadsheetML, the root element is <Workbook>. After the XML declaration, add that element so that your file now looks like this: <?xml version="1.0"?> <Workbook> </Workbook> 2. Declare the Namespace Now you’ll declare the namespace and add a prefix to the root element. Most XML documents have a namespace associated with them. Declaring the namespace of an XML file makes it a lot easier for users parsing your XML to know what type of XML they are dealing with. Even in Office there are a number of different uses for XML. One way to know when you are parsing a Word XML file as opposed to an Excel XML file, for example, is to look at the namespace. With Office XP, when the product group created the SpreadsheetML schema, we were still using namespaces in the form "urn:schemas-microsoft-com:office". Going forward, we’ll use URL namespaces, as we did with WordML in Office 2003 (//schemas.microsoft.com/office, for example). By adding the namespace declaration to the spreadsheet, your file should look like this: <?xml version="1.0"?> <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"> </Workbook> The last thing you’ll do for the namespace is use a prefix, rather than the default. Since the attributes are qualified for the SpreadsheetML schema, you need to do this if you are going to use any attributes. Let’s use "ss" (for spreadsheet) as the prefix. You’ll add "ss:" in front of all of your elements, and you’ll update your namespace declaration to say that the namespace applies to everything with an "ss:" in front of it, instead of just applying to the default XML elements, as shown here: <?xml version="1.0"?> <ss:Workbook xmlns: </ss:Workbook> Notice that the namespace declaration says xmlns:ss= instead of just xmlns=. This means that anything with an "ss:" in front of it applies to the spreadsheet namespace. 3. Add a Worksheet Next you’ll add a worksheet. Since you have an empty workbook, you need to declare the spreadsheet grid within the workbook. As you may know, workbooks can have multiple worksheets, but here you’ll just declare one. In addition, let’s declare a table inside the worksheet. The table is where all the grid data will go, and the file will now look like this: <?xml version="1.0"?> <ss:Workbook xmlns: <ss:Worksheet ss: <ss:Table> </ss:Table> </ss:Worksheet> </ss:Workbook> 4. Add the Header Row The first row in the table you want to generate has "First Name", "Last Name", and "Phone Number" in the three columns. Let’s add a <Row> tag as well as three <Cell> tags. The actual content of the cell is contained within a <Data> tag, so let’s add that as well. The file now looks like Figure 2. Figure 2 XML Worksheet Takes Form <> You now have a template for the table that you can open directly in Excel. It will look like Figure 3. Not too exciting, but it’s a start. Figure 3 Rudimentary Worksheet 5. Adjust the Column Widths Notice that the widths of the columns are too narrow for the content. Let’s add some XML to the file to specify the width you want for the columns. The resulting code is shown in Figure 4. Figure 4 Resizing the Columns <> Now open the file again in Excel. Notice that the columns are wider and that the text now fits (see Figure 5). There is another attribute you can set on the column element that tells it to use autofit for the widths. This only works for numbers and dates though. Since your cells are strings, you need to explicitly set the width. Figure 5 Resized Cells 6. Add the Remaining Data Now add those additional rows of data. This should be pretty easy. Just select that first "row" element and copy it. Then paste it five more times so you have six total rows. Now go through and update the values of the rows. If you are familiar with Extensible Stylesheet Language Transform (XSLT), you’ll see how you could easily generate an XSLT that could be applied to a DataSet to transform it into SpreadsheetML. Just repeat the Row tag for each row in your DataSet and add the values in each cell’s Data tag. After applying all the data, your XML should look like Figure 6, which has been abbreviated for space. Figure 7 shows the full table in Excel. Figure 6 XML Table with all Data <?xml version="1.0"?> <ss:Workbook xmlns: <ss:Worksheet ss: <ss:Table> <ss:Column ss: <ss:Column ss: <ss:Column ss: <ss:Row> :Row> </ss:Table> </ss:Worksheet> </ss:Workbook> Figure 7 Worksheet with Data 7. Add Header Formatting As you can see, the first row does not look like a column header, so let’s format it with bold text so that it’s clearly the header. All you need to do is generate a style that has bold text, and then reference that style with the first row. First, add the following XML in front of the Worksheet tag: <ss:Styles> <ss:Style ss: <ss:Font ss: </ss:Style> </ss:Styles> This creates a style whose ID is "1" and has bold applied to it. Next, update the first row element to reference StyleID 1. The row code should now look like this: <ss:Row ss: Your XML should now look like Figure 8, and Figure 9 shows how it looks in Excel. Figure 8 Bolding the Header Row <?xml version="1.0"?> <ss:Workbook xmlns: <ss:Styles> <ss:Style ss: <ss:Font ss: </ss:Style> </ss:Styles> <ss:Worksheet ss: <ss:Table> <ss:Column ss: <ss:Column ss: <ss:Column ss: <ss:Row ss: :Table> </ss:Worksheet> </ss:Workbook> Figure 9 The Completed Worksheet Wrap-Up That was a pretty simple example, but it’s a good introduction if you’re new to Office XML (or even new to XML in general). The new XML formats for future versions of Excel will look different than what I’ve shown you with SpreadsheetML, but there will also be some similarities. It’s good to become familiar with the existing schemas, and I’ll start posting a lot more about the new schemas on my blog at blogs.msdn.com/brian_jones. Blog Tales Resources Are you looking to get a jump on becoming an Office Open XML Formats expert? Or are you just curious about how the changes in the next version of Microsoft Office will impact your environment? Check out these sites for more information. XML in Office Development Whether you’re just getting up to speed with XML or you’ve been making use of XML support in Microsoft Office since the release of Office 2003, there is always more to learn. The Office Developer Center has an excellent section dedicated to XML in Office Development. Here you’ll find tutorials, code samples, reference documentation, and useful tools. XML in Office Technical Articles Looking for some not-so-light reading about XML? Check out this collection of in-depth articles on using XML to improve how your organization works. Jensen Harris: An Office User Interface Blog While changes to XML in Microsoft Office are buried beneath the surface, the new user interfaces found in familiar apps like Microsoft Excel and Word are a bit more readily evident. Jensen Harris, a member of the Microsoft Office user experience team, keeps a blog where he discuss the new UI designs in Office applications and explains why these changes were made. Brian Jones is a program manager at Microsoft working on XML functionality and file formats in Office. Most recently, Brian has worked on the Microsoft Office Open XML Formats that will be introduced in Office 12. This column was adapted from his blog, which can be found at blogs.msdn.com/brian_jones. © 2008 Microsoft Corporation and CMP Media, LLC. All rights reserved; reproduction in part or in whole without permission is prohibited.
https://docs.microsoft.com/en-us/previous-versions/technet-magazine/cc161037(v=msdn.10)
CC-MAIN-2019-22
refinedweb
1,686
71.34
I'm writing a set of Powershell Cmdlets that require Oauth2 authentication. I currently am able to get to the point where a new browser window opens and the user copies out the Access Authentication Code to pass back to the cmdlets. However, this means I have to have a separate cmdlet that now accepts the Auth Code as input. Is there any way to invoke the Read-Host? I've tried the instructions but despite being listed, ReadHostCommand isn't showing up under the Microsoft.PowerShell.Commands namespace, but something like WhereObjectCommand is. I've tried Console.ReadLine() but it is just ignored when running the Cmdlet. The ReadHostCommand is in the Microsoft.PowerShell.Commands namespace but you have to reference the Microsoft.PowerShell.Commands.Utility.dll assembly.
https://codedump.io/share/JOYaXI6da1Bm/1/invoking-read-host-cmdlet-from-within-c-custom-cmdlet
CC-MAIN-2017-34
refinedweb
129
51.34
03-29-2017 05:22 PM Hi all, I'm trying to replace the current 3D model of the buffer with a 3D model I have in JT format. Is there a way to use that JT to replace the 3D graphic of the buffer or someway to convert my JT to .s3d, which I noticed is the format the 3D models are in. I will be using this as an actual buffer in the simulation but I want to replace it with a rack I have. Thanks! Solved! Go to Solution. 03-30-2017 03:06 AM Hi csadler, You can easly replace the default graphics with your jt model. Select the object and in the home tab use Open2D/3D you will get the 3D graphics of the selected object in new window. Now in the Edit tab use Import Graphics select your jt model. Hope this solves the problem. Regards, ABHIRATH 03-30-2017 03:13 AM have you tried to open your 3d object in a separate window and drag & drop the jt file in to the window ? or import jt file ( amongst other file formats) through menu (s.b.) 03-30-2017 11:00 AM 03-30-2017 11:14 AM
https://community.plm.automation.siemens.com/t5/Plant-Simulation-Forum/Exchange-Convert-3D-graphics/m-p/400039/highlight/true
CC-MAIN-2019-35
refinedweb
206
80.92
- Database Access - Inserting Records - Notes on the Attached Fixture Library - That’s a Wrap! article provides Database Access Inserting Records Dbfit includes a general purpose Execute fixture that lets you execute most any SQL statement you like. However, you should use that only when there is not a more specific fixture available for the task at hand. Thus, to insert data into a table you can pass a SQL insert statement to the Execute fixture (left) but it is better to use the Insert fixture (right). Here is a complete test table using the Insert fixture. A powerful feature of this fixture is that in an atomic operation you can insert records into the table and retrieve IDs for those inserted records! Here you can see that the first three IDs are returned and also stored into symbols. Reference: CleanCode.DataBaseNotes.CrudOperations Updating Records For updating records Dbfit also provides a more specific fixture available for the task at hand, the Update fixture. Thus, to update data in a table you can pass a SQL update statement to the Execute fixture (left) but it is better to use the Update fixture (right) when conditions allow (explained below). With the Update fixture you can convert a standard SQL (left) into the test table (right): You may include multiple columns in the selector; the example selects on both the RecordId field and the Enabled field. You may also include multiple fields to update though only one is shown in the example ( Active). The main advantage of the Update fixture over a standard SQL update statement is that you can use different selection criteria and different update values for every record. The example shows the same values because it is purposely matching the SQL statement. But clearly you are free to use different values in each cell in the test table. The main disadvantage of the Update fixture is that you cannot provide an expression or even a simple field name to SQL-you may use only variables or constants known in the scope of the FitNesse test page. That is, within a SQL update statement you could use an expression (e.g. SET Price=Price+1) or a field name (e.g. SET BillDate=InvoiceDate). Those cannot be used with the Update fixture. Reference: CleanCode.DataBaseNotes.CrudOperations Deleting Records For deleting records Dbfit provides a more specific fixture available-sort of(!). The Clean fixture is available but is undocumented. So just as SQL Server has well-known yet officially unsupported stored procs and such that you should not depend on, nor should you rely on undocumented features in DbFit. But that is not a great loss; I found DbFit’s Clean fixture unsatisfactory anyway. Rather, I have included a DbClean fixture in my project library that provides more capability. There are several disadvantages of the generic Execute fixture and the DbFit Clean fixture. First, neither the generic Execute fixture nor the Clean fixture supports FitNesse symbols. (Recall that you could, for example, define a FitNesse symbol TargetPrice, then use that in the Query fixture as in: SELECT a,b,c WHERE Price > @TargetPrice.) Second, the Clean output field is a Boolean, reporting success or failure but not how many records were processed. Finally, I have not been able to characterize what causes it, but both of these fixtures seem to sporadically fail. DbClean overcomes all of those disadvantages. The Clean output field indicates how many records matched the WHERE clause and were deleted. The ResultDetails output field will be null for a successful operation; if a problem occurred, it will report an error message. DbClean also supports symbols just like Dbfit’s Query fixture so you can build a parameterized WHERE clause when necessary. My recommendation is to use DbClean twice in any database test, once at the start of the test where you do a sanity check to confirm that there are no matching records (thus checking for 0 returned in the Clean? Column)… … and also at the end of the test where you check for the proper record counts inserted during this test and delete them… Any errors at the start of the test indicate some test (possibly the same test) left detritus behind. Errors at the end of the test indicate the current test likely has an error (that may or may not be revealed in other test tables on the page). Alas, DbClean has one important caveat. Because it is external to DbFit, you have to explicitly perform a commit on your DbFit operations before you use DbClean. If you do not, the transaction is left open, blocking DbClean from completing and it will eventually time out and fail. See the reference page to see an example. Reference: CleanCode.DataBaseNotes.CrudOperations Connecting to a Database To connect to a database with DbFit, you must choose either flow mode or standalone mode. The DbFit manual recommends flow mode over standalone mode, in that flow mode provides automatic transaction management “… and some other shortcuts” though it is not clear what that entails. You invoke flow mode with the appropriate database fixture-this one is for SQL Server: But flow mode has one serious restriction; the above connection table must be the very first table on the page-that includes any tables in SetUp or SuiteSetUp pages! And that also precludes having an import fixture to define your namespaces, hence the use of the fully qualified name dbfit.SqlServerTest above. One common scenario that causes mysterious problems is if you choose to use flow mode, putting the above connection table on your test page, while at the same time having an inherited SetUp page that brings in some other test tables before it, violating the absolutely-first-table rule. You must override the inherited SetUp page in such a situation. If you need to interact in one test with more than one database you must use standalone mode because of the above rule. In standalone mode use the DatabaseEnvironment fixture; you can sprinkle multiple DatabaseEnvironments in one test, though only one database is active at a time. Particularly when using multiple databases I recommend doing a sanity check immediately after connecting to each database, like this one for SQL Server: As the first assertion in a test this lets you know immediately whether you are have connected to the database you think you did and whether you can in fact converse with it. Reference: Flow vs Standalone – see Chapter 12 Notes on the Attached Fixture Library Included with this series of articles is an archive containing both a library of custom FitNesse fixtures (CleanCodeFixtures.dll) and a FitNesse suite of tests that illustrate the fixture library as well as document many of the issues discussed in this series. The test suite consists of these subsuites: Refer to the GeneralUtilityFixtureNotes for documentation and examples on how to use the fixtures. (You could also review the source code, of course; that is included as well.) Here is a snapshot of the execution of the entire suite. FitNesse results begin with a one-line summary at the top, which expands into a one-line-per-test summary. Both of those are shown here. (Note that there are deliberately 6 errors injected into this suite for reasons explained on those particular test pages.) Below that is a complete transcript of the entire test run (not shown:-). You will see three of the four sub-suites mentioned above in the figure; the fourth one, Control Flow Notes, could not be included in an automated test run because it fiddles with the control flow. If you want to execute any of the control flow tests (or any others not marked as executable by default) you can either edit the properties on the particular page, or just add this suffix “ ?test” to the URL and reload the particular page. Example (put this all on one line of course): Reference: CleanCode (Remember, non-hyperlinked references point to.) That’s a Wrap! I did not expect this series to turn into seven parts when I began writing but I suppose, in retrospect, having some 35 pages of notes should have given me a clue! But there you have it. Colleagues in my day job have often said they were glad I took copious notes on issues I encountered when I would venture into exploring a new technology that we were going to be adopting. It saved them a lot of time and effort not having to resolve many of the same issues. I hope that you can similarly use these “tips from the trenches” and save some effort so you have more time to get on with your main focus. Let me know!
https://www.red-gate.com/simple-talk/dotnet/.net-tools/acceptance-testing-with-fitnesse-database-fixtures,-project-overview/
CC-MAIN-2019-35
refinedweb
1,453
58.72
Jo – Application app = null; public void JournalCommentTimer() { app = this.Application; UIApplication uiapp = new UIApplication(app); double seconds = 10; Timer timer = new Timer(seconds * 1000); timer.Elapsed += new ElapsedEventHandler(timer_Elapsed); timer.Enabled = true; } void timer_Elapsed(object sender, ElapsedEventArgs e) { app.WriteJournalComment("New Timestamp", true); } Add this to your file to compile the code above: using System.Timers; Advertisements 2 thoughts on “Journal time-stamps at a set interval for another #RTCEUR #Revit API wish” Interesting- will Arnost jump on this and say “don’t use threads with the API!”? or is this somehow simple and non-document-oriented enough to be able to use without problem? Seemed safe in my testing. It isn’t changing the Revit model in a separate thread. I thought there might be problem when Revit was busy during a File Upgrade, but it worked fine, writing the timestamps to the journal file as it upgraded the RVT.
https://boostyourbim.wordpress.com/2016/10/22/journal-time-stamps-at-a-set-interval-for-another-rtceur-revit-api-wish/
CC-MAIN-2018-17
refinedweb
151
57.67
Knockout JS as we know is a highly versatile JavaScript library that helps us implement the MVVM pattern on the client by providing us with two way data binding and templating capabilities. Today we will use Knockout JS and ASP.NET Web API to build an application that represents data in a tabular format with AJAX based sorting and paging capabilities. Representing Tabular data in a table is as old as web itself and today end users expect a certain amount of features and functionality built in. These include fast access, sorting, paging and filtering. There are well established libraries like Datatables.net that already do these for us. However, knowing how something is implemented, helps us tweak things to our advantage, because no two requirements are the same, ever. This article is published from the DNC .NET Magazine – A Free High Quality Digital Magazine for .NET professionals published once every two months. Subscribe to this eMagazine for Free We have a table of user accounts with a few hundred user records. The requirement is to be able to list this user data in a grid layout and provide sorting and paging capabilities on the client side. Prerequisites We assume familiarity with ASP.NET Web API and concepts of MVVM. We’ll walk through the specifics of Knockout model binding. We start off in Visual Studio with a new ASP.NET MVC 4 project using the Empty template. We will start from scratch and not assume any dependencies. Installing Dependencies We start by installing jQuery and Knockout JS using the Nuget Package Management console. PM> install-package jQuery PM> install-package knockoutjs Next we update our Web API dependencies PM> update-package Microsoft.AspNet.WebApi We install Entity Framework for the Data Layer PM> install-package EntityFramework We also get BootStrap styles and scripts from Nuget using PM> install-package Twitter.Bootstrap Step 1: In the Model folder, add a class called Contact with the following properties. public class Contact{public int Id { get; set; }public string Name { get; set; }public string Email { get; set; }public DateTime DateOfBirth { get; set; }public string PhoneNumber { get; set; }public string City { get; set; }public string State { get; set; }public string Country { get; set; }} Build the solution. Step 2: Set up a connection string to point to a LocalDb instance as follows <add name="DefaultConnection" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename='|DataDirectory|\KODatatableContext.mdf';Integrated Security=True" providerName="System.Data.SqlClient" /> You can point to a local SQL Express or SQL Server too, simply update the connection string appropriately. Step 3: Next we scaffold a Controller, Repository and Views using MVC Scaffolding Step 4: In the generated KoDatatableContext class, add the following constructor. public KoDatatableContext():base("DefaultConnection") { } This forces the DB Context to use the connection string. If you don’t provide this, default setting is to look for a SQL Server at .\SQLExpress and create a DB Based on the Context’s namespace. Step 5: Run the application and visit the /Contacts/Index page. This will bring up the empty Index page by first generating the DB behind the scenes. Step 6: To have multiple pages of contacts we need some pre-generated data. I found to be a pretty neat site for this purpose. I added all the columns except Id and requested it to generate 100 rows into an Insert Script. Once the script is downloaded, connect to the DB using the Database Explorer in Visual Studio and run it on the KnockoutDataTableContext DB. Refresh the /Contacts/Index page and you should see 100 rows of data. The page Index looks rather plain vanilla, so let’s get BootStrap kicking and spruce it up a little. Step 1: Add _ViewStart.cshtml in the Views folder. Update the markup to contain only the following @{ Layout = "~/Views/Shared/_Layout.cshtml";} Step 2: Create a folder /Views/Shared and add _Layout.cshtml to it. Step 3: To make use of Bundling and Minification we need to add one more Nuget package PM> install-package Microsoft.AspNet.Web.Optimization Once the optimization bundle is downloaded, setup the BundleConfig.cs. In App_Start folder, add a BundleConfig.cs public class BundleConfig{public static void RegisterBundles(BundleCollection bundles){ bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/html5shiv.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include( "~/Scripts/jquery-ui-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.unobtrusive*", "~/Scripts/jquery.validate*")); bundles.Add(new ScriptBundle("~/bundles/knockout").Include( "~/Scripts/knockout-{version}.js")); bundles.Add(new StyleBundle("~/Styles/bootstrap/css").Include( "~/Content/bootstrap-responsive.css", "~/Content/bootstrap.css"));} } This sets up BootStrap and jQuery script & style bundles. Step 4: Update the _Layout.cshtml to use the bootstrap CSS and Script bundles @{ ViewBag.<title>@ViewBag.Title</title>@Styles.Render("~/Styles/bootstrap/css")</head><body><div class="navbar navbar-inverse"> <div class="navbar-inner"> <div class="brand"> @ViewBag.Title </div> </div></div><div class="container-fluid"> <div class="row-fluid"> @RenderBody() </div> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/knockout") @Scripts.Render("~/bundles/bootstrap") @RenderSection("Scripts", false) </div></body></html> Step 5: In the Index.cshtml add the class table to the container <table class="table">…</table> If we run the app now, it should look much cleaner We are all set, let’s implement the rest of the features. Since we want all the rendering to be done on the client side, instead of using the ASP.NET MVC Controller and rendering the View on the server, we’ll switch to ASP.NET Web API and change the markup to use Knockout JS. Step 1: Add a new API Controller called AddressBookController Step 2: Update the existing Contacts controller so that it doesn’t return any data public ViewResult Index(){ return View();} We will step through the KO Script incrementally. To start off with, we add a new JavaScript file called ko-datatable.js under the Scripts folder. This will contain our view model and data-binding code. Step 1: As a first step, we setup our viewModel to contain only the contacts collection as an observable collection. When the document is loaded, it calls our AddressBook api and gets the list or contacts. It then pushes them into the contacts viewModel property. Finally we call ko.applyBindings(…) to do the data binding. /// <reference path="knockout-2.2.1.js" />/// <reference path="jquery-2.0.2.js" />var viewModel = function (){$this = this;$this.contacts = ko.observableArray();} $(document).ready(function (){$.ajax({ url: "/api/AddressBook", type: "GET"}).done(function (data){ var vm = new viewModel(); vm.contacts(data); ko.applyBindings(vm);});}); Step 2: To utilize the ViewModel data, we update the Index.cshtml to use Knockout Databinding syntax instead of the previous server side razor implementation. We use the foreach data-binding to bind the contacts collection to the table (body). Whereas we bind each td to the field names. <tbody data-<tr> <td data-</td> <td data-</td> <td data-</td> <td data-</td> <td data-</td> <td data-</td> <td data-</td></tr></tbody> At this point if we run the app, we’ll see the same type of table layout we had seen for the server side binding. The only difference now is it’s using Knockout’s Databinding and templating to generate the table on the client side. For paged data, we need to be able to track the following: - Current Page Index: Starts at zero and increases/decreases as user selects different pages - Page Size: A value indicating the number of items in the page - All elements: The complete list of elements from which the current page will be sliced out. We add the above properties in our view Model and add a Knockout Computed observable to calculate the current page. Computed Observables in Knockout are functions that are recalculated automatically when the observables used in the function change. So our computed observable returns a slice of the array elements from the complete list of Contacts. By default page size is 10 and current page index is 0, so the first 10 records are shown. There are two functions previousPage and nextFunction. These are bound to the Previous and Next buttons’ click events. The next button circles back to the first page once it reaches the last page. Similarly the previous button circles back to the last page once it is reaches the first page. var viewModel = function (){$this = this;$this.currentPage = ko.observable();$this.pageSize = ko.observable(10);$this.currentPageIndex = ko.observable(0);$this.contacts = ko.observableArray();$this.currentPage = ko.computed(function (){ var pagesize = parseInt($this.pageSize(), 10), startIndex = pagesize * $this.currentPageIndex(), endIndex = startIndex + pagesize; return $this.contacts.slice(startIndex, endIndex);});$this.nextPage = function (){ if ((($this.currentPageIndex() + 1) * $this.pageSize()) < $this.contacts().length) { $this.currentPageIndex($this.currentPageIndex() + 1); } else { $this.currentPageIndex(0); }}$this.previousPage = function (){ if ($this.currentPageIndex() > 0) { $this.currentPageIndex($this.currentPageIndex() - 1); } else { $this.currentPageIndex((Math.ceil($this.contacts().length / $this.pageSize())) - 1); }}} We add the following Table footer markup for the previous next and current page index. <tfoot><tr> <td colspan="7"> <button data-<i class="icon-step-backward"></i></button> Page<label data-</label> <button data-<i class="icon-step-forward"></i></button> </td></tr></tfoot> If we run the app now, the previous next buttons will be functional and we can see the data change accordingly. $this.contacts.sort(function (left, right){ return left.Name < right.Name ? 1 : -1;}); However, the above is only a one-way sort, as in, after it’s sorted say in ‘ascending’ order, there is no toggling to ‘descending’ order, like is the case with most sort functionality in tabular data representations. To be able to toggle between ascending and descending, we have to store the current status in our ViewModel. Another issue is that the Name property is hard coded above. We would like to sort based on the column header we click on. So instead of the function picking the Name property, we should determine the Property to be sorted on at run time. Updating the Markup We update our Index.cshtml’s table header as follows <thead><tr data- <th data-Name </th> <th data-Email </th> <th data-Date of Birth </th> <th data-Phone Number </th> <th data-City </th> <th data-State </th> <th data-Country </th></tr></thead> We have bound the click event of the table’s header row to a function called sortTable in the ViewModel. We will see the implementation of this function shortly. Next we have used HTML5 data- attributes to define a new attribute called data-column and set the value to the name of each property that column is bound to. 1. First we add a property that saves the current Sort type (ascending or descending) and set it to ‘ascending’ by default. $this.sortType = "ascending"; 2. Next we add the function sortTable that does the actual sorting $this.sortTable = function (viewModel, e){var orderProp = $(e.target).attr("data-column")$this.contacts.sort(function (left, right){ leftVal = left[orderProp]; rightVal = right[orderProp]; if ($this.sortType == "ascending") { return leftVal < rightVal ? 1 : -1; } else { return leftVal > rightVal ? 1 : -1; }});$this.sortType = ($this.sortType == "ascending") ? "descending" : "ascending";}}; This code works as follows a. The function first extracts the column on which the click happened. It uses the event object e and picks out the value in the ‘data-column’ attribute. As we saw in the markup, ‘data-column’ has the name of the property to which that column’s data is bound to. b. Once we have which column to sort on, we call the ‘contacts’ observable array’s sort method with a custom delegate that return 1 or -1 based on the comparison result. c. In the sort function, we extract the property using the column name. Since this is now coming from the ‘data-column’ attribute, we will automatically get the correct property name to compare. d. Next, based on whether the current sortType is ascending or descending, we return the value 1 or -1. e. Once the entire array has been sorted, we set the sortType attribute to opposite of what it was. That’s all that needs to be done to get sorting going! If you run the application now, you can click on the columns and see sorting in action on each. Usually when we have a sortable table, the column on which it is sorted has an arrow indicating if it is sorted in ascending or descending order. In our view model, we are already saving the sortType, we will add two more properties. - First is iconType - this is set to the bootstrap css style or ‘icon-chevron-up’ or ‘icon-chevron-down’. This is set in the sortTable function when user click on the header column. - Second property is for saving the name of the column that the table is currently sorted on – currentColumn. This value is also set in sortTable function. $this.sortTable = function (viewModel, e){var orderProp = $(e.target).attr("data-column")$this.currentColumn(orderProp);$this.contacts.sort(function (left, right){ …}…$this.iconType(($this.sortType == "ascending") ? "icon-chevron-up" : "icon-chevron-down");} Next we update the Table header markup, to do two things 1. Set the arrow visible based on the currentColumn and invisible for the rest of the columns. 2. Set the arrow to ascending or descending based on sortType To do this we do the following: a. Add a couple of CSS styles that we’ll set dynamically <style type="text/css"> .isVisible { display: inline; } .isHidden { display: none; }</style> b. In the table header, for every column we add a span whose visibility is set based on whether the currentColumn value is the same as for current one. For the Name column if the currentColumn() value is ‘Name’ then we set the class to ‘isVisible’ which in turn makes the span and its contents visible. For all other values of currentColumn(), the span remain hidden. <table class="table"><thead> <tr data- <th data-Name <span data- <!-- add image here --> </span> </th> … <tr></thead></table> c. Finally we add an icon in the placeholder above and set the image by binding the class attribute to iconType <i data-</i> If we run the application now, we can see the sorting and the sort indicator in action. For example the snapshot below shows that the table is sorted in ascending order of the Name column. The final feature that we’ll add is to let users select the number of rows per page. Currently it is hard-coded to 10. We will add an html select to the footer with various other sizes and bind it to the pageSize property of our ViewModel. Because the currentPage property is computed and one of the observables it depends on is pageSize, any change in pageSize will re-compute the currentPage property. This will result in re-calculation and rendering of the table. As shown in the markup below we have <tfoot><tr> <td> Number of items per page: <select id="pageSizeSelector" data- > </td>…</tr></tfoot> Here is our final Table With that have completed our requirements of having a Sortable Grid with pagination. We saw how to use ASP.NET Web API and Knockout JS for templating and data-binding to get pretty rich functionality with minimal code. We can certainly improve on this model. For example if we have more than a few hundred rows of data, we should use server side data selection and instead of bringing back the complete dataset, use only the current page’s data. This will offer the right balance between performance and richness of features. Overall Knockout is a powerful library and can be used as a drop-in enhancement to bring in rich functionality on the client side. Download the entire source code of this article (Github)
http://www.dotnetcurry.com/showarticle.aspx?ID=942
CC-MAIN-2014-49
refinedweb
2,642
56.96
STRTOUL(3) BSD Programmer's Manual STRTOUL(3) strtoul, strtoull, strtouq - convert a string to an unsigned long or un- signed long long integer #include <stdlib.h> #include <limits.h> unsigned long strtoul(const char *nptr, char **endptr, int base); #include <stdlib.h> #include <limits.h> unsigned long long strtoull(const char *nptr, char **endptr, int base); #include <sys/types.h> #include <stdlib.h> #include <limits.h> u_quad_t strtouq(const char *nptr, char **endptr, int base); The strtoul() function converts the string in nptr to an unsigned long value. The strtoull() function converts the string in nptr to an unsigned long long value. The strtouq() function is a deprecated equivalent of strtoull() and is provided for backwards compatibility with legacy pro- grams. The conversion is done according to the given base, which must be a number between 2 and 36 inclusive or the special value 0. If the string in nptr represents a negative number, it will be converted to its un- signed equivalent. This behavior is consistent with what happens when a signed integer type is cast to its unsigned counterpart. returns the result of the conversion, unless the value would overflow, in which case ULONG_MAX is returned and errno is set to ERANGE. If there was a leading minus sign, strtoul() returns the (unsigned) negation of the absolute value of the number, unless the abso- lute value would overflow. In this case, strtoul() returns ULONG_MAX and sets the global variable errno to ERANGE. The strtoull() function has identical return values except that ULLONG_MAX is used to indicate overflow. There is no way to determine if strtoul() has processed a negative number (and returned an unsigned value) short of examining the string in nptr directly. Ensuring that a string is a valid number (i.e., in range and containing no trailing characters) requires clearing errno beforehand explicitly since errno is not changed on a successful call to strtoul(), and the re- turn value of strtoul() cannot be used unambiguously to signal an error: char *ep; unsigned long ulval; ... errno = 0; ulval = strtoul(buf, &ep, 10); if (buf[0] == '\0' || *ep != '\0') goto not_a_number; if (errno == ERANGE && ulval == ULONG_MAX) goto out_of_range; This example will accept "12" but not "12foo" or "12\n". If trailing whi- tespace is acceptable, further checks must be done on *ep; alternately, use sscanf(3). [ERANGE] The given string was out of range; the value converted has been clamped. sscanf(3), strtol(3) The strtoul() and strtoull() functions conform to ANSI/ISO/IEC 9899-1999 ("ANSI C99"). The strtouq() function is a BSD extension and is provided for backwards compatibility with legacy programs. Ignores the current locale. MirOS BSD #10-current June 25,.
http://mirbsd.mirsolutions.de/htman/sparc/man3/strtoull.htm
crawl-003
refinedweb
447
56.15
If allocate might be written over data or code in your program, and it might cause a program abort. That’s because scanf() copies information to the address given by the argument, and in this case, the argument is an uninitialized pointer; name might point anywhere. Most programmers regard this as highly humorous, but only in other people’s programs. The simplest course is to include an explicit array size in the declaration: char name[81]; After you have set aside space for the string, you can read the string. The C library supplies a trio of functions that can read strings: scanf(), gets(), and fgets(). The most commonly used one is gets(), which we discuss first. The gets() Function The gets() (get string) function is very handy for interactive programs. It gets a string from your system’s standard input device, normally your keyboard. Because a string has no predetermined length, gets() needs a way to know when to stop. Its method is to read characters until it reaches a newline (\n) character, which you generate by pressing the Enter key. It takes all the characters up to (but not including) the newline, tacks on a null character (\0), and gives the string to the calling program. The newline character itself is read and discarded so that the next read begins at the start of the next line. Following program shows a simple means of using gets(). #include <stdio.h> #define MAX 81 int main() { char name[MAX]; /* allot space */ printf("Hi, what's your name?\n"); gets(name); /* place string into name array */ printf("Nice name, %s.\n", name); getchar(); return 0; }
http://www.loopandbreak.com/string-input-in-c/
CC-MAIN-2021-17
refinedweb
274
71.75
I am trying to write a simple program that takes in a string, reverses the letters in it and displays the result. I have not got it finished but am stuck as I keep getting this error: Application Error The instruction at "0x004010a7" referenced memory at "0x00000065". The memory could not be "read". this is the code that I have is not much but it is simple and I cannot see the problem. This error only occurs when either of the printf statments are included [code] #include <stdio.h> char *p; int main(void) { char string; printf("Type in a string: "); string = getchar(); p=string; printf("%s\n", string); printf("%c\n", *p); } [code] I am lost can you help please.
http://cboard.cprogramming.com/c-programming/17933-help-error-beginner.html
CC-MAIN-2013-20
refinedweb
121
77.77
Purpose: This demo implements a simple harmonic oscillator in a 2D neural population. Comments: This is more visually interesting on its own than the integrator, but the principle is the same. Here, instead of having the recurrent input just integrate (i.e. feeding the full input value back to the population), we have two dimensions which interact. In Nengo there is a ‘Linear System’ template which can also be used to quickly construct a harmonic oscillator (or any other linear system). Usage: When you run this demo, it will sit at zero while there is no input, and then the input will cause it to begin oscillating. It will continue to oscillate without further input. You can put inputs in to see the effects. It is very difficult to have it stop oscillating. You can imagine this would be easy to do by either introducing control as in the controlled integrator demo (so you can stop the oscillation wherever it is), or by changing the tuning curves of the neurons (hint: so none represent values between -.3 and 3, say) so when the state goes inside the (e.g., .3 radius) circle, the state goes to zero. Also, if you want a very robust oscillator, you can increase the feedback matrix to be slightly greater than identity. Output: See the screen capture below. You will get a sine and cosine in the 2D output. import nef net=nef.Network('Oscillator') #Create the network object net.make_input('input',[1,0], zero_after_time=0.1) #Create a controllable input function with a #starting value of 1 and zero, then make it go #to zero after .1s net.make('A',200,2) #Make a population with 200 neurons, 2 dimensions net.connect('input','A') net.connect('A','A',[[1,1],[-1,1]],pstc=0.1) #Recurrently connect the population #with the connection matrix for a #simple harmonic oscillator mapped #to neurons with the NEF net.add_to_nengo()
http://nengo.ca/docs/html/demos/oscillator.html
CC-MAIN-2017-09
refinedweb
322
56.55
SPF From Progteam SPF is problem number 1523 on the Peking University ACM site. Paul's solution: #include <map> #include <set> #include <iostream> using namespace std; typedef set<int> VERTEX_LIST; typedef map<int, set<int> > UGRAPH; map<int, bool> visited; map<int, int> parent; map<int, int> num; map<int, int> low; map<int, int> AP; const int ROOT = 1; const int HOLDER = 1; //The number of unique "low" numbers in the neighbors of the articulation point // signifies the number of subnets that would be created by the removal of the // articulation point. This function is only useful AFTER the all the vertices // in the graph have been processed by findAP(). int subnetCheck(UGRAPH &graph, int v) { set<int> check; set<int>::iterator sitr; set<int> &neighbors = graph[v]; for(sitr = neighbors.begin(); sitr != neighbors.end(); ++sitr) { int w = *sitr; check.insert(low[w]); } return check.size(); } //Main function that looks for articulation points void findAP(UGRAPH &graph, int v, int counter) { visited[v] = true; low[v] = counter; num[v] = counter; //For each neighbor w of v do: set<int>::iterator sitr; set<int> &neighbors = graph[v]; for(sitr = neighbors.begin(); sitr != neighbors.end(); ++sitr) { int w = *sitr; //If w not yet visited do: if (!visited[w]) { //w.parent = v parent[w] = v; //DFS findAP(graph, w, ++counter); //Update v.low low[v] = min(low[v], low[w]); //if v is not the root and the w.low > v.num do: if ((num[v] != ROOT) && (low[w] >= num[v])) { //We have found an articulation point //However we cannot tell how many subnets remain till after // all vertices in the graph have been processed by findAP() //So just set up a temporary HOLDER variable. AP[v] = HOLDER; } //Else w has already been visited, do: } else { //if v.parent != w: // we have a back-edge! if (parent[v] != w) { //update v.low to be the min(v.low, w.num) low[v] = min(low[v], num[w]); } } } //If we are done finally finished the DFS and have returned back to // the root of the new DFS tree then: if (ROOT == num[v]) { //Check how many subnets might exist if we remove the root. //Most online sources say that its sufficient to check whether // the root has 2 or more children, in which case the root is // definitely an articulation point. However this is only true // if the children of the root are not connected to each other. // So if the children have different "low" numbers, then we're // okay since that means they're not interconnected to each other. int root_check = subnetCheck(graph, v); if (2 <= root_check) { AP[v] = root_check; } //Going to perform subnetCheck() on each of the nodes we identified // as being articulation points to properly find out how many // subnets are left over once we remove those vertices. map<int, int>::iterator mitr; for (mitr = AP.begin(); mitr != AP.end(); ++mitr) { int ap_node = mitr->first; int val = mitr->second; if (val == HOLDER) { AP[ap_node] = subnetCheck(graph, ap_node); } } } } //Driver for the findAP() function void findAPDriver(UGRAPH &graph, int root) { //Run the DFS on the arbitrarily chosen root vertex. findAP(graph, root, ROOT); //Annoying printing requirements for PKU map<int, int>::iterator itr; if (0 < AP.size()) { for (itr = AP.begin(); itr != AP.end(); ++itr) { cout << " SPF node " << itr->first << " leaves " << itr->second << " subnets" << endl; } } else { cout << " No SPF nodes" << endl; } } int main() { UGRAPH graph; VERTEX_LIST vlist; int network = 1; int root = -1; while (true) { int a, b; cin >> a; cin >> b; if (0 == a) { //Annoying printing requirements for PKU if (network > 1) cout << endl; cout << "Network #" << network++ << endl; findAPDriver(graph, root); graph.clear(); vlist.clear(); visited.clear(); parent.clear(); num.clear(); low.clear(); AP.clear(); root = -1; if (0 == b) { break; } else { a = b; cin >> b; } } //Arbitrarily choosing a root vertex if (-1 == root) root = a; //Initializing the vertex "fields" visited[a] = visited[b] = false; parent[a] = parent[b] = -1; num[a] = num[b] = -1; low[a] = low[b] = -1; //Adding the vertices to the undirected graph graph[a].insert(b); graph[b].insert(a); } return 0; }
http://cs.nyu.edu/~icpc/wiki/index.php?title=SPF&oldid=6941
CC-MAIN-2014-41
refinedweb
676
59.13
On 9 March 2012 05:42, Alex Karasulu <akarasulu@apache.org> wrote: > On Fri, Mar 9, 2012 at 1:09 AM, Marvin Humphrey <marvin@rectangular.com>wrote: > >> On Fri, Mar 09, 2012 at 12:43:47AM +0200, Alex Karasulu wrote: >> >. >> >> My impression was that there were two issues. >> >> First was the technical issue of a namespace conflict. It seems as though >> there may be good reasons why exceptions should be made on a case-by-case >> basis, as Doug implies. >> >> > +1 > > >> The second was the community issue of potentially advantaging a commercial >> entity; this response seemed to satisfy people: >> >> >> >> > +1 > > >> In fact, Sqoop already has a plan in place to completely remove >> com.cloudera.* namespace from its contents via the next major revision >> of >> the product. The work for that has already started and currently exists >> under the branch sqoop2 [3], tracked by SQOOP-365 [4]. We hope that in a >> few months time, we will have feature parity in this branch with the >> trunk, which is when we will promote it to the trunk. >> >> I would think that any generic policy would need to take both of those >> issues >> into account. >> >> > I feel the Cloudera folks have benign concerns in this case and this is not > an attempt to take advantage. As you reminded us above they're simply > trying to facilitate compatibility to accomodate their users which is > admirable. Also as Doug pointed out they're in control of both namespaces > so they can handle it without conflict. > > However my primary point was when you start allowing this practice even > just a little for benign, positive reasons (as is the case for Scoop), it > can quickly lead to chaos through misuse, and result in community discord. > It's not easy to quantify/clarify whether the usage is meant for good, used > carelessly without consideration, or used explicitly to gain a commercial > advantage. It's going to start ruffling feathers at some point or another > when accusations start flying. Some folks are going to be pissed due to > disruptions, some are going to be on a witch hunt, others are going to have > valid concerns, some just won't care, while those accused will fight > vehemently feeling unjustly attacked. In the end, this feels like a > pandora's box. We just saw how damaging this can be with the recent > Lucene/Solr incident concerning commons CSV. [Just using a reference here > to minimise public discussion of a private list thread.] > > So is there a way we can allow the practice to occur at a minimal scale > with positive gains, without the potential negative impact? > > My rather weak suggestion of having projects explicitly announce the cases > where they "infringe" on another project or party's namespace just raises > awareness and makes it so the potentially "infringing" party exposes it's > intentions before accusations start flying. I'm sure there are better > solutions to this problem where we minimize the administrative overhead and > the negative impact. I just could not think of a better way at this point. Isn't it about who owns and manages the namespace? If the owner gives permission, then OK, otherwise not OK. > -- > Best Regards, > -- Alex --------------------------------------------------------------------- To unsubscribe, e-mail: general-unsubscribe@incubator.apache.org For additional commands, e-mail: general-help@incubator.apache.org
http://mail-archives.apache.org/mod_mbox/incubator-general/201203.mbox/%3CCAOGo0VbMnu-vWHD4DZSvwzh03XDYQ4fJZ0QCN0krHrdb6LvQ0w@mail.gmail.com%3E
CC-MAIN-2015-48
refinedweb
549
61.97
Artificial Intelligence Bests Humans At Classic Arcade Games 148 sciencehabit writes, including Space Invaders and Breakout. In many cases, it surpassed the best human players without ever observing how they play. Breaking news! (Score:5, Funny) Someone made a computer that's really good at reaction time, and at calculating trajectories. Re: (Score:2) Someone made a computer that's really good at reaction time It was done awhile ago. By IBM. Watch Watson play Jeopardy, and it is pretty obvious it won mainly because it was much faster at triggering the button. Watson wasn't better at answering the questions, it just got more chances. Re: (Score:3) At high levels, Jeopardy is all about who presses the button first. Watch a Tournament of Champions. All 3 people buzz in for pretty much every question. The trick is who can parse what the "answer" is really asking, recall the fact required, and then buzz in before the other players can do all 3 things. If Watson can do those things faster than a person, it won fair and square. Just being able to parse the "answer" was an incredibly impressive achievement. Re: (Score:2) Re: (Score:3) The human players get the clue in text format also (printed on the monitor wall). Alex Trebek reading the clue aloud is strictly for the benefit of the mouth-breathers watching at home. Re: (Score:2) I've seen it in the lab at ibm and asked a lot of questions. Its a language codex which is quite good, sitting infront of a ranking database of information. The demo they had was medical journal based, and seemed quite useful for doctors that are lookin Re: (Score:3) ... and then buzz in before the other players can do all 3 things. This is not correct. It is NOT who buzzes first. Alex reads the question and then a light comes on. If you push the button before the light comes on, then you are locked out for a quarter of a second. So the trick is to push the button the instant the light flashes on. It is pure response time. Of course a computer is going to be better at that. That is 99% of the reason Watson won. Re: (Score:2) a looong while ago. what do you think the military used the computers first for? I thought that was the joke of the comment. the thing is though giving it an arbitrary video game. making a robot to play just breakout is very easy, but that it plays breakout after it sees it is not that easy (though breakout is very easy on that scale, paddle follows ball and you get points, not much trial and error involved before you have winning combination(also wasn'tthat done a year or three ago already??) Re:Breaking news! (Score:5, Insightful) Seriously, is there any doubt that a computer can easily defeat a human at a computer game that involves 95% pure reflexes and 5% strategy?. So AI has a massive advantage with precision reflexes and calculations that it can make much faster than humans. Some of my previous jobs involved programmed AI game opponents for action games. As anyone who's faced an aim-bot knows, there's no real challenge for computers to perform many of the tasks humans find difficult, like putting a bullet through a moving target's forehead. I actually had do a lot of extra work to programmatically replicate the difficulties humans face when aiming at a moving target. However, collecting and processing global environmental knowledge and formulating complex strategies based on that knowledge is extremely difficult. That's why we typically build a lot of invisible hints into the environment itself for the benefit of AI, such as pathfinding-specific structures, or dynamic flags that signal potential rewards or danger. Even today, in many strategy games that involve complex ruleset (meaning brute force calculations can't work as well), the computer opponents inevitably have to cheat in order to compete with even modestly skilled players. Early videogames have very few of these sorts of challenges because of their largely static environments and the basic nature of the games. For the most part, you just need to formulate a few simple rules for an optimal victory condition, and when combined with a computer's incredible performance, you can easily trounce the best human players, simply because a computer never gets distracted, tired, or makes silly mistakes in judgement. Again, I'm not dissing the work the researchers did, which I found to be impressive, but the article and summary seem to be missing the point entirely by comparing them to human scores. It's fairly obvious that once a computer learns how to play with an optimal strategy, it's an absolute given that they'll score better than humans ever could. Re: (Score:2). -- Re: (Score:3) I figured out an endless pattern to Atari 2600 Space Invaders and PacMan, high score stuff. Was thrilled and disappointed to read about my solution in some Atari mag several years after my discovery. I figured I had beat the computer and was disappointed when I wasn't asked to help defeat Xur and the Ko-Dan Armada. Fixed that for you. Re: (Score:2). Exactly. The article talks about the "advanced strategy" of tunneling a hole through to bounce the ball of the back wall. But that's only a useful strategy to make up for someone who doesn't have the reflexes to bounce the ball with their paddle, or can't be bothered. If the program had good reflexes and didn't get bored, then tunneling in breakout isn't any advantage. Re: (Score:2) That depends on the incentives the AI has. In this case, it appears it has incentives to gain the highest possible score as quickly as possible. In this case, tunneling and bouncing off the top wall better matches those goals. I read about his before and the computer starts out not knowing where the score is-- it has to learn which area is score and then do random things with the game until something succeeds at causing the score area to go up... and then optimize for high score and high speed. That sure sounds Re: (Score:3)-playin Re: (Score:3) I actually didn't see this story as news, I had seen a video of there work last year from before they were bought by Google. That same video was linked from the article:?... [youtube.com]. Re: (Score:2) Re: (Score:2) Seriously, is there any doubt that a computer can easily defeat a human at ___________ that involves _____________? Of course not. Whenever a computer defeats a human easily, of course it isn't true AI. Computers were better at that all along. Leave that to computers so that humans can do the truly human work. Re: (Score:2) Whenever a computer defeats a human easily, of course it isn't true AI. You're confused. I'm not sure how, exactly, but you might want to google "hard problem" and "strong AI" to net (ha!) yourself a better grounding. Re: (Score:2) As anyone who's faced an aim-bot knows, there's no real challenge for computers to perform many of the tasks humans find difficult, like putting a bullet through a moving target's forehead. It always makes me wonder why fights in futuristic movies are always done by people aiming by hand. Re: (Score:2) Some of my previous jobs involved programmed AI game opponents for action games. As anyone who's faced an aim-bot knows, there's no real challenge for computers to perform many of the tasks humans find difficult, like putting a bullet through a moving target's forehead. Then why did Steven Polge resort to making the ReaperBot cheat [mrelusive.com]? Re: (Score:1) By telling the lie that you think this happened makes you a liar. Believing a liar makes you a liar. Are you smart enough to understand that? This did not happen. There is no proof. There is no video. The only evidence is a vague statement from a Republican. We all know their kind lies. Just look at Rmoney's claim that he is human. No. He is a man-like object. That is why he is so hateful. Again, you are a liar since you believe a liar. Re: (Score:2) Also the game has finite limits which over time the Artificial Stupid can memorize completely enough to anticipate it ahead of time. Re: (Score:2) Hate to break it to you but that was done, years and years ago, it is really easy for computers to do that stuff. The really hard bit it to analyse the environment and from that analysis create an internal virtual environment that you can base your calculations and optimum decisions on. It really is difficult for computers to analyse the visual environment, understand what is within that view and how the various elements will behave as changes occur. So virtual computer robotics is pretty easy because you Re:Breaking news! (Score:4, Informative) The key achievement here is that the AI was able to learn the game on its own in a relatively short time. Imagine if you had an industrial robot that could learn how to do tasks on its own and then modify its behaviour if the situation changed, and generally cope with a variety of situations. Also, they called it DQN which means "dumbass" in Japanese, so bonus points for that. Lower the bar further. (Score:2) AI is now trivial pattern matching. Re: (Score:2) Re: (Score:1) Not true, we also do input and output. Gabage in, garbage out. Re: (Score:2) Re: (Score:2) For example: I have pattern matched this thread^Warticle^Wweb site and decided it was a repetitive waste of time. Re: (Score:2) Re: (Score:3) Re: (Score:2) You've missed the joke. Re: (Score:2) The classic arcade games are more of an issue of attention, than skill or thinking ahead. Once the AI figured out how the play the game, I bet it can focus and pay attention to the detail, more than a human can. Re: (Score:3) Don't even need that. I made pong for the TI-82 instead of paying attention in calculus class in high school, my "AI" could not be beat. Because it's really easy to do things when you can precisely calculate vectors and positions... It's actually harder to have something that makes human-like mistakes. I don't think actual breakout or space invaders would be significantly harder. Re: (Score:2) Nooooooo (Score:2) I want my symbolic AI back... Strategy games? (Score:3, Insightful) In other words, this is an example of good image recognition software, that's it. Show me a game that beat a human on a strategy based game, then you have something. Re: (Score:2) Re: (Score:2) "Go" on the other-hand must still be played as a strategy game by computers because looking ahead is not that helpful. Re: (Score:1) Maybe humans memorize patterns of play (responses) that win then. If the computer cannot "look" far ahead in Go, than neither can people, most likely. What exactly is "strategy" that is different from predicting ahead and/or learning successful patterns? Re: (Score:2) A pic^H^H^H link or it didn't happen. Re: (Score:1) Go atse? Re: (Score:2) Re: (Score:2) To quote Queeg: Chess Re: (Score:3) It's not even a good example of image recognition, because the images to be processed don't have to be "understood" to be used. On top of that, the graphics of the games in question were very simple and primitive compared to what image recognition software deals with. Add to that the repetitive nature of old video games that were based on 99% reaction time and 1% strategy, and you can just flat out colour me "unimpressed" with this "research". Back in University, my AI project was a game player (a simpl Let it try at 80s/90s games (Score:2) Re: (Score:1) Or say, Angry Birds or Fruit Ninja. Re: (Score:2) The real question being: did the AI enjoy it as much as a human? Re: (Score:2) Re: (Score:2) Re: (Score:1) I'd like to see a robot play fruit ninja for real. Sure, it'd be a little scary having a robot waving a razor sharp katana around, in your kitchen, but think of the time you could save making fruit salad! Re: (Score:2) I want to see a computer play Mornington Crescent. Re: (Score:2) import random import urllib.request player = random.choice(['You', 'I']) station = str() tube_stations = urllib.request.urlopen(r'').readlines() tube_stations = [i.decode('utf-8').split(',')[0] for i in tube_stations] while True: if 'You' == player: station = input('Enter a station: ') else: I'm one step ahead (Score:4, Funny) Well, I outsourced my Donkey Kong playing before bots took it over, so there! meh (Score:1) This just in: Even in simplistic AAA games with bots, the AIs are better than human players, we have to dumb them down to keep the game fun. Training a neural net to play tetris is AI:101. Teaching it to play mario, has been done to death by AI students. Let me know when the AI complains about the ending of Mass Effect 3. Then I'll care. Re: (Score:2) > Let me know when the AI complains about the ending of Mass Effect 3. BUZZ CLICK WHIRRR... This Game Sucks. Click. (Side note - I wonder how long before the AI evolves (degenerates?) into comic book guy nerd speak... Are all of our nerdisms really just natural progressions of logic? BUZZ CLICK WHIRR... Worst Game EVER. Exclamation point. Exclamation point. Exclamation point. Click. ) Re:meh (Score:4, Funny) Wasn't the AI complaining about the ending of Mass Effect 3 pretty much the plot of Mass Effect 3? Re:meh (Score:5, Insightful) This just in: Even in simplistic AAA games with bots, the AIs are better than human players, we have to dumb them down to keep the game fun. First the prime challenge in the games you are talking about is lining up a crosshair with a pixel with a mouse and selecting fire. If AI's had to do that they might have some difficulty. In practice the so-called AI bots already know where you are, and could keep their weapon lined up on your noggin through half the map without the need for line of sight. Tthey also get to target and fire at me without having to diddle around with a mouse or looking at the screen to see where I am. Get a bot to actually play such a game with the same UI and world view I have (keyboard and mouse and what they can see on screen and hear on the speakers) and they tend to be quite abysmal.. Re: (Score:2). Lots of extra resources, and a broken fog of war. And the easy/medium/hard on some games changes the damage/health of units. Re: (Score:2, Informative) Seriously, you don't sound like you know what you're talking about. Nor do you. Your AI doesn't have the same control interface as human players. An AI would never miss a stationary target unless you programmed it to or are really bad at programming. Humans do miss them. Humans have to deal with moving a mouse an exact distance. AIs don't. They simply move the exact distance required. No need to deal with mouse physics, no need to deal with running out of desk space, no need to estimate the amount of movement, etc... They don't need think which key does what then pr Re:meh (Score:5, Interesting) When Id released Quake C, this "you have to dumb down the AI" idea became very apparent. Someone wrote a replacement AI for the enemies that allowed them to learn and communicate. They had to follow the rules and physics of the game - so if they were within earshot they could communicate your position to each other, otherwise they couldn't. The first couple of interactions would be pretty easy kills. Then one enemy would see that you were better armed and run away. That would be the last enemy you would see for a while. Then, when you were in a vulnerable position, the entire population of the level would ambush you in a coordinated attack. Game over. They were way, way, way too smart to be beaten. It was pretty fun to explore their learning capabilities and watch how they would win. But it didn't make for engaging gameplay, unless you are a complete masochist.. This "AI" program was very rudimentary, and it was already much too difficult for human players, despite being limited to the same "in game" knowledge and input capabilities as the human players. It makes perfect sense that the challenge and complexity of programming the AI for games mostly revolves around "dumbing down" the AI in a way that makes the enemies challenging and interesting, but also the right amount of "beatable". Re: (Score:3). Yes, and it gives another example of the issue. The AI has access to a perfect clock, and perfect spatial awareness, and has perfect control over its movement, sees everything in its field of view no matter how briefly it sees it... It can run and jump a maze of catwalks over lava with perfect reliability - BACKWARDS. It can do all that and land on a specific set of coordinates where it knows supplies are going to respawn the millisecond it respawns, because it can time to the millisecond when it last picked Re: (Score:3) That echos my point, somewhat. It is pretty easy to design an AI for a lot of video games that can beat a human (without cheating). The AI code from Quake was only a couple of pages. Whether you use the moniker "constraints" or call it "dumbing down", it would take a lot more code to give the AI more human-like abilities. Probably several times as much code. The same goes for the enemies. The code that gave them a degree of autonomy and communication was pretty small, but it made them unstoppable becaus Re: (Score:3) That echos my point, somewhat. It is pretty easy to design an AI for a lot of video games that can beat a human (without cheating). Yes, albeit, for a slightly strained definition of "without cheating" :) Whether you use the moniker "constraints" or call it "dumbing down", I think the distinction is important. Dumbing it down would be deliberately sabotaging its ability to make good decisions. The constraints certainly have the same effect, but we aren't sabotaging the decision making itself, but merely restricting the information it actually has to work with access to human levels. No perfect clock. No perfect positioning. etc. It is odd that the hard part about making a game AI would be making an AI that isn't too competetive, but that's where we are. Not really. It's just that we've devised a game that's difficult and interestin Re: (Score:2) This just in: Even in simplistic AAA games with bots, the AIs are better than human players, we have to dumb them down to keep the game fun. Thats because 99% of AAA games are twitch games. No strategy involved, just reflexes. Games like COD, Halo, et al. really limit what the player can do and it really is the fastest mouse wins. So they have to limit the reaction time of the AI to what a human is capable of. Now if you look at strategy games like Civ IV, you had to give the AI unfair advantages to put it on equal footing with human players. But turn based strategy games have a lot of fuzzy logic. So really an AI mastering COD is not news, we Don't underestimate humans (Score:4, Funny) No AI is a Wizard (Score:1) I'd like to see AI take me on after a few quality bong hits while I rock the orbits and ramps of Black Knight 2000 with perfect captive ball shots or I slam-tilt a Star Trek:TNG table without losing my 50 cents. ...Or totally get 57 second of playtime and 36,000 points out of another 2 games and 6 lost balls after I hit nothing but the glass and scoreless bumpers while every shot goes down the side gutters or perfectly in the center of a triple flipper gauntlet totally getting screwed over by those damn mag Re: (Score:3) Damn, dude, you must be deaf, dumb, and blind. Re: (Score:2) Re: (Score:2) Well, that would be the point. Things like driving a car and performing surgery need both (a) computing capability and (b) a real-world interface. It would seem that taking a pinball machine, a handful of linear motors, a camera, and some compute power would be a much, much more useful real-world learning exercise. When playing an electronic game, the exact same input will produce the exact same result; but on a mechanical pinball game, there will always be a slight variation - which makes the whole thing fa This guy did it in 2013... (Score:2) So ... umm... (Score:2) Now I can buy an AI so it can play the computer game I bought so I'd have more spare time? Impressive accomplishment..but.. (Score:2) ..it's a computer figuring out how to beat a computer at a kinda simple game The real world is a bit harder Still..well done! Paywall and some pdf rendering (Score:2) Wonder why the editors let such bad sites and auto playing videos to be posted. Re: (Score:2) Which one is giving you issues? With noscript / firefox I had no problem with the science mag one. The nature one is really just a link to... [nature.com] It's cool but (Score:2) It's actually really cool that this happened, so it's a shame that most of the reporting on it is sort of "correction bait". The fact that it does good at these games without watching human strategies is interesting, but computers have strategies that humans lack, due to their increased reaction time (random thing happened, I can respond by doing X -> the computer is several orders of magnitude superior at this for free) and increased calculation time (the trajectory is curve such and such -> your vi Wait, not one classic arcade game in here? (Score:2) It looks like it worked with Atari 2600 games, which are ports of classic arcade games. A nitpick, but about 30 seconds playing the 2600 version versus the arcade version will show you a ludicrous level of difference betwixt. I don't want to belittle the work, but calling 2600 games arcade games is like calling a motorcycle a semi truck. Words have meaning- in this case, "Atari 2600 games" or "classic games". NOT arcade games. Re: (Score:2) It's a misleading headline for sure. If you check the PDF it's pretty clear about the volume of 2600 games it works with, but they are def. not arcade games. Surprising (Score:2) Wow! For a generation, we knew that AIs are good at playing Global Nuclear War and now they tell us it's more like Super Mario Bros? does it have a favorite? (Score:2) which game is the AI's favorite? Unfortunately... (Score:2) Unfortunately, the experiment came to an abrupt end when they threw "ET: The Extra Terrestrial" at the AI, whereupon after an hour of trying different tactics the AI decided that the only way to win was to send a power surge through the system, frying the only working Atari 2600 the researchers could dig up. This still classifies the AI as coming up with the best solution to the game ever implemented. Yaz Re: (Score:2) Those early Atari 2600 ET adopters really had to stick their neck out with that game... You gotta love humans. Every time an AI starts to be able to do something that was previously only our domain, it's all "Meh, wake me when..." and "Yeah, but a computer still can't..." Funny stuff.:) Re: (Score:2) Programming a computer to ace these games was possible in the 90s, maybe the 80s. The reason this is interesting is HOW it taught itself, and how many of the games it could get good at (many of the games it could not learn). Cheerleading AI research is nice, but this isn't an example of a computer entering a new domain, this is a research example of something that can solve other problems in the field- an engineering demo of sorts. Re: (Score:1) Obviously. The learning is the "something that was previously only our domain," not the playing, which is precisely what people are reacting so defensively to, and what I find funny. Once AIs using ANN or whatever the ultimate technologies end up being can actually learn at a human level, it'll be "meh, wake me when it can appreciate a sunrise" or "Yeah, but a computer still can't fall in love!" My point is just that we move the bar in order to preserve our collective sense of being special snowflakes. Pacman (Score:2) Re: (Score:2) That one is interesting because it took humans a ludicrous number of hours to figure out emergent patterns. It was trial and error (and the AI was deliberately not given an overly large amount of time on each game). Once the ninth key pattern was solved it became execution based. You could trivially code a machine to killscreen Pacman with no AI involved. Hell, you could probably do it with a very small Perl script- because humans already know the patterns that win. It WOULD have been interesting to giv press your luck (Score:1) Well it's been 20 years and watson is still pressing his luck. Let it loose on the forex market (Score:2) Screw Atari 2600 games. That's small fry gaming. Let this thing run full tilt boogie on a MetaTrader platform, and see what you get. Re: (Score:2) Reinforcement from... where? (Score:1) Reminds me of a programming competition .... (Score:4, Interesting) The best entries, however, didn't rely on AI, but on the fact that the RNG of the arcade game isn't random. Once the Asteroids-bot figured out the internal state of the RNG, it could basically use hyperspace to make targetted jumps (and never one that lead to the destruction of the ship), shoot at asteroids that haven't appeared yet and various other tricks. It was very impressive to watch one of these bots in action. It did well for about 50% of the tested games (Score:2): It would be interesting to compare the games it did well at Vs those it did poorly at. Unfor Zork (Score:2) Now let's have an AI beat Zork.... [thcnet.net] Breaking News: Computer pattern recognition ... ? (Score:2) The computer mostly figures out the game design jsut like human players, and couples that with super fast reaction time. The latter is the only reason it can beat the best human players. The bigger story is: what games did it suck at and why? Re: (Score:2) new strategy (Score:2) But did it enjoy playing them? (Score:2) Source Code (Score:2) Here is a link to the source:... [google.com] Re: (Score:2) That one got solved by the physics guys a while back.... [wikipedia.org]
https://games.slashdot.org/story/15/02/25/2020237/artificial-intelligence-bests-humans-at-classic-arcade-games
CC-MAIN-2018-05
refinedweb
4,683
70.63
For reference, I used raspberry-gpio-python, Raspberry Leaf, and How to use your Raspberry Pi like an Arduino. sudo apt-get update sudo apt-get install python sudo apt-get install python-dev sudo curl -O sudo python distribute_setup.py sudo easy_install pip sudo apt-get install python-rpi.gpio I connected an LED and an inline resistor to GPIO pin 7 and ground, one side of a momentary pushbutton to ground, and the other side of the pushbutton to a 1 kOhm resistor connected to 3.3 V. Starting from a fresh install of Raspbian, at the command line (or in LXTerminal) input the following -commands: (edit: the crossed-out commands aren't really necessary) sudo python #!/usr/bin/env python from time import sleep import os import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) # define the pins we're using button1 = 4 LED = 7 # set up the pins GPIO.setup(button1, GPIO.IN) GPIO.setup(LED, GPIO.OUT) # turn on the LED GPIO.output(LED, True) # wait for half a second sleep(0.5) # turn off the LED GPIO.output(LED, False) # toggle the LED GPIO.output(LED, not GPIO.input(4)) # set up some variable to read from the button input = False previousInput = True # loop while True: # read the button state to the variable input input = GPIO.input(button1) # make sure the button state isn't what it used to be if ((not previousInput) and input): print("button pushed") # copy the button state to the previousInput variable previousInput = input # wait to "debounce" the input sleep(0.05) # clean things up GPIO.cleanup()
http://haytech.blogspot.com/2013/05/lighting-leds-on-raspberry-pi-with.html
CC-MAIN-2018-43
refinedweb
267
57.27
Hello, am quite new to sublime text / plugins so am sorry if am repeating some already know question. I have created a post on Technical support, but perhaps it might be in the wrong place: I'm trying the same thing tonight I'm reading the How to create a Sublime Text 2 tutorial here :net.tutsplus.com/tutorials/pytho ... -2-plugin/ Good luck! Geoffroy I don't know exactly what you want to do, but you can write custom code in Python and then invoke the code from key bindings. In the custom code you can access the selected text, and move the cursor around / manipulate the selections. Here's a real quick example: import sublime, sublime_plugin class SomeExampleCommand( sublime_plugin.TextCommand ): # The 'cfg' arg will be populated with the members # of the 'args' object in the key binding below def run( self, edit, **cfg ): view = self.view # Array of current selections sel = view.sel() # First / only selection or cursor position point = sel[0] # sublime.Region object line = view.line( point ) # Content of line view.substr( line ) # Clear current selections and move the cursor view.sel().clear() target_point = sublime.Region( start_char_offset, end_char_offset ) view.sel().add( target_point ) view.show( target_point ) Sample key binding: { "keys" : "ctrl+shift+b", "up" ], "command" : "some_example", "args" : { "v_dir" : -1, "depth_offset" : 0 } } ] The example is extracted from my Block Nav plugin, so you can take a look at that if you want. You'd also want to see the Sublime API docs. Thanks for your reply! I'm new both to Python and to Sublime plugin development. SuperCollider consists in sclang, a command line executable which waits for commands on STDIN and displays the result in STDOUT.It's a blocking. The idea is to start a new thread with sclang running, and to send commands to sclang, and display what's on STDOUT in a console inside Sublime Text. I started with this code : import sublime, sublime_plugin import subprocess class SupercolliderCommand(sublime_plugin.WindowCommand): def run(self): # create output panel panel_name = 'supercollider' if not hasattr(self, 'output_view'): self.output_view = self.window.get_output_panel(panel_name) v = self.output_view # call supercollider if not hasattr(self, 'sclang_instance'): sc_dir = 'C:\\Program Files\\SuperCollider-3.5-rc2\\' sc_exe = 'sclang' self.sclang_instance = subprocess.Popen(sc_exe, cwd=sc_dir, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) edit = v.begin_edit() stdoutdata, stderrdata = self.sclang_instance.communicate() v.insert(edit, v.size(), stdoutdata + '\n') v.end_edit(edit) v.show(v.size()) # scroll down self.window.run_command("show_panel", {"panel": "output." + panel_name}) It launches sclang but1. there's a new instance of sclang launched every time I run the command (bad!)2. it blocks sublime text If I kill the sclang process, I can see that my panel was created and sclang displayed something, so I'm on the right way. -> I have to find how to launch a separate thread with sclang, and how to communicate with that process. Cheers! geoffroy Hi Managed to get a first alpha version working.Still have some issues with multiple lines.github.com/geoffroymontel/super ... blime-text Cheers Cool geoffroymontel am not alone in this mission anymore! I was planning to send the commands to supercollider using github.com/sbl/scmate.tmbundle which theoretically has better communication ( messages with more than 300 chars ). I'll send you private msg with my contacts, and check what you have done. peace
https://forum.sublimetext.com/t/keyboard-shortcuts-manipulating-text-selection-carets/4551/6
CC-MAIN-2016-40
refinedweb
555
51.85
Making Sybase Scream By DaveLevy on Nov 01, 2005 This article is about running Sybase on a sophisticated UNIX. It discusses sizing Sybase's max engines parameter, the effect of resource management tools & leveraging UNIX & Consolidation. Also note that this is not a Sun Blueprint, its meant to show you that you can, not how to. I am often asked, "Given that Sybase recommend one engine/CPU, how can you consolidate Sybase onto a large computer?" The first thing to say is that it is my view that consolidation is about architecture and co-operating systems, not merely an excuse to inappropriately pimp big-iron; an ideal consolidation host may be of any size. However, it is a fact that higher levels of utilisation are more likley if the available system capability is organised in large systems rather than the equivialently capable number of smaller systems. Sybase is a database and most databases are good citizens within the operating system. This is true of Sybase which is a good Solaris citizen and is hence easy to consolidate. It is absolutley true that Sybase have traditionally recommended that a Sybase engine (implemented as a UNIX process) should be mapped onto a physical CPU, although a common alternative rule is that the number of engines configured ( max engines) should be the number of CPUs, leaving one spare. Either E=#CPU or E=#CPU - 1 where E is number of Engines, #CPU is the number of CPUs. The reason these rules are important is that "A well tuned database server will be CPU bound". However the equations above are only performance tuning rules, and what's more, they're out of date. One of the key reasons that they're out of date is that CPUs are now much faster and more capable than when the rules were first developed. Due to the increased capability of modern CPUs, potentially fractions of CPU are required to support the applications requirement, but only integer numbers of engines can be deployed. The poverty of these rules is compounded by the fact that because they do not take into account the capability of the CPUs, and they are of little use in deciding the capacity requirements of replacement systems, or comparing between system architectures. The tuning rules above have been useful where Sybase is the only piece of work the system is running and only one instance of the database server is running. In these cases, the designer needs to determine how many cycles/MIPS/specINTs etc. the server needs to deliver the expected/required performance. BTW, I shall define the delivered power of CPU as 'omph' (O) for the rest of this article. With Sybase, if it requires more than one CPU's worth of omph, then multiple engines will be required. E=roundup(OReq/Ocpu,0) where OReq is the amount of CPU required and Ocpu is the capability of the CPU. If we are looking to use the Solaris Resource Manager, then we need to translate this rule into SRM concepts and talk about shares. The rule above has stated OReq, and Ocpu \* #CPU defines the capability of the system (or pool). In the world of managed resource, the number of engines is, E=roundup((SReq/Stot)\*#CPU,0) where S is the number of SRM shares either required (SReq) or defined (Stot) & roundup() takes the arguments of expression, sig.figs (set to zero (0) not O for omph). This assumes that the system proposed is more than powerful enough. i.e. i.e. SReq/Stot < 1 Or in other words the number of CPUs in a system must be greater than (or equal to) the number of engines. Where this is not the case, then the amount of omph delivered will be equal to the number of CPUs, unless constrained by SRM. We now have three cases, where SRM is used to constrain system capability availble to the database server, where the Engine/#CPU is used to constrain system capability to the database server or where the database server consumed all available system resource. - where SRM is used to constrain system capability availble to the database server, - where the Engine/#CPU is used to constrain system capability to the database server or - where the database server consumed all available system resourece. These might be expressed in our equation language as O=( SReq/Stot\*#CPU ) || E/#CPU\*#CPU || 1\*#CPU where O is the proportion of the system consumed and the conditions are, if SRM on || E < #CPU, SRM off || E>#CPU, SRM off. These conditions are important; they show the massive difference in configuration rules depending on how actively the systems are resource managed. A single or multiple Sybase instance can then be placed under resource management using the S Ratio {SReq/Stot} to define the resources allocated to the Sybase instance. This can be enforced by user namespace design (S8) or projects (S9/S10). The permitted resources can be enforced using Solaris Resource Manager, processor sets with or without domain dynamic reconfiguration. It should be noted that the max engines parameter can be used to enforce rule two in a consolidation scenario; more engines than CPUs can be configured. In one assignment undertaken, the customer required a ratio of two engines/CPU and rationed between server instances by varying the number of engines. I have written previously here... in my blog about designing the database instance schema as an applications map and why Consolidating Sybase instances onto fewer Solaris instances makes sense. These multiple server instances can be managed using SRM or the Solaris Scheduler. (I propose to research and write something more comprehensive about scheduler classes and zones.) I recommend that the operating system should be the resource rationing tool. Only the OS knows about that hardware and the system capability and unlike Sybase, Solaris with its project construct can approximate an application, and can therefore ration in favour, or against such objects. A Sybase server will not discrimate between applications, nor between queries. In a world of virtual servers, and managed resource, another factor is that the number of CPUs in a domain is no longer static within an operating system instance, or any resource management entity. Our ability to move resources from & into a resource management entity permit us to change the constraints that enable the rule above. An example is that an ASE instance can be started with eight engines & eight CPUs within its processor set and that the processor set is shrunk to four CPUs. The ASE is originally consuming eight CPUs worth of omph, and after the configuration change, it only consumes four. These options permit configuration rules where the maximum number of engines for a single instance of Sybase may be either less than or equal to the Max number of CPUs planned over time. Also where multiple data servers are running on a single system the total number of engines is likely to exceed the number of CPUs. (One leading Sybase user in the City aims at two engines/CPU, while another moves system resources between domains on an intra-day basis.) These are both key consolidation techniques. The number of engines for each ASE Server instance should be set to the maximum required and the resources underpinning it can be changed using dynamic domaining, Solaris processor management utilities or Solaris Resource Manager. Consolidating database servers permits the resource management functionality of the OS (or hardware) to allocate CPU resource to the server. These can be dynamically changed. This means configuring sufficient engines to take advantage of the maximum available CPUs. i.e. if at a short time of day Sybase is required to use 12 CPUs, and for the rest of the day only four, then 'max engines' needs to be set to 12 and constrained at the times of day when only four are required. In summary, in a world where consolidation & virtualisation, exist (or are coming), the value of max engines can no longer be assumed to be the based on the simple rules of the past. tags: Technology Consolidation Sybase Solaris opensolaris RDBMS Performance
https://blogs.oracle.com/DaveLevy/tags/performance
CC-MAIN-2014-23
refinedweb
1,354
57.3
When you build a tree with a BaseTreeModel, the manner to set leaf names is a little confusing. On each leaf, you have toWe don't know which property have to be set (it's not very intuitive and it's not in the javadoc ;-)).We don't know which property have to be set (it's not very intuitive and it's not in the javadoc ;-)).Code:set("name","my folder name") Why don't we have get/setName(String) or get/setTest(String) ? Is there a good reason to that ? Code:public class MyBug implements EntryPoint { private Tree tree; private TreeViewer folders; /** * This is the entry point method. */ public void onModuleLoad() { tree = new Tree(); folders = new TreeViewer(tree); folders.setLabelProvider(new ModelLabelProvider()); folders.setContentProvider(new ModelTreeContentProvider() { @Override public boolean hasChildren(Object element) { return false; } }); HashMap<String, Object> maMap = new HashMap<String, Object>(); maMap.put("name", "My folder 1"); final BaseTreeModel model = new BaseTreeModel(); BaseTreeModel folder1 = new BaseTreeModel(); folder1.set("name","Folder 1"); model.add(folder1); folders.setInput(model); RootPanel.get().add(tree); } }
https://www.sencha.com/forum/showthread.php?34232-Leaf-name-in-a-BaseTreeModel
CC-MAIN-2017-26
refinedweb
174
50.23
Introduction: Arduino Geiger Counter Build a Geiger counter out of an Arduino Step 1: What You Will Need What you'll need: -Arduino (Can be any type but must have 5V capabilities to work with Geiger counter and LCD) -Sparkfun Geiger Counter (Other geiger counter boards might work the same but I do not know) -LCD display -LED -Piezo Buzzer -9V Battery & Battery Clip -Slider switch -Project Box ~ (129mm*64mm*45mm) Step 2: Prep Solder wires to the RX, GND, and VDD of the LCD display Also solder wires to the 5V, TX, and GND of the geiger counter. Step 3: Wiring Here is the circuit diagram for the Geiger counter Step 4: Program // Copy paste the following code into the Arduino program: // Note: You need to have the RX and TX unplugged from the Arduino to program it // To program an Arduino Pro Mini with an Arduino UNO follow this link // Geiger Counter // Eric Bookless // // Introduction // // Uses a Sparkfun Geiger Counter to measure radiation and converts it to counts // per minute. The calculated counts per minute is displayed on an LCD screen. // Each count is registered with an audible and visual signal by the use of a // piezo speaker and an LED. // // Setup: // // - Connect the LED and piezo speaker to pins 9 and 8 respectively // - Attach pins RX, GND, and VDD from the LCD display to pins 2, GND, and VCC on // the Arduino. // - Attach Geiger counter to power source with pins VCC and GND and connect the // TX pin to the RX pin on the Arduino // #include <SoftwareSerial.h> int i; int count; int old = -1; int check; float CPM; float now; float time; int start; int piezo = 8; int led = 9; char OnesString[10]; char DecimalString[10]; char TimerString[10]; SoftwareSerial mySerial(3, 2); void setup(){ pinMode(piezo, OUTPUT); pinMode(led, OUTPUT); Serial.begin(9600); mySerial.begin(9600); delay(500); mySerial.write(254); // move cursor to beginning of first line mySerial.write(128); mySerial.write(" "); // clear display mySerial.write(" "); } void loop(){ i = 0; count = 0; start = millis(); while (i < 30){ digitalWrite(led, LOW); digitalWrite(piezo, LOW); if (Serial.available() > 0) { // If information available check = Serial.read(); // Read serial input if (check > 0){ count++; // If it is a hit, increment counter digitalWrite(piezo, HIGH); // Makes audible sount when there is a hit digitalWrite(led, HIGH); // Blinks LED when there is a hit } } i = millis(); i = i - start; i = i/1000; sprintf(TimerString, "%2d", 30-i); mySerial.write(254); // cursor to 7th position on second line mySerial.write(192); mySerial.write(TimerString); } CPM = count*2; old = count; // Resets 'if' statement int cpm = CPM; int temp = CPM*1000; int decimal = temp % (cpm*1000); sprintf(OnesString, "%3d", cpm); mySerial.write(254); // Displays CPM mySerial.write(128); mySerial.write("CPM: "); mySerial.write(OnesString); } Step 5: Designing the Project Box 1. With the project box I was using there was extra plastic around the edges preventing the Geiger counter from going all of the way to the edge of the box. I fixed this by simply chiseling away at it. 2. Next I cut the holes for the switch and drill a hole for the tube. 3. Then drill screw holes for the standoffs on the geiger counter. 4. Cut a hole for the master power switch. 5. To cut the slot for the lcd screen I drilled several holes about the same size as the screen and carefully removed the remaining material with a sharp chisel. I positioned the screen so that the top left screw hole of the project box would go through the top left mounting hole of the screen. 6. You may need to trim some parts of the project box to insure a good fit. 7. Once you have the LCD screen where you want it you can drill holes for the LED and Piezo speaker. Step 6: Assembly 1. Glue the LED and Piezo speaker into the top of the project box. (Hot glue works particularly well) 2. Mount the main power switch first (Since it will be below the geiger tube board). I added hot glue to protect the solder joints. 3. Attach the LCD screen to the top of the project box Fit Geiger tube in the box ( I found the mini fit well if I put the exposed pins below the geiger tube) 4. Close 'er up and your done!! 5. Test to make sure it works!!! 15 Discussions Would an arduino mega work? I Have a doubt. .. .. can it detect cosmic rays, it has frequency up to 160 ghz and if not can you name a senser which can detect its frequency??????? plz reply it's urgent.. any chance of a video of it in action? Curious to see what your display shows. I'm trying to use a 7 segment display to show just the count. Unfortunately I do not have the Geiger anymore, it was a gift for someone but from what i remember the output looked something like this: CPM: ### ## (Displays CPM) (Countdown timer until next reset) The display you are looking at should work fine though, i would recommend looking at any tutorials they might offer as I suspect the display functions will be a bit different than the ones in the script I provided. Not a problem, I just like seeing videos as they show how it looks and sounds when it's active. I was originally going to only do one display that showed CPM but I had a second one laying around and figured I'd just set it up so I can see when it's going to refresh. Here's my "prototype" that's usually as far as I ever get. I'll have to figure out how to add some decimal points when I have some more time. Thanks for the great instructions. thanks! We are having some trouble getting it going. We thought the "Friday" video on Sprakfun used analog port, but some tuts we've found use serial port (Tx on Geiger, Rx on Ardunio Uno). Like wherein he uses a serial 16x2 LCD to see data. We want to see it on our serial monitor AND log it to SD card. We get something like 214K for a value, and no, this place doesn't glow in the dark. Suggestions? Has anyone logged this to SD card (with other sensors?) Hey just asking again could i use this:... Instead of the spark fun geiger counter? THX Yes, that should work fine Nice work! Just asking what wires do we use for step 2? Thanks! The VCC, 5V and GNDs are to power the geiger counter and LCD display while TX and RX are what the Arduino uses to receive information from the Geiger tube and transmit information to the LCD display. Thanks! Followed you! :) 3rd follower! :3 Could i also use the arduino uno instead of the mini? Yes, just make sure your project box is big enough to fit the Uno Thank you, it displays a counts per minute instead of counts per second. Measuring half life would be pretty cool and I haven't tried that yet, thanks for the suggestion. nice work. i would have some idea of how to make the detection apparatus of the geiger-marsden tube but very well done on building a system that appears to give you a counts or counts per second(becquerels) reading. you may wish to use it to measure the half life of the source in a smoke alarm but unless it is a very sensitive system you will have to wait a long time(432 years for the count rate to halve but some calculations based on A=A0 x e^(-L x t) would allow a measurement of the half life without waiting so long.).
https://www.instructables.com/id/Arduino-Geiger-Counter/
CC-MAIN-2018-34
refinedweb
1,299
76.96
Update: this blog is no longer active. For new posts and RSS subscriptions, please go to. In the process of my continuous learning about agile development, one of my biggest problems is that it’s easy to find materials that say, “Do this, don’t do that,” but offer only trivial examples at best. I’m always wishing for some non-trivial examples of what the principles, or the violation of the principles, look like in the real world. Part of the reason why I put GenesisEngine up on GitHub and am blogging about it here is to provide some slightly-less-than-trivial examples of good techniques, but just as importantly, examples of mistakes and how to fix them. True confessions So, I have a confession to make. I work on GenesisEngine in my spare (ha!) time and progress has been kind of slow. I spent a fair amount of time up front on infrastructure and was careful to build it all with TDD and SOLID principles. I had a good time building that stuff but really, all of the interesting parts have to do with the generation and rendering of the terrain itself. Everything else is just plumbing. So after spending quite a number of weeks telling my friends that I was working on this nifty terrain engine project but having only a featureless white ball to show them, I really, really wanted to get something working that resembled actual planetary terrain. The problem was moderately complex and I was growing impatient. I started cutting corners. My QuadNode class started out fairly small but it quickly accumulated a lot of responsibilities and started to sprawl all over the place. I was violating the Single Responsibility Principle, and frankly, I made a mess. Warning signs One of the early warning signs that you have a fat class that does too many thing is that it’s not fun to write tests for it. Rather than just having simple inputs and outputs to manage in your tests, you have to construct elaborate chains of actions just to get your object into the state that you want to test. The tests aren’t elegant statements of intent; they’re full of confusing noise. You’ll also see a lot of combinatorial explosion going on where you get a ridiculous number of different contexts that say, “when A is true and B is true and C is true”, then “when A is true and B is true and C is false”, and so on through all the combinations of states. It’s tedious to write tests for each combination, especially when they’re messy tests anyway. As I got deeper into the functionality of my quad tree terrain generation and rendering system, I started to clearly see those warning signs in my code. But . . . I just wanted to get something working. Like, now, darn it! I was tired of waiting, and I resisted the obvious need to refactor the QuadNode class because it would take more time than I was willing to spend. Rather than stopping to figure out how many responsibilities I had running around in QuadNode and then figuring out how to tease them apart into separate classes, I simply stopped writing tests for that class. Once I did that then it was easy to not build the Perlin noise generation system test-first either. Stampede! In my non-technical life I’m into long-distance backpacking and in that world we have a term for when you’re about half a day out from town after four or five days and 100+ miles on the trail, and someone says the magic word. “Pizza.” Or maybe “hamburgers”. The technical term for what happens then is “stampede”. All common sense and self-preservation go right out the window and everyone hurtles down the trail at breakneck speed in an effort to get to town. Sometimes people punish their bodies in ways they end up regretting later. We stampede in software development, too. We spend a lot of time being careful, doing thing right, making steady progress, but at some point close to the end we sometimes say, “Ah, screw it, let’s just hack it together and make it work!” The result is usually something we call technical debt. You build up a pile of messy stuff that you’ve got to go back and fix later. I guess that’s not always a bad thing. If you’re trying to hit an aggressive deadline and you need to just throw yourself forward right at the end, building up some technical debt is a valid way to do that. Or if, like me, you just want to see something working and you’re not willing to wait, you can hack something together to scratch that itch. The really evil thing about technical debt is not the short-term impact of creating it. You can sometimes derive a lot of benefit from technical debt in the short term. No, the evil thing about technical debt is when you don’t immediately go back and clean it up once your short-term goal is realized. Anatomy of an SRP violation Right now the QuadNode class is 472 text lines long. Visual Studio code analysis reports that it has one of the worst maintainability indexes of any class in the project. It has at least three big responsibilities jammed into it right now: - As the name implies, it acts as a node in the quad tree. - It also owns the job of generating heightfield data, vertex buffers, and index buffers. This clearly has nothing to do with #1. - It also has to decide when it’s appropriate to split itself into four node children or to merge and delete its children. I first thought that was a trivial aspect of #1 but it turns out to be a huge deal in its own right. Here’s one of the QuadNode spec contexts. When a node is updated, it may decide to do certain things based on the state of the world. In this case, when a non-leaf node (that is, a node that has children) is far enough away from the camera, the children nodes should be removed and disposed because we don’t need that level of detail any more. [Subject(typeof(QuadNode))] public class when_a_nonleaf_node_is_updated_and_the_camera_is_far : QuadNodeContext { public static DoubleVector3 _nearCameraLocation; public static DoubleVector3 _farCameraLocation; Establish context = () => { _nearCameraLocation = DoubleVector3.Up * 11; _farCameraLocation = DoubleVector3.Up * 15 * 10 * 2; _node.InitializeMesh(10, Vector3.Up, Vector3.Backward, Vector3.Right, _extents, 0); _node.Update(new TimeSpan(), _nearCameraLocation, DoubleVector3.Zero, _clippingPlanes); }; Because of = () => _node.Update(new TimeSpan(), _farCameraLocation, DoubleVector3.Zero, _clippingPlanes); It should_remove_subnodes = () => _node.Subnodes.Count.ShouldEqual(0); It should_dispose_subnodes = () => { foreach (var subnode in _node.Subnodes) { ((IDisposable)subnode).AssertWasCalled(x => x.Dispose()); } }; } This is not a horrible test set. Believe me, I’ve seen (and written!) worse. But let’s look at a couple of things that it’s trying to tell me: - The process of setting up a non-leaf node in the context is built on indirect side-effects. Instead of just telling my class under test, “Hey, assume you’re a non-leaf node”, I have to initialize the node’s mesh, then call .Update() with camera coordinates that are near enough to cause the node to split itself and generate children, then call .Update() again with different camera coordinates that are far enough to cause the node to merge its children. The spec isn’t able to say what it means explicitly; it’s very roundabout. Someone unfamiliar with the code base would probably have to put in significant effort to understand how the spec works. - There’s no way to determine whether the QuadNode we’re testing decided to merge its children except by inspecting its children. Again, this is relying on indirect side-effects. There’s no way to get a clear statement from the class that says, “Yes, I’ve decided to merge!”, which is really what I’m interested in testing here. - This spec context is one of four that test a combinatorial set of conditions: - When a non-leaf node is far away from the camera - When a non-leaf node is close to the camera - When a leaf node is far away from the camera - when a leaf node is close to the camera - when a leaf node is at the maximum allowable tree depth and is close to the camera - There is another factor that isn’t even mentioned in these specs because I didn’t want to deal with a doubling of the condition set. A node should only be split if it’s not over the horizon and out of sight, and it should be merged if it does get too far over the horizon even if the camera isn’t far enough to cause a merge on its own. That would turn my five contexts into nine. Yuck. The implementation of .Update() in QuadNode is about as circuitous as these specs would lead you to believe. There’s a lot of stuff going on in Update but it’s not clearly explained. There are quite a few tests and branches and it’s not very maintainable. So what’s the root problem here? The root problem is that I violated the Single Responsibility Principle. The decision of whether to split or merge a quad node is a good-sized responsibility all on its own. There are different ways to make that decision and it’s probably something I’ll want to fiddle with a lot over time since it heavily impacts performance and memory footprint. I probably need a SplitMergeStrategy class for the QuadNode to depend on, or maybe even separate SplitStrategy and MergeStrategy classes. What would that buy me? First, it would help break apart the combinatorial set. The QuadNode wouldn’t have to care anything about the position of the camera or whether it’s below the horizon. All it would have to know is that if it’s a leaf node, make a call to SplitStrategy, otherwise make a call to MergeStrategy. If the return value is true, do the appropriate thing. SplitStrategy and MergeStrategy, for their part, wouldn’t have to know whether they’re being called by a leaf or non-leaf node. They trust the QuadNode to take care of that question. They just need to think about the camera distance and the horizon and respond with yes or no. Not only does that reduce the combinatorial set but it also makes the inputs and outputs very explicit. Inputs are numbers, output is a boolean. No mysterious multiple calls to QuadNode.Update to set up the context and no mysterious poking at child nodes to determine the results. Cleaning up my mess The technical debt I incurred certainly accomplished my short-term goal. I’ve got a working proof of concept of a planetary terrain engine and I feel satisfied at reaching that milestone. However, now I have a problem. The implementation of my terrain generation is very naive and does all of its work on the main thread. At low altitudes this causes so much stuttering as to render the program virtually unusable unless you first turn off updates, move somewhere, then turn updates back on and wait awhile. The fix for that is obviously to a) enlist my other cores for terrain generation and b) do the generation asynchronously so that camera movement and frame rate aren’t impacted, even if I have to wait a bit for higher levels of detail to show up. Well, yes, that’s a great plan except that my QuadNode class is a mess.. I’ve promised myself that before I do any more significant work on this project, I’m going to clean up my mess and break QuadNode into multiple classes with single responsibilities. I’m curious to see how it turns out. If you want to take a closer look at the code as it is at the time of this writing, the permalink to the current tree is here. This would be a great ‘before and after’ case study.
https://blogs.msdn.microsoft.com/elee/2010/04/18/genesisengine-yes-srp-violations-hurt/
CC-MAIN-2016-30
refinedweb
2,034
70.23
Changes related to "cpp/language/enum" This is a list of changes made recently to pages linked from a specified page (or to members of a specified category). Pages on your watchlist are bold. 3 December 2013 - (diff | hist) . . cpp/language/constexpr; 18:24 . . (+3) . . Cubbi (Talk | contribs) (s/compile time/constant expressions (non-constexpr functions can be computed at compile time too)) 29 November 2013 - (diff | hist) . . cpp/language/final; 18:04 . . (+10) . . NHDaly (Talk | contribs) (added a colon in the syntax section between the keyword and the baseclasses) - (diff | hist) . . cpp/keyword; 16:21 . . (+180) . . Cubbi (Talk | contribs) (+namespace posix) - (diff | hist) . . cpp/language; 06:08 . . (+65) . . Cubbi (Talk | contribs) (rules for what can and can't be specialized in the std namespace need a page)
http://en.cppreference.com/w/Special:RecentChangesLinked/cpp/language/enum
CC-MAIN-2013-48
refinedweb
128
55.24
Piyush was here, I was ready with my cup of tea. I always used to worry about visualizations. For me, most of the visualization work was done by either my Visualization tool or the master of all i.e. MS Excel. Needless to say that I was nervous, because I had tried working on this part multiple times in the past, but have always found a good way to escape. My past experience with Piyush tells me that either I will get out of this day learning something worthy or else I will never learn to do it this way. I was getting a bit comfortable with Python, so that was a win for me. But the little milestone I was aiming for was right here. Lost in thoughts, I missed that Piyush was waiting for his Latte, I sipped and sat on the edge of the seat. I did not want him to know that I was nervous, but I guess he must have assumed my condition by this gesture. ‘So, nervous or excited? ‘Umm..nervous, a lot to be frank’ ‘Pihu, I have taken multiple Python session, I know people are scared as fuck to visualize things in a programming language. They always find some way to dodge the bullet. But the real beauty of visualization, and by visualization I mean a good informative graph and not something like a simple bar or line chart, is that you can tell a whole story with it’ ‘You can substitute a lot of table and a handful of graph with just one graph’ ‘That sounds fun’ I couldn’t show mush enthusiasm, but had to nod to show respect to his words. ‘I will start with a question, how or which graph can you use to show the population of each country by continents along with the GDP and life expectancy of each ? This is a classic example of how a graph can exhibit multiple information at one place’ He was looking for at least some sense in my words ‘Well, may be a scatter plot with axis as GDP and Health expectancy !!’ That was quick from my side and I waited for the response. ‘That is close, let me show you’ And he took the laptop from his bag, a silver colored Dell XPS,I used to have the same when I was in college. ‘Just look at the cool graph made by Gapminder’ ‘Wooooo, that is cool and I must say that I was close’ I was excited ‘This is what a good visualization looks like, you don’t have to make 4 graphs each showing a different data and make it interactive to escape creating this one’ ‘Chalo, let’s start with the basics of Python plotting and once we are good to go, we will try creating fancy graphs’ I was a bit excited for the class now, but we only had 40 minutes left and I wanted to make the most out of it. ‘To start with, import the best package available as per now i.e. matplot import matplotlib.pyplot as plt ‘and now create the first plot, a basic line graph with few data points’ age = (20,30,40,50,60) wage = (4000,5000,7000,1000,15000) plt.plot(age,wage) ‘Well that was really easy Piyush’ I was elated after creating my first graph within minutes of our class. ‘It’s always hard before you take the first step and the other way round, once you start exploring more. But, this graph is not even close to what we can make. Let’s add some more information to this graph’ ‘Before we move to label and other graphs, do know that if you have numbers or values on your axis in the range of thousands or millions or any large number, then it’s always better to scale your axis, See the way we scale our age = (20,30,40,50,60) wage = (4000,5000,7000,1000,15000) plt.plot(age,wage) plt.yscale(‘log’) plt.show() ‘Poor Pihu, now you have to mess up with some awesome histograms’ He chuckled, he knew that I never wanted to create a boring histogram. ‘Ohh, am soo excited’ I said with disappointment pouring down my face. ‘It’s not that bad, See, histogram makes you divide various data points in a bin and thus you can get an idea of the average values, the outliers, and many other things. Do one thing, make a list of 20 random values. I hope you know how to create a list. Do one more thing, create a list of random values by using the random function’ I can see doubts in his eyes But, I had done my homework, I knew how to import a random package and create a list out of it import random my_rand = random.sample(range(1,30),20) print(my_rand) print(type(my_rand)) [27, 7, 3, 21, 19, 4, 23, 26, 13, 28, 29, 24, 20, 14, 25, 8, 2, 1, 9, 16] <class 'list'> I showed the my_rand list to him and he was happy to say the least. ‘This is good Pihu, now just remember the basics that when you want to plot a histogram, you need to have two things, a list with values and the number of bins, you want your histogram to have. See the code below’ plt.hist(my_rand,bins = 6) ‘Pihu, why don’t you label the axis? I have no idea what the x and y-axis is showing’ ‘But, I don’t know how to label my graph?’ I had no clue what so ever. ‘In 1998, Larry Page…’ ‘Okay ‘Got it, see if I am correct’ It took me 3 minutes to get to the syntax plt.hist(my_rand,bins = 6) plt.xlabel(‘Year of Experience’) plt.ylabel(‘Number of company switch’) plt.title(‘Year of Exp. vs No. of Company changes ‘) plt.show() ‘The graph is good, but I really liked the labels’ He chuckled. ‘And you provided a graph title as well, good job Pihu’ ‘To make the graph more appealing om the axis label part, try the ticks thing’ ‘So, a tick actually give plt.hist(my_rand,bins = 6) plt.xlabel(‘Year of Experience’) plt.ylabel(‘Number of company switch’) plt.title(‘Year of Exp. vs No. of Company changes ‘) plt.xticks([5,10,15,20,25,30],[‘5 yrs.’,’10 yrs.’,’15 yrs.’,’20 yrs.’,’25 yrs.’,’25 yrs.’,’30 yrs.’]) plt.show()
http://thedatamonk.com/visualization-in-python/
CC-MAIN-2020-05
refinedweb
1,085
76.56
@) 2015 - - 26 / 12:37 am / tools Google Spreadsheet Sync Have you ever wanted to take the contents of a Google Spreadsheet and drop it right into your game project? So have I! That's why I made a tool that will take the contents of a Google Spreadsheet and turn it into a C# code file full of data! Demo Let's say we have a spreadsheet full of data for our video game written in C#, and it looks something like this. The resulting output of that spreadsheet will be this. class Sheets { public static Dictionary<string, CharactersRow> Characters = new Dictionary<string, CharactersRow>() { {"Adventurer", new CharactersRow() { Name = "Adventurer", Health = 100, Magic = 100, Attack = 100, Defense = 100, Speed = 100, VictoryPhrase = "Nice try, \"chump!\"", FailurePhrase = "Ah... well done..." }}, {"Thief", new CharactersRow() { Name = "Thief", Health = 75, Magic = 100, Attack = 100, Defense = 50, Speed = 200, VictoryPhrase = "I take what I want!", FailurePhrase = "Not fair!" }}, {"Assassin", new CharactersRow() { Name = "Assassin", Health = 100, Magic = 50, Attack = 200, Defense = 50, Speed = 100, VictoryPhrase = "You're lucky to be alive.", FailurePhrase = "How could you defeat me?!" }} }; public class CharactersRow { public string Name; public int Health; public int Magic; public int Attack; public int Defense; public int Speed; public string VictoryPhrase; public string FailurePhrase; } public static Dictionary<string, WeaponsRow> Weapons = new Dictionary<string, WeaponsRow>() { {"Bronze Sword", new WeaponsRow() { Name = "Bronze Sword", Attack = 45, Defense = 0, Type = WeaponType.Sword, Value = 100, CanUpgrade = true }}, {"Silver Bow", new WeaponsRow() { Name = "Silver Bow", Attack = 20, Defense = 0, Type = WeaponType.Bow, Value = 250, CanUpgrade = true }}, {"Fire Wand", new WeaponsRow() { Name = "Fire Wand", Attack = 35, Defense = 15, Type = WeaponType.Staff, Value = 400, CanUpgrade = false }}, {"Lasso", new WeaponsRow() { Name = "Lasso", Attack = 30, Defense = 0, Type = WeaponType.Whip, Value = 150, CanUpgrade = true }} }; public class WeaponsRow { public string Name; public int Attack; public int Defense; public WeaponType Type; public int Value; public bool CanUpgrade; } } With a class like that in my project now it becomes very simple to get data from the spreadsheet with the key of the row (the first column.) var charName = "Adventurer"; var health = Sheets.Characters[charName].Health; var victoryPhrase = Sheets.Characters[charName].VictoryPhrase; Console.WriteLine(victoryPhrase); Download Download GoogleSpreadsheetSync.zip (0.02MB) Usage I use Visual Studio, so I can only really tell you about that. It's easiest to set this up as an EXTERNAL TOOL in Visual Studio. * In Visual Studio go to the Tools menu at the top, select "External Tools..." * Click "Add" * Name it something like "Google Spreadsheet Sync" * For Command, press the "..." button to the right and find the exe. * For arguments you can use "$(TargetName)" "$(ProjectDir)GoogleSheet.key" * Include the quotes in those arguments! * For Initial Directory put $(ProjectDir) * No quotes in that one. * Below that check the "Use Output Window" option. Before you run it though you're going to need to create a GoogleSheet.key file. That file should only contain google spreadsheet key. For this example here's a URL to a published google spreadsheet: The key is that big long section: 11Ia3wr-Pon1180M0_KRR1hywEITLn_P1BoUedbNQeqw So in this example the contents of your GoogleSheet.key file should only be: 11Ia3wr-Pon1180M0_KRR1hywEITLn_P1BoUedbNQeqw Save the file as GoogleSheet.key inside your root project folder. (So probably the same folder as your Program.cs) You should be all set to now run it from Visual Studio! It should appear in your Tools menu. You can even set a keyboard shortcut for it later if you want. Run the tool from the Tools menu and what should happen is a Sheets.cs file is generated with all the data from your spreadsheets. Source Of course it would be way better if you're able to take this tool and craft it into your own needs, so here's the source code! I've started a public repository where I'll keep any useful tools I create right here. Trouble? If you run into any trouble feel free to post a comment and I'll try to help! Or you can reach me at hi@kpulv.com, or the contact form at the bottom of my site. 2014 - 11 - 30 / 9:59 pm / tools Easy CSV Parsing in .Net - 25 / 12:04 pm / tools Google Spreadsheet and nanDeck Workflow _10<< . 2013 - 6 - 5 / 1:14 pm / tools Some Shader Resources As I've been messing around with C# and SFML, one of the major benefits is the support for shaders! I've been crawling the internet trying to find examples of shaders, but for awhile all I could find were types like this that created entire images, or produced super elaborate effects that I wasn't really interested in. After a quick trip to Twitter I realized that what I was looking for were post processing shaders. I want to be able to adjust an image that I've already drawn for the most part, instead of creating new imagery. A lot of people gave me suggestions (mostly Sven) so here's a quick list of what was found! GeekXLab There's a handful of post processing shaders here that all look pretty neat, but unfortunately I can only get some of them to work with SFML right off the bat. Others throw errors that I don't yet know how to diagnose. They also have some software you can use to demo the shaders in, which is pretty rad! A couple of them worked right off the bat, like Thermal Vision, Dream Vision, and Pixelation, but the rest I have to mess with to figure out. nVidia Shader Library It turns out the nVidia site has a bunch of shader examples but unfortunately none of them seem to be in GLSL. The CgFX shaders should be able to compile into GLSL though. I haven't personally tried any of the shaders here, but it seems like a good sampling. hunterk GLSL Shaders Somewhere a mysterious mediafire folder full of shaders exists. This one was pointed out to me by Loren, and I haven't dug too deeply into this yet. It's a lot easier to browse the sites that have previews of all the shaders, but it looks like there's a lot of cool stuff to be found in the depths of these files. Shaders for Game Programmers and Artists This book was recommended by Sven, and the fact that it might be also geared toward artists is interesting. This was published in 2004 and I'm not sure how much has changed in the world of shaders since, and I'm also unsure on how much focus there is on post processing vs. other types of shaders in here, but maybe worth a look! Pixel Art GLSL Shading I was also pointed in the direction of this beautiful piece of work which uses shaders to light pixel art in an incredibly good looking way. I haven't checked out the real time demo yet, but just that preview image looks absolutely delicious! Photoshop Blend Mode Math Of course there is this classic post about Photoshop GLSL shaders that I first started looking at in the early days of Snapshot development. I really wanted Photoshop blending modes since I do all of my art in Photoshop anyway. I haven't tried these out in real time yet in SFML, but it looks promising! That's all I got so far! I'll see what happens in the coming weeks in shader town. I've had some fun just pixelating and blurring and warping stuff so far. One of my next game projects in C# will be having a lot of special effects (I hope) so I need to become a shader master as soon as possible. If you know of any awesome resources not featured here please let me know! Oh also here's a pro tip for writing shaders: don't use Visual Studio C#. It seems to be adding funky white space characters that causes the shader compiler in SFML to fail. So on that topic, what is an awesome shader IDE?! read more6 Comments about !
http://kpulv.com/category/tools/
CC-MAIN-2015-11
refinedweb
1,341
71.55
Opened 14 months ago Closed 14 months ago Last modified 14 months ago #12366 closed feature request (invalid) Use TypeOperators for pattern synonyms? Description With the language setting -XTypeOperators, I can use varsym expressions, like <|, as type constructors. I would expect that we would then also be able to use them as pattern synonyms; but we can't. This is a request for that to become possible. {-# LANGUAGE TypeOperators, PatternSynonyms #-} module Main where pattern (<|) x xs = Just (x, xs) main = case Just (1, [2,3]) of { Nothing -> putStrLn "Nothing"; y <| ys -> print y } gives a parse error. Change History (3) comment:1 Changed 14 months ago by comment:2 Changed 14 months ago by Pattern synonym names live in the data constructor name space whilst the type operators extension only affects type constructors. Pattern synonym definitions define no type construction so there shouldn't be any interaction between the two features. comment:3 Changed 14 months ago by Ok, thanks for the prompt and clear explanation. Note: See TracTickets for help on using tickets. Unfortunately, I don't think this is possible. The type-level namespace and the term-level namespace are organized differently: |>in a type is indeed like a capitalized word, but |>in a term is like a lowercase word. The problem is, as I understand it, that the parser needs to be able to know where the constructors/pattern synonyms are in a pattern. Is C (|>)binding the variable |>or are we matching against a nullary pattern synonym |>? It's impossible to tell.
https://ghc.haskell.org/trac/ghc/ticket/12366
CC-MAIN-2017-34
refinedweb
256
62.17
28 May 2010 15:12 [Source: ICIS news] By Will Beacham LONDON (ICIS news)--Dramatic falls in US and Asian chemicals prices in recent weeks could indicate a faltering in the global economic recovery, an industry consultant said on Friday. The steep declines could indicate falling demand in end use industries as incentive schemes come to an end and consumers return to more cautious spending habits, according to Paul Hodges, chairman of International eChem . “The chemical industry is always a leading indicator of the general economy because we’re so tied in to consumption, he said. “When ICIS reports that ethylene prices in the states have dropped by more than 20% in a week it’s a serious sign. "If you look at what’s been happening in Asian olefins and polymers in the past three to four weeks we’ve seen dramatic falls." The warning signs are there from behaviour in the ?xml:namespace> Economists and politicians are pinning their hopes on consumers continuing to spend at the increased levels which were fuelled by incentive schemes which are now ending, he added ahead of publication by ICIS of an update to his White Paper 'Budgeting for a new normal'. “I’m afraid that over the last six months I see increasing signs that this is not happening.” He pointed out that auto sales in The Auto sales growth in Hodges is concerned that huge government spending on incentive schemes may simply add to state debt rather than helping economic growth. “Perhaps I’m overcautious but if it [the theory that consumers will continue high levels of spending] is wrong then the great problem we have is that governments have not only replaced debt created by the private sector, but they’ve generated their own debt. "Now countries like Hodges believes the global economy is entering a ‘new normal’ of lower levels of consumption and debt. He added: “The characteristics of the boom years were very high levels of consumption, particularly in areas relevant to the chemical industry like housing and autos together with a lot of debt and leverage. “We saw the end result of this leverage in the crash of 2008. The ‘new normal’ says that we’re not going to go back to those days but we’ll go forward to an era of lower consumption and lower debt.” Bookmark Paul Hodges’ Chemicals & the Economy blog Read John Richardson’s Asian Chemical Connections blog Click here to find out more on the ICIS Europe, North America amd
http://www.icis.com/Articles/2010/05/28/9363409/collapsing-chem-prices-could-signal-slowdown-consultant.html
CC-MAIN-2014-41
refinedweb
420
52.43
Java Project Programming Help- The file Numbers.java reads in an array of integers, invokes the selection sort algorithm to sort them, and then prints the sorted array. Save Sorting.java and Numbers.java to your directory. Numbers.java won’t compile in its current form, because int type is primitive but not object in java. Change the array type from int to Integer (autoboxing). The numbers should be sorted now. Write a program Strings.java, similar to Numbers.java, that reads in an array of String objects and sorts them. You may just copy and edit Numbers.java. Now the selectionSort method can sort both Integer and String types. This polymorphism is implemented through interface. Modify the selectionSort algorithm so that it sorts in descending order rather than ascending order. Run Numbers.java and Strings.java again to check the descending output. Solution.pdf Solution.pdf The file Sorting.java contains the Sorting class. This class implements both the selection sort and the insertion sort algorithms for sorting any array of Comparable objects in ascending order. In... public class Sorting {//-----------------------------------------------------------------// Sorts the specified array of objects using the selection// sort... Java Programming Project Help! (Insertion Sorting) Assignment Details; Add searching.java, sorting.java and Numbers.java to your project. Work on the Numbers.java and fill the blanks with proper code.... Write a program that: 1. Calls a method called selectionSort that accepts an integer array as a parameter and sorts the elements in the array using the selection sort algorithm. The selection sort... Your solution is just a click away! Get it Now By creating an account, you agree to our terms & conditions We don't post anything without your permission Attach Files Get it solved from our top experts within 48hrs!
https://www.transtutors.com/questions/java-project-programming-help-the-file-numbers-java-reads-in-an-array-of-integers-in-2743005.htm
CC-MAIN-2019-47
refinedweb
294
53.98
Opened 8 years ago Last modified 3 years ago #3541 new feature request Allow local foreign imports Description I have no idea the level of difficulty this would entail, but it would be rather nice to be able to import foreign functions at scopes other than the top level. When writing glue code, especially for C++ where I often want to catch and haskellize exceptions, I find myself using wrappers quite a bit, for example: foreign import ccall "foo.h foo" raw_foo :: CString -> IO () foo :: String -> IO () foo s = withCString s raw_foo Where I only want "foo" exported from the module. It's not that big a deal to list explicit exports, I know, but I would like to be able to say instead: foo :: String -> IO () foo s = withCString s raw_foo where foreign import ccall "foo.h foo" raw_foo :: CString -> IO () In addition to reducing clutter in the top level namespace, it makes for less clutter on the left margin of the code, making it easier to scan through function names visually. Let's leave this as an unmilestoned feature request for now. It's something that a contributor could tackle.
https://ghc.haskell.org/trac/ghc/ticket/3541
CC-MAIN-2018-13
refinedweb
192
61.29
typesafety.pm - compile-time object type usage static analysis Perform heuristics on your program before it is run, with a goal of insuring that object oriented types are used consistently -- the correct class (or a subclass of it) is returned in the right places, provided in method call argument lists in the right places, only assigned to the right variables, and so on. This is a standard feature of non-dynamic languages such as Java, C++, and C#. Lack of this feature is one of the main reasons Perl is said not to be a "real" object oriented language. package main; use typesafety; # 'summary', 'debug'; my FooBar $foo; # establish type-checked variables my FooBar $bar; # FooBar is the base class of references $bar will hold my BazQux $baz; $foo = new FooBar; # this is okay, because $foo holds FooBars $bar = $foo; # this is okay, because $bar also holds FooBars # $foo = 10; # this would throw an error - 10 is not a FooBar # $baz = $foo; # not allowed - FooBar isn't a BazQux $foo = $baz; # is allowed - BazQux is a FooBar because of inheritance $bar = $foo->foo($baz, 1); # this is okay, as FooBar::foo() returns FooBars also typesafety::check(); # perform type check static analysis # package FooBar; use typesafety; # unneeded - new() defaults to prototype to return same type as package # proto 'new', returns => 'FooBar'; sub new { bless [], $_[0]; # or: bless whatever, __PACKAGE__; # or: bless whatever, 'FooBar'; # or: my $type = shift; bless whatever, $type; # or: my $type = shift; $type = ref $type if ref $type; bless whatever, $type; } sub foo (FooBar; BazQux, undef) { my $me = shift; return $me->new(); } # or: proto 'foo', returns => 'FooBar'; sub foo { my $me = shift; return $me->new(); } # package BazQux; use typesafety; @ISA = 'FooBar'; This module is similar to "strict.pm" or "taint.pm" in that it checks your program for classes of possible errors. It identifies possible data flow routes and performs heuristics on the data flow to rule out the possibility of the This software is BETA! Critical things seem to work, but it needs more testing (for bugs and usability) from the public before I can call it "1.0". The API is subject to change (and has already changed with each version so far). This is the first version where I'm happy with the basic functionality and consider it usable, so I'm calling it beta. While it correctly makes sense of a lot of code related to types in OO, there's still a lot of code out there in the wild that it mistakes for an object related construct and causes death and internal bleeding when it foolishly tries to swollow it. IMPORTANT: This module depends on B::Generate, but the version up on CPAN doesn't build cleanly against current versions of Perl. I have a modified version of B::Generate up in my area that works, at least for me. As I write this, Perl 5.8.8 is current. IMPORTANT: Like adapting a Perl 4 program to compile cleanly on Perl 5 with strict and warnings in effect, adapting a Perl 5 program to cleanly pass type checking is a major undertaking. And like adapting a Perl 4 program for strict, it takes some self-education and adjustment on the part of the programmer. Also like adapting a program for strict, it's an extremely rewarding habit to get into for a program that might grow to tens of thousands of lines. I suggest making it a corporate project (with large sums of money budged towards consulting fees for me) or else for the adventurous and broad-minded. IMPORTANT-ish: There's a good tutorial on strong typing (type safety, type checking) in my _Perl 6 Now: The Core Ideas Illustrated with Perl 5_ along with loads of other great stuff (you should buy it just for the two chapters on coroutines). See for excerpts, more plugging, and links to buy. Failure to keep track what kind of data is in a given variable or returned from a given method is an epic source of confusion and frustration during debugging. Given a ->get_pet() method, you might try to bathe the output. If it always a dog during testing, everything is fine, but sooner or later, you're going to get a cat, and that can be rather bloody. Welcome to Type Safety. Type Safety means knowing what kind of data you have (atleast in general - it may be a subclass of the type you know you have). Because you always know what kind of data it is, you see in advance when you try to use something too generic (like a pet) where you want something more specific (like a dog, or atleast a pet that implements the "washable" interface). Think of Type Safety as a new kind of variable scoping - instead of scoping where the variables can be seen from, you're scoping what kind of data they might contain. "Before hand" means when the program is parsed, not while it is running. This prevents bugs from "hiding". I'm sure you're familiar with evil bugs, lurking in the dark, il-used corners of the program, like so many a grue. Like Perl's use strict and use warnings and use diagnostics, potential problems are brought to your attention before they are proven to be a problem by tripping on them while the program happens on that nasty part of code. You might get too much information, but you'll never have to test every aspect of the program to try to uncover these sorts of warnings. Now you understand the difference between "run time diagnostics" and "compile time warnings". Asserts in the code, checking return values manually, are an example of run-time type checking: # we die unexpectedly, but atleast bad values don't creep around! # too bad our program is so ugly, full of checks and possible bad # cases to check for... my $foo = PetStore->get_pet(); $foo->isa('Dog') or die; Run-time type checking misses errors unless a certain path of execution is taken, leaving little time bombs to go off, showing up later. More importantly, it clutters up the code with endless "debugging" checks, known as "asserts", from the C language macro of the same name. Type Safety is a cornerstone of Object Oriented programming. It works with Polymorphism and Inheritance (including Interface Inheritance). Use typesafety.pm while developing. Comment out the typesafety::check() statement when placing the code into production. This emulates what is done with compiled languages - types are checked only after the last time changes are made to the code. The type checking is costly in terms of CPU, and as long as the code stays the same, the results won't change. If everything was type safe the last time you tested, and you haven't changed anything, then it still is. A few specific things are inspected in the program when typesafety::check() is called: $a = $b; Variable assignment. Rules are only applied to variables that are "type safe" - a type safe variable was declared using one of the two constructs shown in the SYNOPSIS. If it isn't type safe, none of these rules apply. Otherwise, $b must be the same type as $a, or a subclass of $a's type. In other words, the types must "match". $a->meth(); Method call. If $a is type safe, then the method meth() must exist in whichever package $a was prototyped to hold a reference to. Note that type safety can't keep you from trying to use a null reference (uninitialized variable), only from trying to call methods that haven't been proven to be part of the module they're prototyped to hold a reference to. If the method hasn't been prototyped in that module, then a ->can() test is done at compile time. Inheritance is handled this way. $a = new Foo; Package constructors are always assumed to return an object of the same type as their package. In this case, $a->isa('Foo') is expected to be true after this assignment. This may be overridden with a prototype for your abstract factory constructors (which really belong in another method anyway, but I'm feeling generous). The return type of Foo->new() must match the type of $a, as a seperate matter. To match, it must match exactly or else be a subclass of $a expects. This is just like the simple case of "variable assignment", above. If new() has arguments prototyped for it, the arguments types must also match. This is just like "Method call", above. $a = $foo->new(); Same as above. If $foo is type checked and $a is not, then arguments to the new() method are still checked against any prototype. If $a is type checked, then the return value of new() must match. If no prototype exists for new() in whatever package $foo belongs to, then, as above, the return value is assumed to be the same as the package $foo belongs to. In other words, in normal circumstances, you don't have to prototype methods. $b = $a->bar(); As above: the return type of bar() must be the same as, or a subclass of, $b's, if $b is type safe. If $a is type safe and there is a prototype on bar(), then argument types are inforced. $b = $a->bar($a->baz(), $z->qux()); The above rules apply recursively: if a method call is made to compute an argument, and the arguments of the bar() method are prototyped, then the return values of method calls made to compute the arguments must match the prototype. Any of the arguments in the prototype may be undef, in which case no particular type is enforced. Only object types are enforced - if you want to pass an array reference, then bless that array reference into a package and make it an object. bless something, $_[0]; bless something, __PACKAGE__; bless something, 'FooBar'; This is considered to return an object of the type of the hard-coded value or of the present package. This value may "fall through" and be the default return value of the function. return $whatever; Return values in methods must match the return type prototyped for that method. push @a, $type; unshift @a, $type; $type = pop @a; $type = shift @a; $type = $a[5]; When typed variables and typed expressions are used in conjunction with arrays, the array takes on the types of all of the input values. Arrays only take on types when assigned from another array, a value is pushed onto it, or a value is unshifted onto it. Whenever the array is used to generate a value with an index, via pop, or via unshift, the expected type is compared to each of the types the array holds values from. Should a value be assigned to the array that is incompatiable with the types expected of the array, the program dies with a diagnostic message. This feature is extremely experimental. In theory, this type of automatic type inference could be applied to method arguments, scalars, and so forth, such that types can be specified by the programmer when desired, but never need to be, and the program is still fully type checked. O'Caml reported does this, but with a concept of records like datastructures, where different elements of an array are typed seperately if the array isn't used as a queue. We only support one type for the whole array, as if it were a queue of sorts. sub foo (FooBar; BazQux, undef) { my $me = shift; return $me->new(); } Method prototypes are provided in the () after method name. You might recognize the () from perlsub. You might also remember perlsub explaining that these prototypes aren't prototypes in the normal meaning of the word. Well, with typesafety.pm, they are. The format is (ReturnType; FirstArgType, SecondArgType, ThirdArgType). Any of them may be undef, in which case nothing is done in the way of enforcement for that argument. The ReturnType is what the method returns - it is seperated from the arguments with a simicolon ( ;). The argument types are then listed, seperated by commas ( ,). Any calls made to that method (well, almost any) will be checked against this prototype. sub foo (FooBar; BazQux) { my $b = $_[0]; my $a = shift; # ... } Arguments read from prototyped methods using a simple shift or $_[n] take the correct type from the prototype. shift @_ should work, too - it is the same thing. In this example, $a and $b would be of type BazQux. Of course, you can, and probably should, explicitly specify the type: my BazQux $a = shift;. typesafety::check(); This must be done after setting things up to perform actual type checking, or it can be commented out for production. The module will still need to be used to provide the proto(), and add the attribute.pm interface handlers. Giving the 'summary' argument to the use typesafety line generates a report of defined types when typesafety::check() is run: typesafety.pm status report: ---------------------------- variable $baz, type BazQux, defined in package main, file test.7.pl, line 36 variable $bar, type FooBar, defined in package main, file test.7.pl, line 34 variable $foo, type FooBar, defined in package main, file test.7.pl, line 33 I don't know what this is good for except warm fuzzy feelings. You can also specify a 'debug' flag, but I don't expect it will be very helpful to you. unsafe assignment: in package main, file test.7.pl, line 42 - variable $baz, type BazQux, defined in package main, file test.7.pl, line 36 cannot hold method foo, type FooBar, defined in package FooBar, file test.7.pl, line 6 at typesafety.pm line 303. There are actually a lot of different diagnostic messages, but they are all somewhat similar. Either something was being assigned to something it shouldn't have been, or else something is being passed in place of something it shouldn't be. The location of the relavent definitions as well the actual error are included, along with the line in typesafety.pm, which is only useful to me. proto() is always exported. This is considered a bug. My favorite section! Yes, every module I write mentions Damian Conway =) Testing 13 is commented out because it was failing ( $foo{bar} = $foo{baz} where each slot held a different object type). Constructs like $foo->bar->() were kicking its butt (functions that return closures) and probably still are. Not sure about closure handling. This is on my todo. Not having it is an embarasement. my Foo $bar is used by fields as well. Blesses are only recognized as returning a given type when not used with a variable, or when used with $_[0]. E.g., all of these are recognized: bless {}, 'FooBar', bless {}, $_[0], and bless {}, __PACKAGE__. ( __PACKAGE__ is a litteral as far as perl is concerned). Doing bless {}, $type and other constructs will throw a diagnostic about an unrecognized construct - typesafety.pm loses track of the significance of $_[0] when it is assigned to another variable. To get this going, I'd have to track data as it is unshifted from arguments into other things, and I'd have to recognize the result of ref or the first argument to new as a special thing that produces a predictable type when feed to new as the second argument. Meaty. Update: a few more constructs are supported: my $type = shift; bless whatever, $type; the most significant. Still, you won't have much trouble stumping this thing. undef isn't accepted in place of an object. Most OO langauges permit this - however, it is a well known duality that leads to checking each return value. This is a nasty case of explicit type case analysis syndrome. Rather than each return value be checked for nullness (or undefness, in the case of Perl) and the error handling logic be repeated each place where a return value is expected, use the introduce null object pattern: return values should always be the indicated type - however, a special subclass of that type can throw an error when any of its methods are accessed. Should a method call be performed to a method that promises it will always return a given type, and this return value isn't really needed, and failure is acceptable, the return can be compared to the special null object of that class. The normal situation, where a success return is expected, is handled correctly without having to introduce any ugly return checking code or diagnostics. The error reporting code is refactored into the special null object, rather than be littered around the program, in other words. We're intimately tied to the bytecode tree, the structure of which could easily change in future versions of Perl. This works on my 5.9.0 pre-alpha. It might not work at all on what you have. Only operations on lexical my variables are supported. Attempting to assign a global to a typed variable will be ignored - type errors won't be reported. Global variables themselves cannot yet be type checked. All doable, just ran out of steam. Only operations on methods using the $ob->method(args) syntax is supported - function calls are not prototyped nor recognized. Stick to method calls for now. New - function prototypes might work, but I haven't tested this, nor written a test case. Types should be considered to match if the last part matches - Foo::Bar->isa('Bar') would be true. This might take some doing. Workaround to :: not being allowed in attribute-prototypes. Presently, programs with nested classes, like Foo::Bar, cannot have these types assigned to variables. No longer true - the declare() syntax is a work-around to this. Many valid, safe expressions will stump this thing. It doesn't yet understand all operations - only a small chunk of them. map { }, when the last thing in the block is type safe, grep { }, slice operations on arrays, and dozens of other things could be treated as safe. When typesafety.pm encounters something it doesn't understand, it barfs. We use B::Generate just for the ->sv() method. Nothing else. I promise! We're not modifying the byte code tree, just reporting on it. I do have some ideas for using B::Generate, but don't go off thinking that this module does radical run time self modifying code stuff. XXX this should go anyway; B has equivilents but it needs a wrapper to switch on the object type to get the right one for the situation. The root (code not in functions) of main:: is checked, but not the roots of other modules. I don't know how to get a handle on them. Sorry. Methods and functions in main:: and other namespaces that use typesafety; get checked, of course. Update: B::Utils will give me a handle on those, I think, but I'm too lazy to add support. Having to call a "check" function is kind of a kludge. I think this could be done in a CHECK { } block, but right now, the typesafety::check() call may be commented out, and the code should start up very quickly, only having to compile the few thousand lines of code in typesafety.pm, and not having to actually recurse through the bytecode. Modules we use have a chance to run at the root level, which lets the proto() functions all run, if we are used after they are, but the main package has no such benefit. Running at CHECK time doesn't let anything run. The B tree matching, navigation, and type solving logic should be presented as a reusable API, and a module specific to this task should use that module. After I learn what the pattern is and fascilities are really needed, I'll consider this. Tests aren't run automatically - I really need to fix this. I keep running them by hand. It is one big file where each commented-out line gets uncommented one by one. This makes normal testing procedures awkward. I'll have to rig something up. Some things just plain might not work as described. Let me know. sub foo (FooBar $a, BazQux $b) { } This should use B::Generate to insert instructions into the op tree to shift @_ into $a and <$b>. When foo() runs, $a and $b would contain the argument values. Also, support for named parameters - each key in the parameter list could be associated with a type. This is much more perlish than mere argument order (bleah). That might look something like: sub foo (returns => FooBar, name => NameObject, color => ColorObject, file => IO::Handle) { } This would first require support for hashes, period. Then support for types on individual hash keys when hash keys are literal constants. Support for hashes is also sorely needed for type safe access to instance variables: sub foo (FooBar; undef) { my $self = shift; return $self->{0}; # XXX dies, even if we always store only FooBars in $self->{0}! } Scalars without explicitly defined types and method parameters to unprototyped methods should be given the same treatment as arrays - the type usage history should be tracked, and if an inconsistency is found, it should be reported. map {}, grep {}, and probably numerous other operations should be supported on arrays. Probably numerous other operations should be supported on scalars. If you stub your toe on something and just can't stand it, let me know. I'll look into making it work. private, public, protected, friendly protection levels, as well as static. Non- static methods aren't callable in packages specified by constant names, only via padsvs and such ( $a-meth()>, not Foo-meth()>. Eg, FooBar-bleah()>, bleah() must be prototyped static if prototyped. Non-static methods should get a $this that they can make method calls in. See also the comments at the top of the typesafety.pm file. Even though I have plenty of ideas of things I'd like to do with this module, I'm really pleased with this module as it is now. However, you're likely to try to use it for things that I haven't thought of and be sorely dissappointed. Should you find it lacking, or find a way in which it could really shine for your application, let me know. I'm not likely to do any more work on this beyond bug fixes unless I get the clear impression that doing so would make someone happy. If no one else cares, then neither do I. This is the fifth snapshot. The first was ugly, ugly, ugly and contained horrific bugs and the implementation was lacking. The second continued to lack numerous critical features but the code was radically cleaned up. In the third version, I learned about the context bits in opcodes, and used that to deturmine whether an opcode pushed nothing onto the stack, or whether it pushed something that I didn't know what was, for opcodes that I didn't have explicit heuristics coded for. This was a huge leap forward. This fourth version added support for more bless() idioms and fixed return() to check the return value against the method prototype rather than the type expected by the return's parent opcode, and added support for shift() and indexing argument array and got generic types for arrays working. Version four also introduced the concept of literal values beyond just object types, needed to make the bless() idioms work. The interface is in flux and has changed between each version. The fourth one was pretty good but has essentially no users, so I kind of ignored the whole mess for a while. The fifth version makes the thing more tolerant of closures but it still doesn't do the right thing. Some constant expressions were stumping it (duh). There were some fixes that really didn't seem right to me... it didn't seem to be able to cope with untyped function calls at all, but I was certain that it just ignored all untyped stuff. Another thing that was confusing it was functions that were exported into the checked namespace from other modules -- it should have been ignoring those, and now it is. Some more places uses PVX rather than sv to get strings without meta-information tacked on after nulls. I forget what they were (it happened a few months ago) but there were some other fixes for 5.8.8. I didn't get to clean up (and spell check) the docuemntation or add new features in this release, but a new release was over due. Class::Contract by Damian Conway. Let me know if you notice any others. Class::Contract only examines type safety on arguments to and from method calls. It doesn't delve into the inner workings of a method to make sure that types are handled correctly in there. This module covers the same turf, but with less syntax and less bells and whistles. This module is more natural to use, in my opinion. To the best of my knowledge, no other module attempts to do what this modules, er, attempts to do. Object::PerlDesignPatterns by myself. Documentation. Deals with many concepts surrounding Object Oriented theory, good design, and hotrodding Perl. The current working version is always at. See "Pragmatic Modules" in perlmodlib. types, by Arthur Bergman - C style type checking on strings, integers, and floats. - look for updated documentation on this module here - this included documentation is sparse - only usage information, bugs, and such are included. The TypeSafety page on, on the other hand, is an introduction and tutorial to the ideas. - an extreme case of the utility of strong types. Class::Contract, by Damian Conway Attribute::Types, by Damian Conway Sub::Parameters, by Richard Clamp Object::PerlDesignPatterns, by myself. The realtest.pl file that comes with this distribution demonstrates exhaustively everything that is allowed and everything that is not. The source code. At the top of the .pm file is a list of outstanding issues, things that I want to do in the future, and things that have been knocked down. At the bottom of the .pm file is a whole bunch of comments, documentation, and such. - typesafety.pm works by examining the bytecode tree of the compiled program. This bytecode is known as "B", for whatever reason. I'm learning it as I write this, and as I write this, I'm documenting it (talk about multitasking!) The PerlAssembly page has links to other resources I've found around the net, too. - Mark Jason Dominus did an excellent presentation and posted the slides and notes. His description on of Ocaml's type system was the inspiration for our handling of arrays. Scott Walters - scott@slowass.net Distribute under the same terms as Perl itself. Copyright 2003 Scott Walters. Some rights reserved.
http://search.cpan.org/~swalters/typesafety-0.05/typesafety.pm
CC-MAIN-2016-40
refinedweb
4,477
71.14
Re: When is "volatile" used instead of "lock" ? - From: Jon Skeet [C# MVP] <skeet@xxxxxxxxx> - Date: Mon, 6 Aug 2007 18:41:57 +0100 Peter Ritchie [C#MVP] <prsoco@xxxxxxxxxxxxxxxxx> wrote: I was thinking more in the context of a PInvoke call; but I did mix in some asynchronous call patterns in there... But, with PInvoke it's going to marshal those pointers and the background thread wouldn't be directly updating the stack variable's value either. Although not relevant, it doesn't cause an access violation if the loop doesn't end while the background thread is running (didn't try breaking the loop and exiting the method before the thread completed; so, I don't know if it causes a violation, my guess it wouldn't until the next GC...). I haven't tried it; but my guess is you'd have to use an unsafe method in C# to get the address of a stack variable to a background thread. Not really worth doing because of the obvious problems; but the JIT doesn't know that. The JIT doesn't know that it's worth doing, but I think it's reasonable for the specification to not make any attempt to make code like that particularly easy to write in a thread-safe manner. Oddly, the JIT doesn't do any optimizations on the integer as long as I pass them by ref to another method. It's almost as if the JIT thinks the address could have been passed to another thread (I can't think of any other reason why it should't before that optimization). But, far from proof of anything... It's possible that that's the easiest way of making sure that Interlocked.Increment etc work from the point of view of that stack frame. It could be that there are other corner cases we haven't thought about which just make it easier to fix by prohibiting such optimisations than working out whether or not they apply. You're more comfortable with saying that .NET 2.0 is violating both the spec and Vance's .NET 2.0 memory model article (as written) than to say they deal with processor write-cache flushing? 335 does have that over other language specs., which goes a long way towards being able to reliably write platform-independent thread-safe code. Something you can't say for some other languages yet. I'm suggesting that the memory model (in terms of moving access) doesn't apply to stack memory in a way that either *should* be specified or *is* specified in a place that neither of us have noticed. I believe it makes sense to allow more memory access reordering on the stack than on the heap. 12.6.1 states: "By "memory store" we mean the regular process memory that the CLI operates within. Conceptually, this store is simply an array of bytes. The index into this array is the address of a data object. The CLI accesses data objects in the memory store via the ldind.* and stind.* instructions." That's about the only thing I can see which describes which bits of memory are being talked about. I've gone through Vance's article [1] again and it does say the double-check lock pattern works without making the instance member volatile; while Joe Duffy says on IA64 no instructions are generated with the acq or rel completer without declaring a member "volatile" [2]... To save you scouring Vance's article, it's the last sentence paragraph 3 of the section Technique 4: Lazy Initialization. "In the .NET Framework 2.0 model, the code works without the volatile declarations.", in reference to Figure 7 which is: public class LazyInitClass { private static LazyInitClass myValue = null; private static Object locker = new Object(); public static LazyInitClass GetValue() { if (myValue == null) { lock(locker) { if (myValue == null) { myValue = new LazyInitClass(); } } } return myValue; } }; One of the interesting parts of the .NET 2.0 model is that all writes during a constructor are made visible before the new reference itself is made visible. Maybe that's something to do with the apparent contradiction? With a per-method JIT it's not possible to optimize member fields. If they ever improved the optimizations, I think we'd see more examples. i.e. if the JIT knew it was JITting the last method in a class it could go back and re-optimize other methods (Java does this?) Not sure about that particular one, but it does some very clever stuff. For instance, a virtual method can still be inlined so long as nothing's been loaded which overrides it - when the first overriding class is loaded, the inlining optimisation is undone. Scary. or a single-method class that updated a private member field could conceivably optimize use of that field. Not to mention the possibilities with NGEN. The fact that it doesn't, coupled with the required behaviour of try blocks, I think you're only getting the appearance of those guarantees. Simply adding "volatile" to fields shared amongst more than one thread despite following the locking protocol is best case not going to impact performance on x86 and worst case, as you've put it with making the double-check locking pattern faster, not a significant performance difference. You're concern with also declaring fields uses with the locking protocol (that aren't implicitly volatile) is only performance? You don't think declaring such fields volatile makes it not thread-safe? Using "volatile" *instead* of the locking protocol makes it easier to make mistakes, IMO - things like incrementing a value. Using "volatile" *as well as* the locking protocol could easily lead the reader into thinking that it's required - which then begs the question of what they're meant to do when they can't make the field volatile (doubles, fields in classes they don't have access to etc). For instance, if I have a class like this: class Dummy { int counter; double average; object dataLock; } (and appropriate methods, of course) then it looks pretty odd to me to make "counter" volatile when "average" isn't (and can't be). It looks like some safety is being added when in my view it's not, if you're also using the locking protocol. It means that in *some* cases you can get away without using the locking protocol - but I rarely try to write lock-free multi- threaded code, as I like to keep things as simple as possible. Even if doubles were treated atomically, that wouldn't mean you'd still get the "latest written" value. It just means you'd either get the new value or the old one, not a "half way house". I wasn't implying that VolatileRead(ref double) makes the access atomic. Why did you bring up atomicity then? This code seems pretty misleading to me: // doubles aren't atomic, we need to use // VolatileRead to read the "latest written" value and // because BeginBackgroundOperation uses // Thread.VolatileWrite(ref double). double temp = Thread.VolatileRead(ref value1); I don't think it's too much of a stretch to infer that there's some connection between the first clause of the sentence and the second. Without the first part, I agree with it completely - but it would still be true even if doubles *were* atomic, and value2 should also be read/written using VolatileRead/VolatileWrite if it's expected to be changed by different threads. Using VolatileRead or VolatileWrite to always access a particular field VolatileReadI(ref double) is documented as "obtains the very latest written to a memory location by any processor" and able "to synchronize access to a field that can be updated by another thread, or by hardware" and "provides effective synchronization for a field". Locking is usually a better idea; but in my example it shows that a memory access can move from before a volatile operation in the CIL instruction sequence to after the operation in the processor's instruction sequence and synchronize access to a non-atomic type with Monitor.Enter/Exit. Your example shows that it can happen with stack access, yes. I think I've covered my beliefs on that matter elsewhere :) I'm just not comfortable with the lack of consistency, the contradictions with viewing "acquire semantics" and "release semantics" as having anything to do with anything other than processor write-cache flushing. Basically we're both suggesting that part of the spec only applies to a certain situation: I believe that it only applies to heap access, and you believe that it only applies to processor write-cache flushing. If I'm right, it means the memory model is doing what I think it should do: abstracting away the hardware specifics, to specify how the system as a whole should observably behave. To my mind, that's what layered specifications are all about. We agree that the spec needs clarification: if the clarification required needs to break the veneer of the memory model to show the processor cache, I'll be disappointed. Not to mention the lack of spec for the .NET 2.0 memory model. We certainly concur on this matter. -- Jon Skeet - <skeet@xxxxxxxxx> Blog: If replying to the group, please do not mail me too . - Follow-Ups: - Re: When is "volatile" used instead of "lock" ? - From: Ben Voigt [C++ MVP] - Prev by Date: Re: Accessing office addins... - Next by Date: Re: How can I overcome the buffer limitation using StreamReader.Re - Previous by thread: Re: When is "volatile" used instead of "lock" ? - Next by thread: Re: When is "volatile" used instead of "lock" ? - Index(es):
http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.languages.csharp/2007-08/msg00771.html
crawl-002
refinedweb
1,615
59.23
Ben Finney <ben+python at benfinney.id.au> writes: > Terry Reedy <tjreedy at udel.edu> writes: > >> On 3/3/2010 12:05 PM, John Nagle wrote: >> > CPAN is a repository. PyPi is an collection of links. >> >> As Ben said, PyPI currently is also a respository and not just links >> to other repositories. [..] >> > CPAN enforces standard organization on packages. PyPi does not. > > This is, I think, something we don't need as much in Python; there is a > fundamental difference between Perl's deeply nested namespace hierarchy > and Python's inherently flat hierarchy. Perl's hierarchy is 2 (e.g. Text::Balanced) or 3 levels deep (e.g. Text::Ngram::LanguageDetermine), rarely deeper (Text::Editor::Vip::Buffer::Plugins::Display). Which is in general most likely just one level deeper than Python. Perl is not Java. And I think that one additional level (or more) is a /must/ when you have 17,530 (at the time of writing) modules. If Python wants it's own CPAN it might be a good first move to not have modules named "xmlrpclib", "wave", "keyword", "zlib", etc. But I don't see that happen soon :-). -- John Bokma j3b Hacking & Hiking in Mexico - - Perl & Python Development
https://mail.python.org/pipermail/python-list/2010-March/570316.html
CC-MAIN-2017-30
refinedweb
199
69.48
socketpair - create a pair of connected sockets #include <sys/types.h> #include <sys/socket.h> int socketpair(int d, int type, int protocol The. EMFILE Too many descriptors are in use by this process. EAFNOSUPPORT The specified address family is not supported on this machine. EPROTONOSUPPORT The specified protocol is not supported on this machine. EOPNOSUPPORT The specified protocol does not support creation of socket pairs. EFAULT The address sv does not specify a valid part of the process address space. 4.4BSD (the socketpair function call appeared in 4.2BSD). Generally portable to/from non-BSD systems supporting clones of the BSD socket layer (including System V variants). read(2), write(2), pipe(2)
http://www.linuxsavvy.com/resources/linux/man/man2/socketpair.2.html
CC-MAIN-2018-05
refinedweb
115
53.47
So while evaluating possibilities to speed up Python code i came across this Stack Overflow post: Comparing Python, Numpy, Numba and C++ for matrix multiplication I was quite impressed with numba's performance and implemented some of our function in numba. Unfortunately the speedup was only there for very small matrices and for large matrices the code became very slow compared to the previous scipy sparse implementation. I thought this made sense but nevertheless i repeated the test in the original post (code below). When using a 1000 x 1000 matrix, according to that post even the python implementation should take roughly 0,01 s. Here's my results though: python : 769.6387 seconds numpy : 0.0660 seconds numba : 3.0779 seconds scipy : 0.0030 seconds What am i doing wrong to get such different results than the original post? I copied the functions and did not change anything. I tried both Python 3.5.1 (64 bit) and Python 2.7.10 (32 bit), a colleague tried the same code with the same results. This is the result for a 100x100 matrix: python : 0.6916 seconds numpy : 0.0035 seconds numba : 0.0015 seconds scipy : 0.0035 seconds Did i make some obvious mistakes? import numpy as np import numba as nb import scipy.sparse import time class benchmark(object): def __init__(self, name): self.name = name def __enter__(self): self.start = time.time() def __exit__(self, ty, val, tb): end = time.time() print("%s : %0.4f seconds" % (self.name, end-self.start)) return False def dot_py(A, B): m, n = A.shape p = B.shape[1] C = np.zeros((m, p)) for i in range(0, m): for j in range(0, p): for k in range(0, n): C[i, j] += A[i, k] * B[k, j] return C def dot_np(A, B): C = np.dot(A,B) return C def dot_scipy(A, B): C = A * B return C dot_nb = nb.jit(nb.float64[:,:](nb.float64[:,:], nb.float64[:,:]), nopython=True)(dot_py) dim_x = 1000 dim_y = 1000 a = scipy.sparse.rand(dim_x, dim_y, density=0.01) b = scipy.sparse.rand(dim_x, dim_y, density=0.01) a_full = a.toarray() b_full = b.toarray() print("starting test") with benchmark("python"): dot_py(a_full, b_full) with benchmark("numpy"): dot_np(a_full, b_full) with benchmark("numba"): dot_nb(a_full, b_full) with benchmark("scipy"): dot_scipy(a, b) print("finishing test") In the linked stackoverflow question where you got the code from, m = n = 3 and p is variable, whereas you are using m = n = 1000, which is going to make a huge difference in the timings.
https://codedump.io/share/Q8UNB16cuXqa/1/cannot-replicate-results-comparing-python-numpy-and-numba-matrix-multiplication
CC-MAIN-2017-43
refinedweb
428
78.45
GR-COTTON Special Project: Having Fun with LEDs Overview Here we introduce several ways to enjoy GR-COTTON LED lighting. Simply copy and paste the sample programs to the Web compiler and IDE for GR. ><< Programming the LED to Blink The following sample is extremely easy to follow, and only makes the blue LED blink. The blue LED is allocated to pin 24 on the GR-COTTON board. It is output from pin 24 in pinMode, and turned ON and OFF with digitalWrite. Pin 22 is red and pin 23 is green, so set the #define area to 22 or 23 to change LED colors. #include <arduino.h> #define LED 24 // blue led void setup() { pinMode(LED, OUTPUT); digitalWrite(LED, HIGH); } void loop() { digitalWrite(LED, LOW); delay(500); digitalWrite(LED, HIGH); delay(500); } Programming the LED to Flicker Like a Firefly The sample shows how to make the red and green LEDs flicker like a firefly. The intensity of the LED light can be set by configuring area 0 - 255 using analogWrite; digitalWrite was used only to turn the LEDs ON and OFF. #include <arduino.h> #define LED_R 22 // red led #define LED_G 23 // green led void setup() { } void loop() { for(int i = 0; i < 255; i++){ analogWrite(LED_R, i); analogWrite(LED_G, i); delay(5); } for(int i = 0; i < 255; i++){ analogWrite(LED_R, 255 - i); analogWrite(LED_G, 255 - i); delay(5); } } Rainbow The sample below shows how to make the LEDs flicker in a rainbow of colors. #include <arduino.h> void setup() { } void loop() { static double t = 0.0; analogWrite(22, int(255.0 * pow(0.5 - 0.49 * cos(t / 2.0), 2.0))); analogWrite(23, int(255.0 * pow(0.5 - 0.49 * cos(t / 3.0), 2.0))); analogWrite(24, int(255.0 * pow(0.5 - 0.49 * cos(t / 5.0), 2.0))); t = fmod(t + (2 * M_PI / 1000 * 10), 60.0 * M_PI); delay(1); }
https://www.renesas.com/sg/en/products/gadget-renesas/boards/gr-cotton/project-sketch-fun-leds.html
CC-MAIN-2020-05
refinedweb
320
73.27
Pages: 1 I wanted to be able to do some work on my desktop since it's more comfortable than my laptop, but I have come across a frustrating error: gdb refuses to break on anything. The programs just run merrily along. I've even tried setting breakpoints at EVERY SINGLE LINE and still nothing. I honestly haven't got a single clue where to even start looking for a solution. I would normally assume something in code, but my laptop will run the same exact code and have gdb work just fine. I also haven't performed any sort of configurations on gdb in either machine. Anybody have any idea where I might begin to look? Offline Right out of the gate, I would guess you missed the -g flag when you compiled your target. Are you using autotools to compile? You say the targets are the exact same code. Are they? Any chance the one that works is actually a bit larger? Try the solution in here: Offline Right out of the gate, I would guess you missed the -g flag when you compiled your target. Are you using autotools to compile? You say the targets are the exact same code. Are they? Any chance the one that works is actually a bit larger? I use a makefile to compile both, and I include the -g flag in that. I'll check tonight to see if the output files are significantly different. I'll also give the other suggestion a shot. For now, here's a sample I'm trying out that produces the error: Makefile: CC = gcc CFLAGS = -Wall -c -g LDFLAGS = -g PROG = test $(PROG): gdbexample.o author.o $(CC) gdbexample.o author.o -o $(PROG) $(LDFLAGS) gdbexample.o: gdbexample.c author.h $(CC) gdbexample.c $(CFLAGS) author.o: author.c author.h $(CC) author.c $(CFLAGS) clean: rm -f *.o test *~ author.c: #include <stdio.h> #include"author.h" void display_author_details(Author person){ int i; printf("Author's name: %s\n", person.name); printf("Number of published books: %d \n", person.book_count); for (i=0; i<person.book_count; i++) { printf("%d. %s\n", i+1, person.book_name[i]); } } author.h: typedef struct { char name[30]; int book_count; char book_name[5][70]; /* 5 books, 70 character names */ } Author; void display_author_details(Author guy); gdbexample.c: /* Name: gdbexample.c * Author: Archana Chidanandan, December 3, 2007 * Modified: Delvin Defoe on March 11, 2008 * Description: This program is meant to be used with a tutorial on * GDB. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "author.h" int main(int argc, char *argv[]) { int i; /* Used to show how pointers and their pointees can be examined using GDB */ Author *ptr; /* Used to show how a struct can be examined using GDB */ Author one; /* The following is included to show how command line arguments must be specified when running the program in GDB */ if (argc<2){ printf("Error: incorrect number of arguments\n"); printf("Enter <exec_name> <num_of_times_to_display_details>\n"); exit(1); } int count = atoi(argv[1]); strcpy(one.name,"J. K. Rowling"); one.book_count = 3; strcpy(one.book_name[0],"Harry Potter and the Philosopher's Stone"); strcpy(one.book_name[1],"Harry Potter and the Chamber of Secrets"); strcpy(one.book_name[2],"Harry Potter and the Prisoner of Azkaban"); ptr = &one; for (i=0; i<count; i++) { /* Function defined in author.c. Use to demonstrate: a. "step" b. Setting a breakpoint in another file */ display_author_details(one); } return 0; } And I run the following commands: $ gdb ./test (gdb) b main (gdb) run 2 Offline Pages: 1
https://bbs.archlinux.org/viewtopic.php?pid=1361521
CC-MAIN-2016-26
refinedweb
594
68.57
- Silverlight - .NET - C# Elements - C# Constructs - C# Data Access - C# Security/Debug - C# Code - C# Videos - Windows Phone - About C# Basic Test 1. The fundamental building block in C# is a: A. Class B. Object C. Type D. Interface 2. Which of the following languages supports multiple inheritance of classes: A. C++ B. C# C. Perl D. Java 3. What kind of a type system does C# have: A. Unified B. Decentralized C. Stratified D. Isolated 4. A _______ defines a blueprint for a value. A value is a storage location denoted by a _______ or a _______. Answer A. Function Members B. No Members C. Conditional Members D. Data Members 6. Which of the following are categories of C# types: A. Generic Type Parameters B. Value Types C. Reference Types D. Pointer Types 7. Every C# application must have a single method specifying where the program execution should begin. The method must be called _____. A. main B. Main C. Either of the above 8. Main method can return which of the following: A. void B. int C. uint D. long 9. Main method can accept which of theses as a parameter: A. Array of char B. Array of string C. Array of int D. No parameters 10. In C#, the args[0] parameter contains the name of the executable file (True or False)? Answer 11. Microsoft's "All-In-One-Code Framework" project team created unified standards for coding C++, C#, and VB.NET. Which of the following represent True statements from their coding guidelines: A. Do not use tabs in source files. All code should use spaces for indentation. B. The length of code lines should not extend past column 90. C. Pascal case (e.g. MyMethod) should be used when creating all identifiers, except for the following (True/False): I. parameters ii. local variables iii. private fields iv. structures v. macros vi. constants vii. UI controls 12. Which of the following predefined value types are not primitives in the CLR: A. float B. ulong C. sbyte D. decimal 13. Which of the following are correct variable declarations C#: A. decimal cost = 10.00; B. decimal cost = 10.00D; C. decimal cost = 10.00M; D. float cost = 10.00; E. float cost = 10.00F; F. double cost = 10.00; 14. How many integers are instantiated in the following line of code: int x = 45 * 3; 15. What data type does C# create for each of the following declarations: A. var a = 1E1; B. var b = 10; C. var c = 10.0; d. var d = 0xF0000000; 16. Why does the following statement create a compiler error: float x = 3.5; 17. What data type is the "result" variable from the following statements: float x = 3.5F; int y = 2; short z = 4; var result = x * y / z; Console.WriteLine("{0}", result.GetType()); 18. What is printed for each of the statements below: A. Console.WriteLine(1.0F / 0.0F); B. Console.WriteLine(-1.0F / 0.0F); C. Console.WriteLine(1.0F / -0.0F); D. Console.WriteLine(-1.0F / -0.0F); E. Console.WriteLine(0.0F / 0.0F); F. Console.WriteLine(0.0F / 0.0F == float.NaN); G. Console.WriteLine(float.IsNaN(0.0F / 0.0F)); 19. Which of the following are correct variable declarations C#: A. bool x1 = false; B. Boolean y1 = true; C. Boolean z1 = null; D. bool? x2 = null; E. bool? y2= True; F. bool z2 = null; G. bool x3 = FALSE; H. bool? y3= true; I. boolean z3 = true; 20. What is printed from the following lines of code: byte x = Byte.MaxValue; Console.WriteLine("{0}", x.ToString("X4")); A. 7FFF B. FFFF C. 00FF D. 007F 21. What is printed from the following lines of code: short x = short.MaxValue; Console.WriteLine("{0}", x.ToString("X4")); A. 7FFF B. FFFF C. 00FF D. 007F 22. What is printed from the following lines of code: short x = short.MinValue; Console.WriteLine("{0}", x.ToString("X4")); A. 7FFF B. FFFF C. 8000 D. 008F 23. What is printed from the following line of code: Console.WriteLine("{0:X}", (sbyte)~0xd); A. F2 B. 0D C. 8F D. F8 24. What is printed from the following line of code: Console.WriteLine("{0:X}", 0xd ^ 0xf); A. d B. 2 C. 7 D. f 25. The _______ keyword is used to ignore integral arithmetic overflow and results in truncation. Answer 26. What is printed from the following line of code: byte z = Byte.Parse("23"); A. Console.WriteLine("z is: {0}", z); B. Console.WriteLine("z is: {0,-3}", z.ToString()); C. Console.WriteLine("z is: {0}", z.ToString("D3")); D. Console.WriteLine("z is: {0}", z.ToString("X4")); E. Console.WriteLine("z is: {0}", Convert.ToString(z, 2)); F. Console.WriteLine("z is: {0}", z & 0xF0); 27. If the default compile time integral overflow checking is used, what is printed from the following lines of code: byte x = Byte.MinValue; Console.WriteLine("x is: {0}", x); x--; Console.WriteLine("x is: {0}", x); A. 0, then 255 B. -128, then -129 C -128, then -127 D. 0, then -1 28. Fix the code below so it does not result in a compile-time error: short x = 1; short y = 1; short z = x + y; Answer 29. What is printed from the following lines of code: BitArray myBA = new BitArray(5); myBA[1] = true; foreach (Object obj in myBA) Console.Write("{0} ", obj); A. False, True, False, False, False B. True, False, False, False, False C. True, null, null, null, null D. null, True, null, null, null 30. Given the definition of variable x below, which "if" statements have correct C# syntax: byte x = 0x01; A. if ((x != null) & (x < 3)) B. if ((x != null) && (x < 3)) C. if (x != null) && (x < 3) D. if x != null && x < 3 31. What is the result of the following code in C#: int x = -3; sbyte y = -3; Console.WriteLine((x = y) ? "Equals" : "Not Equal"); A. Compiler Error B. Run-time Error C. Prints: Equals D. Prints: Not Equal 32. What is the size in bits for the following data types: A. bool B. short C. float D. decimal E. double F. long 33. What data types are printed for the following literals: A. Console.WriteLine(1.GetType()); B. Console.WriteLine(1.0.GetType()); C. Console.WriteLine(1M.GetType()); D. Console.WriteLine(1D.GetType()); E. Console.WriteLine(1F.GetType()); F. Console.WriteLine(1U.GetType()); G. Console.WriteLine(1UL.GetType()); H. Console.WriteLine(1L.GetType()); I. Console.WriteLine(true.GetType()); J. Console.WriteLine(1E03.GetType()); 34. Which of the following data declarations have valid C# syntax: A. long x1 = 1; B. double x2 = 1; C. double x3 = 1.0; D. float x4 = 1.0; E. decimal x5 = 1.0; 35. The arithmetic operators (+, -, *, /) are valid for all numeric data types except: _______ and _______. Answer 36. Which of the following are value types and which are reference types: A. struct B. enum C. string D. object E. array of integers 37. You can assign values of any type to a variable of type object (True or False). 38. The following code is an example of ________ and ___________. object x = 1; int y = (int) x; Answer 39. Where does an integer reside when it is declared as a: A. local variable B. field with an object C. element of an array 40. Code two "if" statements to test if a file called "test.txt" in the Windows temp directory of a Windows 7 server called Kevin-PC. Use backslashes in the path. Code the statement using verbatim string literals and then code the statement again without the use of verbatim string literals. Answer 41. Which of the following statements will print the number 0? A. Console.WriteLine(0x30); B. Console.WriteLine("{C}", 0x30); C. Console.WriteLine("{U}", 0x30); D. Console.WriteLine('\u0030'); E. Console.WriteLine('\u30'); 42. Which of the following statements are true about arrays? A. Arrays are always stored in contiguous blocks of memory. B. Once an array is created, its length can not be changed. C. Array elements are automatically initialized. D. An array is always a reference type regardless of type of its elements. E. An array must contain all the same type of elements. 43. How should data members and functions members be designated if you wish to operate on the type itself, instead of operating on an instance of the type? Answer 44. Will the address of the character 'h' have the same address in loop 2 as it does in loop 1? unsafe { string a = "the"; char[] b = a.ToCharArray(); fixed (char* charPtr = &b[0]) { // loop 1 int i = 0; char* charPtr2 = charPtr; foreach (char myChar in b) { Console.WriteLine("Address of: {0} is: {1}", b[i++],(int)charPtr2++); } // loop 2 a += " end"; b = a.ToCharArray(); i = 0; charPtr2 = charPtr; foreach (char myChar in b) { Console.WriteLine("Address of: {0} is: {1}", b[i++], (int)charPtr2++); } } Answer 45. How many bytes are used fore each char data type and how are char literals delimited? Answer 46. Given the following string declarations, what will be printed: string a1 = "alligator"; string a2 = "alligator"; string a3 = "Alligator"; string a4 ="xxx"; string a5; string z1 = "zebra"; A. Console.WriteLine(a1 == a2); B. Console.WriteLine(a1 == a3); C. Console.WriteLine(a1 D. Console.WriteLine(a1.ToLower().Equals(a3.ToLower())); E. Console.WriteLine(ReferenceEquals(a1, a2)); F. a4 = "alligator"; Console.WriteLine(ReferenceEquals(a1, a4)); G. a5 = "alli"; a5 += "gator"; Console.WriteLine(ReferenceEquals(a1, "a5")); H. Console.WriteLine(a1.CompareTo(a2)); I. Console.WriteLine(a1.CompareTo(a3)); J. Console.WriteLine(z1.CompareTo(a3)); K. Console.WriteLine(String.Compare(a1, a3, true)); L. Console.WriteLine(String.Compare(a1, a3)); M. Console.WriteLine(String.CompareOrdinal(a1, "crocodile")); 47. What are the two types of multidimensional arrays in C# and how do they differ? Answer 48. Write the code to declare and print the contents of a 2 dimensional array with 4 elements in each dimension. Answer 49. Write the code to declare and print an array containing 4 arrays. The first inner array should have 1 element, the second 2 elements, the third 3 elements, and the forth should have 4 elements. Answer 50. Which of the following are valid array definitions? A. int[,] myArray1 = new int[4, 4]; B.int[][] myArray2 = new int[4][4]; C. int[,] myArray3 = new int[,]; D. int[,] myArray3a = new int[,] { {1,2,3}, {4,5} }; E. int[][] myArray4 = new int[][] { new int[] {1,2,3}, new int[] {4,5} }; F. var myArray5 = new int[][] { new int[] {1,2,3}, new int[] {4,5} }; G. var myArray6 = new[] { 1, 2, 3 }; H.var myArray7 = new var[][] { new int[] {1,2,3}, new int[] {4,5} }; 51. What is printed from the following block of code: var x = new[] { 1, 100000000000 }; Console.WriteLine(x[0].GetType()); Answer 52. What is printed by each line of code: A. Console.WriteLine(default(int)); B. Console.WriteLine(default(bool)); C. Console.WriteLine(default(string) == null); D. Console.WriteLine(default(char) == null); E. Console.WriteLine(default(char) == '\0'); 53. Where are Static Fields and Constants stored? How long do they live? Answer 54. A constant is evaluated at ________, while a readonly variable is evaluated at ________. Answer 55. Both constants and readonly variables can be initialized when they are declared. But a readonly variable can also be initialized in the __________. Answer 56. C# enforces a definite assignment policy. What does this mean? Answer 57. By default, arguments are passed by: A. reference B. value C. either reference or value depending upon the data type 58. What is printed from the following code: object o1 = 9; Foo(o1); Console.WriteLine(o1); static void Foo(object myObject) { myObject = (int) myObject + 6; } 59. What are the two parameter modifiers and how do they work? Answer 60. Where do parameter modifiers need to be specified (hint: 2 places)? Answer 61. How is the "params" parameter modified used? Answer 62. Write a method and method call that accepts a variable number of integers and returns their sum. Answer 63. Indicate whether the following statements are true or false: A. Mandatory parameters must be listed before optional parameters. B. Positional parameters must be listed before named parameters. C. Optional parameters can be marked as either "ref" or "out". 64. Write a method that has one required and one optional parameter and returns their product. Also code calls to the method with 1 and 2 parameters. Answer 65. Write a method with 3 optional parameters. Code three calls to the method: 1. Call using first two parameters by position. 2. Call using first two parameters by name. 3. Call using only third parameter by name. 66. Name two operators that are left-associative and give examples of each. Answer 67. Name four operators that are right-associative. Answer 68. Name three operators which use parentheses and give examples. Answer 69. Name three unsafe operators. Answer 70. Given the following declarations, what will be printed by each statement. If the statement doesn't print anything, specify why (compiler error, runtime error). const int c = 0; int x = 0; int y = 1; int z; A. Console.WriteLine(z); B. Console.WriteLine(x / y); C. Console.WriteLine(y/x); D. Console.WriteLine(x/c); E. Console.WriteLine(8 % (4 % 2)); F. Console.WriteLine(8 / (2-2+1-1)); 71. Given the following code, identify which statements will cause compiler errors and specify why. int x = 1; { int x = 2; int y = 3; } { int y = 4; int z = 5; } Console.WriteLine(x); Console.WriteLine(y); Console.WriteLine(z); 72. What is printed by the following code: foreach (char c in "Visual+Studio 2012") { if (c.Equals('s')) continue; if (c.Equals('\u0020')) break; if (Char.IsSymbol(c)) goto skip1; Console.Write(c); } skip1: Console.WriteLine("X"); 73. If your project contains two types with the same name from different assemblies, how can you resolve the ambiguity in your code when referencing the type? For example, your project references both one.dll and two.dll. Both dll's have defined a class called MyClass. In your code, how do you reference the MyClass defined in two.dll? Answer 74. What token is commonly used in auto-generated code to avoid name conflicts between namespaces? Answer 75. What is the difference between the using directive and the using statement? Answer Answers 1. Answer is C. A Type is the fundamental building block in C#. It is an encapsulated unit of data and functions. basic set of functionality. ... In a traditional object-oriented paradigm, the only kind of type is a class. In C#, there are several other kinds of types, one of which is an interface. An interface is like a class, except it only describes members." C# 5.0 in a Nutshell: The Definitive Reference By Joseph Albahari, Ben Albahari, O'Reilly Media Inc. 2. Answer is A and C. C++ and Perl support multiple inheritance of classes. C# and Java do NOT support multiple inheritance of classes, but instead use interfaces to perform a similar function. Back 3. Answer is A. C# has a unified type system. This means all types share the same basic set of functionality. Back 4. Answer is: A type defines a blueprint for a value. A value is a storage location denoted by a variable or a constant . Back 5. Answer is: A and D. A type consists of Function Members (e.g. methods, constructors) and Data Members (e.g. fields). Back 6. Answer is: A, B, C, D. The categories for C# types include: Generic Type Parameters, Value Types, Reference Types, and Pointer Types. Back 7. Answer is: B. In C#, Main must be capitalized. (Java uses lowercase main). Back 8. Answer is: A,B. The main method can return void or int. Back 9. Answer is: B,D. The main method can only accept an array of string as parameters, or can have no parameters. Back 10. Answer is: False In C#, the name of the executable file is not contained in the parameters (as it is in C and C++). Back 11. Answers are: A. True. Do not use tabs in source files as they are rendered differently by various text editors. All code should use spaces for indentation. Visual studio (and most IDEs) can be configured to insert spaces for tabs. B. True. Having overly long lines inhibits the readability of code. Break the code line when the line length is greater than column 78 for readability. If column 78 looks too narrow, use column 86 or 90. C. I. True. parameters use camelCase (e.g. myParameter) ii. True. local variables use camelCase iii. True. private fields use camelCase or _camelCase iv. True. structures use all upper case with underscore between words v. True. macros use all upper case with underscore between words vi. True. constants use all upper case with underscore between words (e.g. MY_CONSTANT) vii. True. UI controls should use prefixes in camelCase to identify the type of control (e.g. btnFileSave). Also, do not use Hungarian notation (i.e., do not encode the type of a variable in its name) in .NET. Back 12. Answer is: D Decimal is a predefined data type that is not a primitive in the CLR. Decimal uses base 10, while the other floating point numbers use base 2 ... which makes Decimal more accurate for financial calculations. A Decimal calculation is about 10 times slower than an equivalent double calculation. Back 13. Answer is: C, E, F. C. decimal cost = 10.00M; E. float cost = 10.00F; F. double cost = 10.00; Back 14. Answer is: 3. 3 integers are instantiated because predefined types can be instantiated simply by using a literal. Back 15. Answer is: A. var a = 1E1; (double) B. var b = 10; (integer) C. var c = 10.0; (double) D. var d = 0xF0000000; (uint) Back 16. Answer is: Compiler Error Can't implicitly convert double to float Back 17. Answer is: float (a.k.a single) The result datatype is a float because no double data types were used in the calculation. Back 18. Answers are: A. Console.WriteLine(1.0F / 0.0F); // Prints: Infinity B. Console.WriteLine(-1.0F / 0.0F); // Prints: -Infinity C. Console.WriteLine(1.0F / -0.0F); // Prints: -Infinity D. Console.WriteLine(-1.0F / -0.0F); // Prints: Infinity E. Console.WriteLine(0.0F / 0.0F); // Prints: NaN F. Console.WriteLine(0.0F / 0.0F == float.NaN); // Prints: False G. Console.WriteLine(float.IsNaN(0.0F / 0.0F)); // Prints: True Back 19. Answer is: A, B, D, H are correct variable declarations. These are the INCORRECT variable declarations: C. Boolean z1 = null; // INCORRECT: Cannot convert null to bool E. bool? y2= True; // INCORRECT: True does not exist in current context F. bool z3 = null; // INCORRECT: Cannot convert null to bool G. bool x3 = FALSE; // INCORRECT: FALSE does not exist in current context I. boolean z3 = true; // INCORRECT: type or namespace 'boolean' could not be found Back 20. Answer is: C. 00FF Back 21. Answer is: A. 7FFF Back 22. Answer is: C. 8000 Back 25. Answer is: unchecked Back 26. Answer is: A. 23 B. 23 C. 023 D. 0017 E. 10111 F. 16 Back 27. Answer is: A. 0, then 255 Back 28. Answer is: short x = 1; short y = 1; short z = (short) (x + y); Back 29. Answer is: A. False, True, False, False, False Back 30. Answers are: A. if ((x != null) & (x < 3)) // Correct B. if ((x != null) && (x < 3)) // Correct C. if (x != null) && (x < 3) // INCORRECT D. if x != null && x < 3 // INCORRECT Back 31. Answer is: A. Compiler Error Cannot implicitly convert type 'int' to 'bool'. (Changing (x = y) to (x == y) will result in in printing Equals. Back 32. Answers are: A. bool = 8 bits B. short = 16 bits C. float = 32 bits D. decimal = 128 bits E. double = 64 bits F. long = 64 bits Back 33. Answers are: A. Console.WriteLine(1.GetType()); // Int32 B. Console.WriteLine(1.0.GetType()); // Double C. Console.WriteLine(1M.GetType()); // Decimal D. Console.WriteLine(1D.GetType()); // Double E. Console.WriteLine(1F.GetType()); // Single (float) F. Console.WriteLine(1U.GetType()); // UInt32 G. Console.WriteLine(1UL.GetType()); // UInt64 H. Console.WriteLine(1L.GetType()); // Int64 I. Console.WriteLine(true.GetType()); // Boolean J. Console.WriteLine(1E03.GetType()); // Double Back 34. Answer is: A, B, C A. long x1 = 1; // Valid B. double x2 = 1; // Valid C. double x3 = 1.0; //Valid D. float x4 = 1.0; // Compiler Error, need F suffix E. decimal x5 = 1.0; // Compiler Error, need M suffix Back 35. Answer is: 8-bit integral types and 16-bit integral types (byte, sbyte, short, ushort). Back 36. Answers are: A. struct // Value Type B. enum // Value Type C. string // Reference Type D. object // Reference Type E. array of integers // Reference Type 38. Answer is: Boxing and Unboxing Back 39. Answers are: A. local variable // stack B. field with an object // heap C. element of an array // heap Back 40. Answers are: A. With verbatim string literal: if (File.Exists(@"\\Kevin-PC\admin$\temp\test.txt")) B. Without verbatim string literal: if (File.Exists("\\\\Kevin-PC\\admin$\\temp\\test.txt")) Back 41. Answers are: A. Console.WriteLine(0x30); // No, prints: 48 B. Console.WriteLine("{C}", 0x30); // Compiler Error C. Console.WriteLine("{U}", 0x30); // Compiler Error D. Console.WriteLine('\u0030'); // Yes, prints 0 E. Console.WriteLine('\u30'); // Compiler Error Back 42. Answers are: A. True - Arrays are always stored in contiguous blocks of memory. B. True - Once an array is created, its length can not be changed. C. True - Array elements are automatically initialized. D. True - An array is always a reference type regardless of type of its elements. E. True - An array must contain all the same type of elements. Back 43. Answer is: static Back 44. Answer is: Yes. By default strings are immutable, but they can be made mutable by pinning their memory address with the fix statement. Back 45. Answer is: The char data type uses 2 bytes of storage and is delimited by single quotes. Back 46. Answers are: A. Console.WriteLine(a1 == a2); // Prints: True B. Console.WriteLine(a1 == a3); // Prints: False C. Console.WriteLine(a1 D. Console.WriteLine(a1.ToLower().Equals(a3.ToLower())); // Prints: True E. Console.WriteLine(ReferenceEquals(a1, a2)); // Prints: True (String Interning) F. a4 = "alligator"; Console.WriteLine(ReferenceEquals(a1, a4)); // Prints: True (String Interning) G. a5 = "alli"; a5 += "gator"; Console.WriteLine(ReferenceEquals(a1, "a5")); // Prints: False H. Console.WriteLine(a1.CompareTo(a2)); // Prints: 0 (a1 equals a2) I. Console.WriteLine(a1.CompareTo(a3)); // Prints: -1 (a1 is less than a3) J. Console.WriteLine(z1.CompareTo(a3)); // Prints: 1 (z1 is greater than a3) K. Console.WriteLine(String.Compare(a1, a3, true)); // Prints: 0 L. Console.WriteLine(String.Compare(a1, a3)); // Prints: -1 (a1 is less than a3) M. Console.WriteLine(String.CompareOrdinal(a1, "crocodile")); // Prints: -2 (a1 is 2 less than "crocodile") Back 47. Answer is: Rectangular and jagged arrays. Rectangular arrays have the same number of elements in each dimension, while that is not required for jagged arrays. A rectangular array is an n-dimensional array, while a jagged array is an array of arrays. Back 48. Answer is: int[,] myArray = new int [4,4]; // Rectangular array for (int i = 0; i < myArray.GetLength(0); i++) for (int j = 0; j < myArray.GetLength(1); j++) Console.Write(myArray[i,j]); //Prints: 0000000000000000 (16 zeros) Console.WriteLine(); Back 49. Answer is: int[][] myArray2 = new int[4][]; // Jagged array for (int i = 0; i < myArray2.Length; i++) myArray2[i] = new int[i+1]; for (int i = 0; i < myArray2.Length; i++) for (int j = 0; j < myArray2[i].Length; j++) Console.Write(myArray2[i][j]); //Prints: 0000000000 (10 zeros) Console.WriteLine(); Back 50. Answers are: A. int[,] myArray1 = new int[4, 4]; // Valid B.int[][] myArray2 = new int[4][4]; // Invalid (Can not specify size of inner dimension on jagged array) C. int[,] myArray3 = new int[,]; // Invalid (Must specify all size of all dimensions on rectangular array) D. int[,] myArray3a = new int[,] // Invalid (Inner dimension on rectangular array is not variable) { {1,2,3}, {4,5} }; E. int[][] myArray4 = new int[][] // Valid { new int[] {1,2,3}, new int[] {4,5} }; F. var myArray5 = new int[][] // Valid { new int[] {1,2,3}, new int[] {4,5} }; G. var myArray6 = new[] { 1, 2, 3 }; // Valid H.var myArray7 = new var[][] // InValid { new int[] {1,2,3}, new int[] {4,5} }; Back 51. Answer is: Console.WriteLine(x[0].GetType()); // Prints: Int64 (All array elements must be of same type, so "long" is used because of second element) Back 52. Answers are: A. Console.WriteLine(default(int)); // Prints: 0 B. Console.WriteLine(default(bool)); // Prints: False C. Console.WriteLine(default(string) == null); // Prints: True D. Console.WriteLine(default(char) == null); // Prints: False E. Console.WriteLine(default(char) == '\0'); // Prints: True (null character not same as null reference) Back 53. Answer is: Static Fields and Constants are stored on the heap. They live for the entire life of the application. However, they are not involved in garbage collection. Back 54. Answer is: A constant is evaluated at compile time, while a readonly variable is evaluated at runtime. Back 55. Answer is: Both constants and readonly variables can be initialized when they are declared. But a readonly variable can also be initialized in the constructor(s). Back 56. Answer is: The Definite Assignment Policy in C# means that, outside of the unsafe context, it is impossible to access uninitialized memory. Back 57. Answer is: B. By default, arguments in C# are passed by value. Back 58. Answer is: The number 9 is printed. The argument is passed by value so the original version is not updated. Note: a parameter can be passed by reference or by value, regardless of whether the parameter type is a reference type or a value type. Back 59. Answers are: 1. ref - is an input/output parameter. Variable must be assigned a value going into the method. 2. out - is an output parameter. Variable must be assigned a value going out of the method. Back 60. Answer is: Parameter modifiers must be specified in two places: 1. inside the methods parameter list and 2. inside the method call. Back 61. Answer is: The params parameter modifier is used to accept an array of parameters. It must always be the last parameter defined in the method. Only one params parameter modifier can be used in the parameter list. Only one array can be used with the params modifier. Back 62. Answer is: static long Sum(params int[] theParms) { long theSum = 0; for (int i = 0; i < theParms.Length; i++) theSum += theParms[i]; return theSum; } int[] intArray = {1, 2, 3, 4}; Console.WriteLine("Sum is {0}", Sum(intArray)) Back 63. Answers are: A. Mandatory parameters must be listed before optional parameters. (TRUE). B. Positional parameters must be listed before named parameters. (TRUE). C. Optional parameters can be marked as either "ref" or "out". (FALSE - Optional parameters can not be either "ref" or "out" parameters.) Back 64. Answer is: static long Multi(int firstParm, int secondParm = 3) { return (firstParm * secondParm); } long x = Multi(5, 5); Console.WriteLine(x); long y = Multi(5); Console.WriteLine(y); 65. Answer is: static void myMethod (char x='X', char y='Y', char z = 'Z') { Console.WriteLine("x is {0} and y is {1} and z is {2}", x, y, z); } myMethod('A', 'B'); //Prints: x is A and y is B and z is Z myMethod(y: 'A', x: 'B'); //Prints: x is B and y is A and z is Z myMethod(z: 'A'); //Prints: x is X and y is Y and z is A Back 66. Answers are: Division and Modulus operators are left-associative. Console.WriteLine(16 / 4 / 2); // Prints: 2 (Left-Associative) Console.WriteLine(16 / (4 / 2)); // Prints: 8 Console.WriteLine(16 % 3 % 2); // Prints: 1 Console.WriteLine(16 % (3 % 2)); // Prints: 0 Back 67. Answer is: The following operators are right-associative: 1. Assignment Operator (=) 2. Lambda Operator (=>) 3. Null Coalescing Operator (??) 4. Conditional Operator (?:) Back 68. Answer is: 68. Three operators which use parentheses are: 1. Cast, example: (int) x 2. Grouping, example: if (x==a) 3. Method Call, example: myMethod() Back 69. Answer is: Three unsafe operators are: 1. * is "Value at address" 2. & is "Address of value" 3. -> is "Pointer to struct" Back 70. Answers are: A. Console.WriteLine(z); // Compiler Error: Use of unassigned variable B. Console.WriteLine(x / y); // Prints: 0 C. Console.WriteLine(y/x); // Runtime Error: Division by zero D. Console.WriteLine(x/c); // Compiler Error: Division by constant zero E. Console.WriteLine(8 % (4 % 2)); // Compiler Error: Division by constant zero F. Console.WriteLine(8 / (2-2+1-1)); // Compiler Error: Division by constant zero Back 71. Answer is: int x = 1; { int x = 2; // Compiler Error: variable already defined int y = 3; } { int y = 4; int z = 5; } Console.WriteLine(x); Console.WriteLine(y); // Compiler Error: variable does not exist Console.WriteLine(z); // Compiler Error: variable does not exist Back 72. Answer is: ViualX Back 73. Answer is: Use an external alias to resolve the ambiguity. Compile with references to the dll's: csc /r:A1=one.dll /r:A2=two.dll myApplication.cs Define the external references as the very top of your code: extern alias A1; extern alias A2; Then use the alias when referencing the class: A1.MyClass // MyClass from one.dll A2.MyClass // MyClass from two.dll Back 74. Answer is: What ::token is commonly used in auto-generated code to avoid name conflicts between namespaces. It can be referenced from the root of all names as designated by the global keyword. global::TheNameSpace.TheClass(); 75. Answer is: The using directive is used to import namespaces, or to create an alias for a namespace or a type: using System; // Import namespace or using ST = System.Text.StringBuilder; // using alias directive class Program { ST p; } while the using statement ensures the correct use of objects which support the IDisposable interface. When you use an object that supports the IDisposable interface, it should be declared and instantiated inside a using statement to ensure the object is correctly disposed of in a timely manner. The using statement makes sure the object is disposed of as soon as the object goes out of scope instead of having to wait for garbage collection. The using statement is equivalent to putting the object in a try/finally block with Dispose() being called in the finally block. Back C# Basics CrossWord Puzzle Across 2. Structure used to represent an instance in time. 4. Used to declare a member that belongs to the type itself instead of an instance of the type. 6. Number of bytes used by the int data type. 8. The fundamental building block of C#. 10. Keyword used to indicate a class can not be inherited from. 11. Area of memory where a value type stores its contents. 15. The default way arguments are passed to parameters. 17. The type of a class. 18. Keyword used to invoke a context that allows for the use of pointers. 19. Default type for a real number literal that does not have a suffix. 21. Predefined type that should be used with financial calculations. 22. Keyword used to ignore integral arithmetic overflow. 23. Keyword used to define an input/output parameter. 24. A private field which contains accessor methods to read and/or write its value. 27. Number of bits used by the bool data type. 28. Keyword used to mark code to be skipped during the compile-time type checking. 30. The type of a struct. 31. Name for the area of memory where constants and static fields are stored. Down 1. Naming convention used for naming classes, structs, and methods. 3. Used to declare a member whose implementation is missing or incomplete. 5. Process of converting a value type to a reference type. 7. Type of array that does not contain the same number of elements in each dimension. 9. Keyword used to define an array of parameters. 12. Name for a set of keywords used to specify the accessibility level of types and type members. 13. The base type for all other types. 14. The process which reclaims memory used by objects that are no longer referenced. 16. Used to declare a method which can be overridden in a derived class. 20. Type used to create a group of named constants associated with an underlying integral type. 25. Type of array that contains the same number of elements in each dimension. 26. Number of bytes used by the char data type. 29. Naming convention used for naming parameters and variables. Answers Across 2. Structure used to represent an instance in time. (datetime) 4. Used to declare a member that belongs to the type itself instead of an instance of the type. (static) 6. Number of bytes used by the int data type. (four) 8. The fundamental building block of C#. (type) 10. Keyword used to indicate a class can not be inherited from. (sealed) 11. Area of memory where a value type stores its contents. (stack) 15. The default way arguments are passed to parameters. (byvalue) 17. The type of a class. (reference) 18. Keyword used to invoke a context that allows for the use of pointers. (unsafe) 19. Default type for a real number literal that does not have a suffix. (double) 21. Predefined type that should be used with financial calculations. (decimal) 22. Keyword used to ignore integral arithmetic overflow. (unchecked) 23. Keyword used to define an input/output parameter. (ref) 24. A private field which contains accessor methods to read and/or write its value. (property) 27. Number of bits used by the bool data type. (eight) 28. Keyword used to mark code to be skipped during the compile-time type checking. (dynamic) 30. The type of a struct. (value) 31. Name for the area of memory where constants and static fields are stored. (heap) Down 1. Naming convention used for naming classes, structs, and methods. (pascalcase) 3. Used to declare a member whose implementation is missing or incomplete. (abstract) 5. Process of converting a value type to a reference type. (boxing) 7. Type of array that does not contain the same number of elements in each dimension. (jagged) 9. Keyword used to define an array of parameters. (params) 12. Name for a set of keywords used to specify the accessibility level of types and type members. (accessmodifiers) 13. The base type for all other types. (object) 14. The process which reclaims memory used by objects that are no longer referenced. (garbagecollection) 16. Used to declare a method which can be overridden in a derived class. (virtual) 20. Type used to create a group of named constants associated with an underlying integral type. (enum) 25. Type of array that contains the same number of elements in each dimension. (rectangular) 26. Number of bytes used by the char data type. (two) 29. Naming convention used for naming parameters and variables. (camelcase)
http://www.kcshadow.net/wpdeveloper/?q=basicexam
CC-MAIN-2018-22
refinedweb
5,854
70.6
Java 9 Modular Development (Part 2) Java 9 Modular Development (Part 2) Get a look at how to develop, package, and run modules in Java 9, including how the Jlink tool works and an overview of JMOD files. Join the DZone community and get the full member experience.Join For Free In my previous post, we discussed modularity, module descriptors, and the details about module-info.java files. This article will help in developing a modular project step by step and packaging them as JARs and JMODs and also describes the steps needed to create runtime images by using jlink. We will be developing a small modular project that will print, "Hello Welcome to Java 9 Modularity" in the console. Project Structure Create the following structure: In the above structure, the src folder is used to create source files, the mods folder is used to place all the compiled class files, the libs folder is used to place the created JARs, and the jmods folder is for placing the packaged jmod files. Every module has a module-info.java file, which is the module descriptor file to define dependencies. (Refer to my previous post for details.) module com.gg.client{ } By default, the module's descriptor file is provided by the java.base module. Tha is why it is not mentioned in the code. In our example, the Client.java file is the placeholder for the logic and the contents are shown below. If we are going to use any other modules in this one, it should be mentioned in the com.gg.client module descriptor file. package com.gg.client; public class Client { public static void main(String[] args) { System.out.println("Hello Welcome to Java 9 Modularity"); } } Compiling the Source Code The project we have developed above is compiled using the Java compiler ( javac) command, as shown below. Also, save the compiled class files in the mods directory. The javac command is in the JDK_HOME\bin directory. The javac command is used to compile the project, -d is used to specify the directory to place the compiled class files, and --module-source-path is used to define the source file location. As we mentioned above, the java.base module is added by default as a dependency to all application modules. The below snapshot describes this by disassembling the class files via the javap command. We haven't mentioned the requires statement in our code, but it added the requires statement on its own. Running the Project The java command is used to run the client, where --module-path specifies the module's location and --module defines the module we have to run.Outcome of this is, it prints "Hello Welcome to Java 9 Modularity" Packaging the Module Code: JAR The jar command is used to create a JAR file, which is located in the JDK_HOME\bin directory. The '.' in the command is used to specify the current directory. Multi-Release JARs Java 9 introduced the multi-release JAR. Multi-release JARs are a single JAR containing the same release of a library for multiple JDKs. Example: The JAR contains the class files and the MANIFEST.MF file. The multi-release JAR has the version-specific class files the under META-INF directory. The classes specific to the JDK 9 will be in the /META-INF/versions/9 directory. The environment using a multi-release JAR will first check its version and use the classes that are all placed in that version. If the classes for that version are not available, then classes in the root directory will be used. The main advantage of a multi-release JAR is used to take advantages of the newer releases. The below snapshot describes the command for creating a multi-release JAR file from the classes which we have compiled in the previous steps. In addition to that, we have placed one Java 8 class file (Client8.class) in the builder8 directory to explain the multi-release JAR. The --create command is used to create the JAR while the --verbose command is added to check the operations happening behind the screen. --file specifies the name of the JAR file and --module-version specifies the version of the module. We can add the version to the module at the time of creation and not in the module descriptor file. --list is used to list all files in the JAR. The following snapshot is for running the JAR file. Creating jmod Files From Modules Java 9 uses the jmod tool to package all the platform modules. So, in this section, we are packaging our modules as jmod files using the jmod tool.The jmod tool is available in the JDK_HOME\bin directory. The create sub-command is used to create the jmod file. We can also set the --module-version to set the version that will be recorded in the module-info.class file. In the above command, the 'create' option is used specify the operation, --class-path is used to specify the JAR file location and then followed by the name of the jmod file with the extension as jmod. The gg.client.jmod file is created in the jmods directory of the project, and the jmod describe command is used to describe the jmod file. We can use the same command to describe the platform modules. The other options are extracting the jmod file and listing its contents of. The following snapshot will show an example. Jlink The Jlink tool is used to create custom, platform-specific runtime images, where the runtime images contain the specified application module and the required platform modules. The good thing about Jlink is needing to have the complete JRE. JDK 9 ships with the Jlink tool, which is available in the JDK_HOME\bin directory. But do we need to have all the classes (like security and logging) to print "Hello world"? The answer is no, but we used to load all the classes through Java 7. In Java 8, Oracle developers made an attempt to come up with the concept of compact modules (compact profiles). But even with compact profiles, we still have some unwanted classes. Sure, it was better than before, but in Java 9, Jlink is used to run only the required modules. Jlink's main intention is to avoid shipping everything and, also, to run on very small devices with little memory. By using Jlink, we can get our own very small JRE. Jlink also has a list of plugins that will help optimize our solutions. The details for each plugin and options in the Jlink tool will be covered in upcoming articles. To create the Jlink portable java command with simple options, the following general syntax will be used: jlink --module-path <modulepath> --add-modules <modules> --output <path> Here, module-path gives the module path locations, which will be separated by : in Linux and ; in Windows. Finally, --add-modules specifies the modules that need to be added, and --output specifies the output path. On executing the above command, we will be able to get the output in the specified path. The output package is shown below: If we look in bin, we will get our own little Java world. Running the Program Now the portable java command will be used to run our program. Listing the modules will display only the required modules. Note: Configuring the services and hashing the modules will be described in upcoming articles. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/java-9-modular-development-part-2?fromrel=true
CC-MAIN-2020-10
refinedweb
1,265
63.29
My XF UWP app in release mode behaves incorrectly compared to when in debug mode, so I think, although I am not experiencing the "Target Invocation Exception", I need to follow the advice listed here regarding the inclusion of assemblies in the Forms.Init call :- Is there a way to determine which assemblies to include? Is it just the list of references for the UWP project? Do I need to include assemblies that my references might be referencing? How do I determine which assemblies other assemblies are referencing? Based on the list here :- There seems to be a degree of duplication, is this required? I presume the perceived duplication is the fact that the same namespace might span across multiple assemblies? Answers If you are getting a different error - which one is it? Why would you think you have to add all these references? Does the error indicate this? I did not know about these UWP limitations in combination with X.Forms. There's something new to learn every day. I don't know if I am getting a different error as it is impossible to debug with the Compile with .NET Native tool chain option checked () I don't know if I have to add all these references as I don't know why my app would work one way in debug and another way in release mode. After further investigation I believe I have found one of the issues that was affecting my app's functionality between debug and release. This was due to the use of a constructor of the XmlSerializer class, which according to this document ( "aren't guaranteed to work as expected". I changed over to use the basic constructor (XmlSerializer xmlSer = new XmlSerializer(typeof(T));) instead of (XmlSerializer.XmlSerializer(Type, XmlRootAttribute)). For more info :- I have now removed all the assemblies I was loading in the App.xaml.cs, as this does not, at this time, seem required. I wonder if the Xamarin forums are the best place to discuss this. If you have a reproducible case you might get better answers over at StackOverflow.com I find StackOverflow.com to be quite restrictive in terms of me asking a question as most of the time I am unsure of what question I would like to ask and would really like to discuss the problem further, which SO doesn't lend itself very well too. I don't feel the problems I am running into are your usual coding issues which can be corrected in a simple manner that SO implies.
https://forums.xamarin.com/discussion/comment/317909
CC-MAIN-2018-43
refinedweb
427
62.68
When operating in C++ mode, KAI C++ is extremely close to ISO C++. The C++ Deficiencies section of this document lists all known places where KAI C++ deviates from ISO C++. When operating in C mode, KAI C++ is conformant to ISO C. KAI C++ does not provide an implementation of POSIX Threads. Instead, each operating system manufacturer provides an implementation of POSIX Threads. Conformance with the POSIX Threads standard is left up to the operating system manufacturer. KAI C++ does provide a command line option, --thread_safe, which causes KAI C++ to generate code that is compatible with the operating system's implementation of POSIX Threads. For C++ this means somewhat more than the traditional re-entrant code. It includes the use of the operating system's implementation of POSIX Thread mutexs to control construction and destruction of static objects, and other shared objects hidden from the user. --strictcommand line option to select full compliance to ISO C++ syntax/semantics (chapters 1-16). -D__KAI_STRICTcommand line option to select full compliance to ISO C++ class library (chapters 17-27). Certain system have #include files in the system header file directories that are not standard conforming. If you encounter compilation errors in system header files while using --strict, consider using the slightly relaxed system specific forms of restrict that are available on systems that have these problems. (for example: --linux_strict). --c --strictcommand line options to select full conformance to ISO C. \uabcd) exportkeyword for templates wchar stdnamespace both contain the name of some extern "C"library functions.
http://www.star.bnl.gov/public/comp/train/KAI/doc/Current/doc/standard.html
CC-MAIN-2017-47
refinedweb
255
55.74
ScrollableControl.DockPaddingEdges Class Determines the border padding for docked controls. For a list of all members of this type, see ScrollableControl.DockPaddingEdges Members. System.Object System.Windows.Forms.ScrollableControl.DockPaddingEdges [Visual Basic] Public Class ScrollableControl.DockPaddingEdges Implements ICloneable [C#] public class ScrollableControl.DockPaddingEdges : ICloneable [C++] public __gc class ScrollableControl.DockPaddingEdges : public ICloneable [JScript] public class ScrollableControl.DockPaddingEdges implements ICloneable Thread Safety Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe. Remarks The ScrollableControl.DockPaddingEdges class creates a margin on a given edge or all edges of a docked control. You can set the width of this margin for each individual edge by setting the following properties: Bottom, Top, Left, Right. Alternatively, you can set all the edges to the same width simultaneously by setting the All property. If the size of the control is too large for its container, the control will be resized to fit in the container, minus the specified margin width. Example [Visual Basic, C#, C++] The following example uses the derived class, Panel. The example docks a button in a panel control and cycles through the ScrollableControl.DockPaddingEdges properties, setting each individually on the click of the button. This code assumes a Panel control and a Button have been instantiated on a form, and a class-level member variable named myCounter has been declared as a 32-bit signed integer. This code should be called on the Click event of the button. [Visual Basic] = "Start"; break; case 1: panel1.DockPadding.Top = 10; button1.Text = "Top"; break; case 2: panel1.DockPadding.Bottom = 10; button1.Text = "Bottom"; break; case 3: panel1.DockPadding.Left = 10; button1.Text = "Left"; break; case 4: panel1.DockPadding.Right = 10; button1.Text = "Right"; break; case 5: panel1.DockPadding.All = 20; button1.Text = "All"; break; } // Increment the counter. myCounter += 1; } = S"Start"; break; case 1: panel1->DockPadding->Top = 10; button1->Text = S"Top"; break; case 2: panel1->DockPadding->Bottom = 10; button1->Text = S"Bottom"; break; case 3: panel1->DockPadding->Left = 10; button1->Text = S"Left"; break; case 4: panel1->DockPadding->Right = 10; button1->Text = S"Right"; break; case 5: panel1->DockPadding->All = 20; button1->Text = S"All"; break; } myCounter++; } ScrollableControl.DockPaddingEdges Members | System.Windows.Forms Namespace | ScrollableControl
https://msdn.microsoft.com/en-US/library/system.windows.forms.scrollablecontrol.dockpaddingedges(v=vs.71).aspx
CC-MAIN-2016-44
refinedweb
377
52.76
With respect of a given integer N, our task is to determine all factors of N print the product of four factors of N so that − It has been seen that if it is impossible to find 4 such factors then print “Not possible”. It should be noted that all the four factors can be equal to each other to maximize the product. 24 All the factors are -> 1 2 4 5 8 10 16 20 40 80 Product is -> 160000 Select the factor 20 four times, Therefore, 20+20+20+20 = 24 and product is maximum. Following is the step by step algorithm to solve this problem − // C++ program to find four factors of N // with maximum product and sum equal to N #include <bits/stdc++.h> using namespace std; // Shows function to find factors // and to print those four factors void findfactors2(int n1){ vector<int> vec2; // Now inserting all the factors in a vector s for (int i = 1; i * i <= n1; i++) { if (n1 % i == 0) { vec2.push_back(i); vec2.push_back(n1 / i); } } // Used to sort the vector sort(vec2.begin(), vec2.end()); // Used to print all the factors cout << "All the factors are -> "; for (int i = 0; i < vec2.size(); i++) cout << vec2[i] << " "; cout << endl; // Now any elements is divisible by 1 int maxProduct2 = 1; bool flag2 = 1; // implementing three loop we'll find // the three maximum factors for (int i = 0; i < vec2.size(); i++) { for (int j = i; j < vec2.size(); j++) { for (int k = j; k < vec2.size(); k++) { // Now storing the fourth factor in y int y = n1 - vec2[i] - vec2[j] - vec2[k]; // It has been seen that if the fouth factor become negative // then break if (y <= 0) break; // Now we will replace more optimum number // than the previous one if (n1 % y == 0) { flag2 = 0; maxProduct2 = max(vec2[i] * vec2[j] * vec2[k] *y,maxProduct2); } } } } // Used to print the product if the numbers exist if (flag2 == 0) cout << "Product is -> " << maxProduct2 << endl; else cout << "Not possible" << endl; } // Driver code int main(){ int n1; n1 = 80; findfactors2(n1); return 0; } All the factors are -> 1 2 4 5 8 10 16 20 40 80 Product is -> 160000
https://www.tutorialspoint.com/cplusplus-find-four-factors-of-n-with-maximum-product-and-sum-equal-to-n
CC-MAIN-2022-21
refinedweb
369
65.49
From: Aleksey Gurtovoy (alexy_at_[hidden]) Date: 2000-01-05 20:39:45 Dave Abrahams (abrahams_at_[hidden]) wrote: > >> Oh, and another thing: > >> > >> 1. Why not use std::swap() in restore_invariant? > >> 2. It would be lots more efficient just to use std::min()/std::max() and > >> never use restore_invariant at all. > >> [snip] > > OK, you're right. What about point #2 above, though? > Now you are right ;) I read your comment too quickly at the first time and didn't catch your thought.. Now I've got you. I'll remove 'restore_invariant'. > >> And finally: > >> > >> ~delta() {} // empty, just for enabling deletion through pointer to > >> 'delta' > >> > >> There is no logic to the comment, and functions like this will actually > >> result in significant 'pessimization' on many compilers (e.g. gcc, CW). > >> > > > > May be comment is indeed unclear, but actually there was a reason for this > > destructor - as I used public inheritance for 'units_pair' in 'point' class, > > and 'units_point' destructor is not virtual (and must to stay such), so I've > > tried to prevent deletion of points through units_pair<...>* - by declaring > > 'units_pair' destructor as protected. On the other hand, I want to allow > > deletion points through point<...>*, so I've just made destructor 'public' > > by declaring empty one in point... Am I missed something? And may be you can > > offer something much better - I'll be glad to learn something new and > > exciting ;) > > Hmm. You are correct, of course. The choices seem to be: > 1. The way you've got it > 2. Make base class destructor public, but put the base class in namespace > detail and don't tell people about it. > 3. Give up on sharing much code using the base class. > > I don't know which is best. > I think #2 can be a reasonable compromise. A declaration of a pointer to units_pair<..> is something like 'geometry::units_pair< long, geometry::delta<long> >* ptr;' and if you wrote something like this, you *must* expect some problems may occur, when you use it =). > >? > > To me it smacks of overdesign, but having seen Beman's comment I am > open-minded on the issue. > > Oh, here's another feature I like for my points: indexability (I like to be > able to access the coordinates by index). That allows programmatic selection > of orientation for things like scrollbars. Indexability is of course > unusable when the types of x and y differ. OTOH this is definitely a corner > case. I have no strong opinion on the topic. > We can provide generic version of classes with two template parameters (and without indexability) and a specialization for case T1==T2 with operator[]. I think it will be reasonable solution. -Alexy Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2000/01/1584.php
CC-MAIN-2020-05
refinedweb
458
67.96
buildout.eggtractor 0.6 Auto generates zcml slugs, buildout:egg and buildout:develop entries. buildout.eggtractor Q: What is a buildout extension ? A: The problem When developing zope/plone eggs with buildout I have to edit the buildout configuration file ( in 3 places ) each time I create/delete/rename a development egg in the src directory or in other development directories (sometime I have more than one). I have to add/delete/rename the egg in the eggs option of the [buildout] and then add/delete/rename the egg path in the develop option of the [buildout] and in the end add/delete/rename the zcml option of the zope [instance] or in the configure.zcml file of my policy package. This is too much specially when the speed is set to development mode. I need a less boring way to develop. Solution buildout.eggtractor is a buildout extension that scans the src directory or a list of directories I give for eggs and picks them up automatically. So no more editing of the buildout's configuration file. When buildout.eggtractor finds an egg in the scanned directory it: 1. adds the egg to the ``eggs`` option of all zope instance parts or to a set of given parts 2. adds the egg's path in the ``develop`` option of the ``[buildout]`` 3. If ``tractor-autoload-zcml`` is not given or set to other thing than false, scans the egg folder for ``configure.zcml``, ``meta.zcml`` and ``overrides.zcml`` and adds the appropriate zcml entries to the ``zcml`` option of the zope instance parts or to a set of given parts. This steps are done on the fly when running buildout. So I can add/delete/rename an egg and it will be picked up. NOTE: The extension does not write to the buildout's configuration file. buildout.eggtractor options - tractor-src-directory: - A set of directories to scan for development eggs. Defaults to the src directory of the buildout. - tractor-target-parts: - A set of parts to update their eggs option with eggs found in the tractor-src-directory. Defaults to zope instance parts if any. - tractor-autoload-zcml(boolean): - Update the zcml option of tractor-target-parts with the eggs found in tractor-src-directory. Defaults to true - tractor-zcml-top: - A set of eggs to load their zcml files first. Defaults to an empty set. How to use it Using buildout.eggtractor is very simple. As said, it is a buildout extension. All I have to do is to declare it in the extensions option: [buildout] parts = extensions = buildout.eggtractor That's all. buildout.eggtractor will scan the src directory and do its job every time I run the buildout command. When I have other directories I want to scan I just add an tractor-src-directory option in the [buildout] and add my directories there: [buildout] parts = extensions = buildout.eggtractor tractor-src-directory = dev-src1 dev-src2 src In a few cases when the priority of loading zcml files matters. I add the egg to be loaded first in the tractor-zcml-top option in the [buildout]: [buildout] parts = extensions = buildout.eggtractor tractor-src-directory = dev-src1 dev-src2 src tractor-zcml-top = plone.app.mypackage1 If I want to add the eggs found in the development directories to the eggs option of a given set of parts, I add a tractor-target-parts option and add the parts there: [buildout] parts = instance1 instance2 instance3 extensions = buildout.eggtractor tractor-target-parts = instance1 instance3 This way only instance1 and instance3 will be updated. If I have already other way to include the zcml files (ie: z3c.autoinclude) and don't want eggtractor to generate the zcml slugs, I add an tractor-autoload-zcml option and set it to false In most cases you will only need to add buildout.eggtractor to the extensions option of the [buildout] without any extra configuration options. LIMITATION: The extension assumes that the egg name reflects its file system structure example: if the egg name is com.mustap.www the extension assumes that the file system structure is one of the following: 1. com.mustap.www/src/com/mustap/www 2. com.mustap.www/com/mustap/www This is where the extension looks for configure.zcml, meta.zcml and overrides.zcml files. If the egg name has nothing to do with how it is structured on the system, the extension will ignore it. XXX: I guess walking through the directory is better than this assumption. In my case this is not a limitation as I choose my egg names that way. Mustapha web: Change history 0.6 (2008-10-29) - fixed install problem on windows: - split buildout configuration values before we test if an egg was added already. using 'in' with a string doen't work if an egg's name is a substring of an already added egg (e.g. plone.app.content after plone.app.contentmenu). [csenger] - sort output of os.listdir (it's order is undefined) to make debugging easier. [csenger] 0.5 (2008-04-30) - Refactoring Added tractor-target-parts option Added tractor-autoload-zcml option Updated documentation Updated tests: need more tests [mustapha] 0.4 (2008-04-27) - Made sure the configure.zcml is added to package includes if a meta.zcml or overrides.zcml in the same packages have already been found. [hannosch] 0.3 (2008-04-27) - Use a new line as a separator for added entries. A space makes buildout think it has to deal with a version specifier. [hannosch] 0.2 (2008-04-27) - Added support for automatically finding multiple instances. [hannosch] - Better use the recipe name for finding the instance, as this is less likely to conflict. [hannosch] 0.1 (2008-04-27) - Whitespace fixes. [hannosch] - Created recipe with ZopeSkel. [mustapha] Detailed Documentation Tests for buildout.eggtractor buildout extension Let's create a buildout configuration file: >>>>> rmdir(tempdir, 'buildout.test') >>> cd(tempdir) >>> sh('mkdir buildout.test') mkdir buildout.test <BLANKLINE> >>> cd('buildout.test') >>> touch('buildout.cfg', data=data) >>> ls('.') buildout.cfg run the buildout first time so wget our zope instances: >>> sh('buildout bootstrap') buildout bootstrap Creating directory '/tmp/buildout.test/bin'. Creating directory '/tmp/buildout.test/parts'. Creating directory '/tmp/buildout.test/develop-eggs'. Generated script '/tmp/buildout.test/bin/buildout'. <BLANKLINE> >>> sh('bin/buildout') bin/buildout ... Installing instance1. Generated script '/tmp/buildout.test/bin/instance1'. Generated script '/tmp/buildout.test/bin/repozo'. Installing instance2. Generated script '/tmp/buildout.test/bin/instance2'. <BLANKLINE> <BLANKLINE> Now let's create an egg in the src directory: >>> sh("paster create --no-interactive -o src -t plone_app com.mustap.www namespace_package=com namespace_package2=mustap package=www") paster create --no-interactive -o src -t plone_app com.mustap.www namespace_package=com namespace_package2=mustap package=www ... ...setup.py egg_info <BLANKLINE> Ok, so now that we have an egg, lets run the buildout in offline mode. We should get a link file in develop-egg, a zcml slugs in parts/instance1/etc/package-includes and parts/instance2/etc/package-includes and a line with the path to our egg in the bin/instance1 and bin/instance2 files. First we check that there is nothing of the previous mentioned things: >>> ls('develop-eggs') >>> ls('parts/instance1/etc/package-includes') No directory named parts/instance1/etc/package-includes >>> ls('parts/instance2/etc/package-includes') No directory named parts/instance2/etc/package-includes >>> sh('grep com.mustap.www bin/instance1') grep com.mustap.www bin/instance1 <BLANKLINE> >>> sh('grep com.mustap.www bin/instance2') grep com.mustap.www bin/instance2 <BLANKLINE> OK, now run the buildout in offline mode: >>> sh('./bin/buildout -o') ./bin/buildout -o ... Check that we have a correct created buildout. First check that we have a link in the develop-eggs directory: >>> ls('develop-eggs') com.mustap. Check that we have our zcml slugs in the package-includes: >>> ls('parts', 'instance1', 'etc', 'package-includes') 001-com.mustap.www-configure.zcml >>> ls('parts', 'instance2', 'etc', 'package-includes') 001-com.mustap.www-configure.zcml and in the end check that there is a line in bin/instance1 and bin/instance1 that includes our egg in the path: >>> cat('bin', 'instance1') #!/usr/bin/python2.4 ... sys.path[0:0] = [ '/tmp/buildout.test/src/com.mustap.www', ... ] ... >>> cat('bin', 'instance2') #!/usr/bin/python2.4 ... sys.path[0:0] = [ '/tmp/buildout.test/src/com.mustap.www', ... ] ... Let's now try the tractor-target-parts option. We create a new buildout.cfg file with an empty tractor-target-parts: >>> data = data.replace('eggs =', 'tractor-target-parts = \neggs = ') >>> touch('buildout.cfg', data=data) >>> sh('./bin/buildout -o') ./bin/buildout -o ... We get the egg link in the develop-egg directory: >>> ls('develop-eggs') com.mustap. But no zcml slug in the instance 1 and 2: >>> ls('parts', 'instance1', 'etc', 'package-includes') No directory named parts/instance1/etc/package-includes >>> ls('parts', 'instance2', 'etc', 'package-includes') No directory named parts/instance2/etc/package-includes Nor a line in bin/instance1 and bin/instance2 with our egg path: >>> code = cat('bin', 'instance1', returndata=True) >>> code.find('com.mustap.www') == -1 True >>> code = cat('bin', 'instance2', returndata=True) >>> code.find('com.mustap.www') == -1 True But if the tractor-target-parts option is not empty: >>> data = data.replace('tractor-target-parts =', 'tractor-target-parts = instance1') >>> touch('buildout.cfg', data=data) >>> sh('./bin/buildout -o') ./bin/buildout -o ... and we get a zcml slug only in the specified target: >>> ls('parts', 'instance1', 'etc', 'package-includes') 001-com.mustap.www-configure.zcml >>> ls('parts', 'instance2', 'etc', 'package-includes') No directory named parts/instance2/etc/package-includes and only the specified target's control script is updated: >>> code = cat('bin', 'instance1', returndata=True) >>> code.find('com.mustap.www') == -1 False >>> code = cat('bin', 'instance2', returndata=True) >>> code.find('com.mustap.www') == -1 True Contributors - mustapha, Author - hannosch, Minor fixes - Author: Mustapha Benali <mustapha at headnet dk> - Keywords: buildout extension egg tractor - License: GPL - Categories - Package Index Owner: hannosch, mustap, wichert, sidnei - DOAP record: buildout.eggtractor-0.6.xml
http://pypi.python.org/pypi/buildout.eggtractor/
crawl-002
refinedweb
1,667
50.84
Creating .NET Compact Framework applications that use Message Queuing (also known as MSMQ) is similar to the process that is used in the .NET Framework. However, Windows CE does not support all the features described in MSMQ in the .NET Compact Framework. The following code examples show how to create a message queue, send a message to the queue, and receive a message from the queue, all on the same device. No network connectivity is required. A simple class, Order, is used to create objects for Message Queuing. These examples assume that Message Queuing has been installed on the device. For more information about obtaining the Message Queuing component, see MSMQ in the .NET Compact Framework. Add the following class to your project. ' This class represents an object that ' is sent to and received from the queue. Public Class Order Dim ID As Integer Dim DTime As DateTime Public Property orderID() As Integer Get Return Me.ID End Get Set(ByVal value As Integer) Me.ID = value End Set End Property Public Property orderTime() As DateTime Get Return Me.DTime End Get Set(ByVal value As DateTime) Me.DTime = value End Set End Property End Class Add the following method to your form. Private Sub CreateQueue() ' Determine whether the queue exists. If Not MessageQueue.Exists(QPath) Then Try ' Create the queue if it does not exist. myQ = MessageQueue.Create(QPath) MessageBox.Show("Queue Created") Catch ex As Exception MessageBox.Show(ex.Message) End Try Else MessageBox.Show("Queue Exists") End If End Sub Private Sub SendMessageToQueue() ' Create a new order and set values. Dim sendOrder As New Order() sendOrder.orderID = 23123 sendOrder.orderTime = DateTime.Now Try myQ.Send(sendOrder) MessageBox.Show("Message Sent") Catch ex As Exception MessageBox.Show(ex.Message) End Try End Sub Private Sub ReceiveMessageFromQueue() ' Connect to the a queue on the device. myQ = New MessageQueue(QPath) ' Set the formatter to indicate the body contains an Order. Dim targetTypes() As Type targetTypes = New Type() {GetType(Order)} myQ.Formatter = New XmlMessageFormatter(targetTypes) Try ' Receive and format the message. Dim myMessage As Message = myQ.Receive() Dim myOrder As Order = CType(myMessage.Body, Order) ' Display message information. MessageBox.Show("Order ID: " & _ myOrder.orderID.ToString() & _ Chr(10) & "Sent: " & myOrder.orderTime.ToString()) Catch m As MessageQueueException ' Handle Message Queuing exceptions. MessageBox.Show(m.Message) Catch e As InvalidOperationException ' Handle invalid serialization format. MessageBox.Show(e.Message) End Try End Sub Add a button to the form, labeled Send, that calls the CreateQueue and SendMessageToQueue methods. Add a button to the form, labeled Receive, that calls the ReceiveMessageFromQueue method. This example requires references to the following namespaces: System System.Messaging System.Windows.Forms
http://msdn.microsoft.com/en-us/library/ms172497.aspx
crawl-002
refinedweb
442
53.07
Inserting variables to database table using Python In this article, we will see how one can insert the user data using variables. Here, we are using the sqlite module to work on a database but before that, we need to import that package. import sqlite3 To see the operation on a database level just download the SQLite browser database. Note: For the demonstration, we have used certain values but you can take input instead of those sample values. Steps to create and Insert variables in database Code #1: Creat the database Explanation: We have initialised the database pythonDB.py. This instruction will create the database if the database doesn’t exist. If the database having the same name as defined exist than it will move further. In the second statement, we use a method of sqlite3 named cursor(), this help you to initiate the database as active. Cursors are created by the connection cursor() method, they are bound to the connection for the entire lifetime and all the commands are executed in the context of the database session wrapped by the connection. Code #2: Create table Explanation: We have created a function create_table. This will help you to create table if not exist, as written in the query for SQLite database. As we have initiated the table name by RecordONE. After that we pass as many parameters as we want, we just need to give an attribute name along with its type, here, we use REAL and Text. Code #3: Inserting into table Explanation: Another function called data_entry. We are trying to add the values into the database with the help of user input or by variables. We use the execute() method to execute the query. Then use the commit() method to save the changes you have done above. Code #4: Method calling and Close the connection. Explanation: We normally use the method call, also remember to close the connection and database for the next use if we want to write error-free code because without closing we can’t open the connection again. Let’s see the complete example now. Example: Output: Inserting one more value using data_entry() method. Output: Recommended Posts: - Python | Inserting item in sorted list maintaining order - Python | Database management in PostgreSQL - Python MySQL - Create Database - Oracle Database Connection in Python - Unicodedata – Unicode Database in Python - Create a database in MongoDB using Python - Python Variables - Python Scope of Variables - Private Variables in Python - Python | Extract key-value of dictionary in variables - Python | Unpack whole list into variables - Class or Static Variables in Python - Global and Local Variables in Python - Python Program to Swap Two Variables - Tracing Tkinter variables.
https://www.geeksforgeeks.org/inserting-variables-to-database-table-using-python/?ref=rp
CC-MAIN-2020-24
refinedweb
442
59.84
Regular readers might have spotted I've been slightly quieter than usual over the past few weeks - actually I've not been slacking, but working on a tool which you might find useful from time to time. As I've discussed in numerous posts, deployment of SharePoint artifacts is something that's perhaps more complex than it should be, and the standard tools provided don't always simplify this picture. Personally, over my past few MOSS projects, there have been several times when I've thought: - I just need to move this document library from A to B - I just need to move these selected files (e.g. master page, page layouts, CSS etc.) from A to B - I just need to move this web from A to B - I just need to move this site collection from A to B - I just need to move these 20 list items from A to B If only there was an easy way! CMS 2002 users may remember the SDO export mechanism which allowed you to use a treeview to select exactly which content you wished to move, but unfortunately there's no similar tool for MOSS. Sure, we have Content Deployment and STSADM export etc., but the lowest level of granularity is a web, and if you don't want to overwrite the whole thing neither option can be used. The only other option is to write code which uses the Content Migration API. This is fine for projects which have the appropriate development skills and time, but otherwise things can be tricky. Enter the SharePoint Content Deployment Wizard. The tool provides a wizard-like approach to deploying content between SharePoint sites. The selected content is exported using the Content Migration API (PRIME), giving a .cmp file (Content Migration Package) which can be copied to other servers. Since pictures are often more useful than words, let's look at using the tool. Click to enlarge any of the images below: EXPORTING CONTENT Welcome screen (click any image to enlarge): Select action (import or export) and provide site URL: For export, use the treeview to select which content you wish to deploy. On container objects such as webs, there are options about whether descendent objects should be included: Select options around security, dependencies, versions and name of the export file: Browse to the .cmp file we exported in the previous steps, and select options around security, versions and, importantly for some scenarios, whether object IDs should be retained: The details are shown back for confirmation, and when 'Finish' is clicked the import will begin: And that's the gist of it. This is the first beta of the tool and I'm sure there will be issues. Regardless, when using any tool which makes this kind of change to your data you should always take a backup before performing the import. Depending on what you're doing, it could be difficult to revert back to the previous state otherwise. Some other notes: - the tool must be installed locally on the server which hosts the site - not all features of the Content Migration API are supported by the tool - the next beta (mid-December) will properly support large sites - currently the site bind operation can be slow for large sites since the treeview is built in one operation - it must be run under an account which has the appropriate permissions to the SharePoint site - use the Windows 'Run as..' feature to do this if necessary (shown below in the image below- right-click on the .exe and select 'Run as..') 222 comments:1 – 200 of 222 Newer› Newest» does this also work with WSS 3.0? or only MOSS? Chris! What a great contribution to the community! Content deployment has been one of the biggest things they missed in the product. When you look at MOSS in the eyes of a MCMS dev, you assume that they at least created all the features you were familiar with in MCMS - even if they improved on them. However, it's not the case. Content Deployment has been a big disappointment. I look forward to giving your tool a try simply because I will have a call for content deployment in an upcoming project. There *is* an equivalent to the CMS treeview for moving content, and its out-of-the-box. It's called 'Manage Content and Structure' and it is available at /_layouts/sitemanager.aspx when you activate the Office SharePoint Server Publishing Infrastructure feature on your site collection. Many OOTB site templates come with this feature activated (such as Collaboration Portal and Publishing Portal). Either way, there are uses for this wizard-based UI. Good job! Wow, this looks fantastic. Can't wait to try it out. Awesome work mate! This looks like a great free tool. I think there is a tool on the market that does this (echo for SharePoint ()) but that may be overkill for simple single doc lib. content moves. Great tool - I've been wondering how to do the things you mention without going crazy over it. :) Looking forward to the final version! Possible to move the site / list from one site to another site within the same site collection?? Looks awesome... have to check this out. @Peter, Yes this is possible. This is known as 'reparenting' and I wrote the following notes on the Codeplex page: Reparenting of objects such as webs and lists is possible with the following usage on the import: - enter the URL for the target web in the 'Import web URL' textbox - ensure 'Retain object IDs and locations' is not checked I'll post very soon with some more information on different options. HTH, Chris. Chris, How does one export a complete app and import it into a totally different server? I tried export, immediately followed by an import. The problem is that import requires visibility of the source from the target machine. When I try to use the .cmp, I get an error. Dov I have installed the tool on two different servers so that I can move a copmlete app from one server to another (not in the same farm). Now I exported the site to a cmp file on a network drive and I try to import it to the other server. I get an error: "Could not find webtemplate CALLCENTER#75812 with LCID 1033" What does this mean? BTW, I love your use of the archaic "whilst" and thank thee for it. Hi Dov, To move a complete app you should right-click on the root node of the tree and select 'Export > Include all descs'. This will export the root web of the site collection and everything beneath it. Visibility of the source from the destination is definitely not required - this won't be your problem. Remember that all filesystem dependencies are not captured by the tool, so any site definitions, Features, assemblies etc. should be applied to the destination before the import. If you fail to do this, the exact cause of the import error (i.e. which dependency is missing) should be logged in the import log file which is generated (the tool tells you the location). Ping me back if can't resolve with the log information. Cheers, Chris. @coachcs, The error that you're seeing seems to point to a dependency which you must resolve before the import can work successfully. In this case, it looks like a custom site definition - since these comprise files on the filesystem (in the 12 directory), these must be copied to the destination before running the import. Best thing to do would be to find out what all the files related to the site definition are, then copy them to the destination prior to re-running the import. HTH, Chris. P.S. Thanks for the grammar observation :-) Hi Chris, Great tool, thanks for making it available for all of us. I was expirimenting with it today on a Wss3 only machine, export goes great, but import gives an IO.FileNotFound exception. After some testing I found out that for the import you depend on the MOSS microsoft.sharepoint.publishing assembly. First of all it might be a good idea to test if this assembly is available, and give a warning if not, second, it is really a pitty to depend on this assembly, because the whole content migration API is a Wss3 thing that is really useful in a Wss3 only solution. I hope you can make your tool independent of MOSS in your next release! Keep up the good work! Regards, Serge Hey Serge, Great feedback thanks. I found where a class from the Publishing assembly is used - applying publishing schedules from the source onto the destination so that they are respected there. So it should be entirely possible to check for the assembly, go ahead and do this if present, but present a warning somewhere if not. Hence WSS-only support should definitely appear in the next release, and I agree the tool should support WSS-only. Thanks again for the feedback Serge, much appreciated. Chris. P.S. Next release should be in around 3 weeks - I'm just slightly tied up until then with some other community stuff I was asked to do. Hi Chris, nice tool you made. Is it possible to run it from a command prompt so I can schedule the export/import? Cheers, Sjoert @Sjoert, Not at this stage I'm afraid. It might be possible in a future release however, I'll add it to my list of functionality to consider. Thanks for the feedback. Chris. Great Tool... How do you differentiate between the three export option. Also, regarding the Lists, even if you say overwrite/Append, if it finds the List with same name in the target Site, it totally errors out. Possibly, it should give an error message and move on. Is it possible to import to a existing site with overwrite/append options without the same GUID Thanks a lot for the tool Hi, My post on Using the Content Deployment Wizard covers some of your questions, particularly the difference between Export > Include descendants/Content only/Exclude descendants. For your second question/comment, I'm pretty sure the error will be coming from the underlying SharePoint API rather than the tool, so examine the error message and consider the settings you're using. Even so, something doesn't sound right - you should definitely be able to update list items OK. If the items already exist on the destination, consider if they will currently have the same GUID - this should guide you in deciding whether to select 'Retain object IDs and locations' or not. This is also relevant to your last question/comment. Generally I've selected the option to retain object IDs, but it depends on exactly what you're doing. Key Concepts in Selective Migration and Stefan's Deep Dive into the SharePoint Content Deployment and Migration API - Part 5 article offer good information on this. Hope this helps, if you're still having specific problems let me know the exact details and I'll try to help further. Cheers, Chris. I love this tool. I want to take the content of a subsite of one location (different app) to a top-level managed path elsewehre. example: site.company.com/subsite to smith.company.com/managed_path. What happened is that the subsite went to smith.company.com/managed_path/subsite instead of placing the content in the managed_path URL. Any idea what I did wrong? export settings: chose the subsite and selected Include all descendents; Retain objtect ~ left blank; exlcude dependecnies ~ checked. Import Settings: Retain object ID's ~ left blank. Any input is greatly appreciated. gedurish@hotmail.com Hi Gerry, That's an interesting question - the reason this happened is because when you selected the subsite (web) for export, assuming you select "All descendents" you are effectively saying "take this web and everything beneath it". You are not saying "take only the contents of this web". So it's useful to consider the web as an object in it's own right, if that helps. When you import, you are adding that object (and all children) to the new parent site. So you have two options: - do not create the subweb before doing the import - let the import job create it for you. You should import to your new site's root web by either leaving the 'Import web URL' box blank or entering "" (either will work) - if the target subweb already exists, export the contents of the original web only by "cherry-picking" them from the treeview. You'll need to specify the 'Import web URL' as "" in this case (this URL should already be browsable) Any other questions, feel free to leave another comment. HTH, Chris. I chose the apps subweb i.e. site.company.com/subweb and included all descendants. I did not choose site.company.com and included all descendants. Correct me if I'm wrong. I assume descendants are the web itself and all its subsites - nothing from above? The new location already exists in it's own database (no content in it yet). It is a managed path. You are correct I could import to and it would create the subsite, but the content would go to the wrong database. If you'd like, I could send you screen shots of what I did. Gerry, Yes, you're right in your assumption. I've not worked with managed paths specifically, but if I understand how they work you'd need to use my option 2 to do this - go beneath the source web in the treeview and cherry-pick each list/subweb. Remember to also specify the import web URL on the import. If my understanding of managed paths is right, this should work. Let me know.. Chris. Do I need to cherry pick on the export and the import? I cherry pick the import and I ended up with smith.com.com/web/web. My work around was to use your tool for a difficult migration and I ended up with the result described. I then used stsadm for a new import and export. I deleted and recreated the managed path. Stsadm correctly fixed the problem. You can only cherry-pick on the export, since the tool will always import all the contents of your chosen package. It sounds like you got there in the end, just remember that STSADM will allocate new IDs for all your objects on import. This can be a problem in certain scenarios, e.g. if ListView web parts are used or you wish to use Content Deployment between the source and destination site. If these don't apply you should be OK though. Cheers, Chris. Hi Chris - great tool. Thanks for sharing it. I have 2 questions for you: - is there a way to export a site with all its associated user groups? - do you plan to have a bug reporting system in the future for beta-testers? Guillaume Hi Guillaume, Yes it is possible to export security groups along with the content. Select 'All' from the 'Include security' dropdown to do this. In terms of bug reporting, adding issues on the codeplex site is the best idea - I monitor it regularly. Interested in all feedback! Thanks, Chris. Chris - I cannot believe you built this incredible tool. Here was complaining that we started using SP on a development box and people will want to migrate their lists to production when we are ready. And you took care of that problem for us. Thank you!!! it must be run under an account which has the appropriate permissions to the SharePoint site - use the Windows 'Run as..' feature to do this if necessary (shown below in the image below- right-click on the .exe and select 'Run as..') Anyway, I have an export problem that is related to security. When I run with my account that has admin rights to the SP server, I get System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) errors. When I do a RUN AS as my user account that is a Sharepoint admin, but not a user on the server, I keep getting a message "Unable to contact sute at address..." Please Help??? TIA, Dave Dave, Is anything written to the log file from the export/import operation? This might give a clue as to what the permissions issue is. Or are you not getting as far as being able to start the operation? Remember the account you use will also need permissions to write to the folder where the export/log files are saved. Cheers, Chris. I am struggling with a situation. I ran prescan on a WSS 2.0 site: smith.company.com. I copied the database. I created a new site in 2007 called smith2007.company.com, pointed it to the copied database and everything worked wonderfully. The site contains events with workspaces and the workspaces resolve when clicked. However. if I run stsadm or use the content deployment wizard to export/import of smith2007 and move it to a site collection, the workspaces resolve to the wrong URLs. I cannot find the code to change the URL. What happens is if I have a site collection: gohere.company.com/sitecollection/site the links for the workspaces will go to gohere.company.com/workspace. The 'sitecollection' is dropped from the link. I have no idea where this is codes. If I add the missing information into he URL in the webbrowser, the workspace resolves. This hard coded information is killing me. Has anyone come across these situations where URL's do not resolve? I opened the site in SP Designer and searched code, there is no reference to the incorrect URL's. They must be in the database or something. Any thoughts? Hi Chris, I am getting the following exception when exporting: [2/20/2008 11:08:11 AM]: Start Time: 2/20/2008 11:08:11 AM. [2/20/2008 11:08:11 AM]: Progress: Initializing Export. [2/20/2008 11:08:11 AM]: FatalError: Illegal characters in path. at System.IO.Path.CheckInvalidPathChars(String path) at System.IO.Path.NormalizePathFast(String path, Boolean fullCheck) at System.IO.Path.GetFullPath(String path) at Microsoft.SharePoint.Deployment.DataFileManager.get_CompressedFile() at Microsoft.SharePoint.Deployment.ExportDataFileManager.VerifyFileLocation() at Microsoft.SharePoint.Deployment.ExportDataFileManager.VerifyDataFileLocation() at Microsoft.SharePoint.Deployment.ExportDataFileManager.Initialize() at Microsoft.SharePoint.Deployment.SPExport.InitializeExport() at Microsoft.SharePoint.Deployment.SPExport.Run() [2/20/2008 11:08:13 AM]: Progress: Export Completed. [2/20/2008 11:08:13 AM]: Finish Time: 2/20/2008 11:08:13 AM. [2/20/2008 11:08:13 AM]: Completed with 0 warnings. [2/20/2008 11:08:13 AM]: Completed with 1 errors. I can export fine a particular piece of content from 1 box but I would get the above exception from another. I gather this must be down to an environment issue rather than a SharePoint content issue. Do you know how I could figure out more precisely where this problem is coming from ? Thanks, Guillaume @GerryD, I guess the key is working out how those links are generated. I'm afraid I haven't done much with workspaces or WSS2.0 upgrades, so not sure what the issue could be. Anyone else chip in? Chris. @Guillaume, It looks like there is an issue with where you are trying to save the file to in that environment. Is it an extremely long path or are there any strange characters? Suggest trying to save to different locations on that machine to see if that makes a difference. HTH, Chris. Thanks for your help Chris. I tried exporting to the C drive and it did make a difference. The path which the wizard was struggling with was a shared drive, and it was definitely a long one! Guillaume @Guillaume, Thanks for letting me know, that's useful. I'll try and add better exception-handling for this scenario in the next release. Cheers, Chris. Hi I've a big problem in the stsadm -restore command We only had Site collection backups and we need one site the user deleted from the backup We did the backup in the production server and one of the user deleted the site(:)) and we’re trying to get the site backup. When we try to restore we're getting the following error C:\Documents and Settings\rameshk>stsadm -o restore -url -filename z:\projects.bak -overwrite Your backup is from a different version of Windows SharePoint Services and cannot be restored to a server running the current version. The backup file should be restored to a server with version '3701403.0.1196032409.29915337' or later. I saw few post on this error. - I did install the MSITDelete Site capture on my local machine. Not sure that is the problem. If only have installed this the production, that would have saved almost two days and still no postive results But not any solutions though. I don't know whether Microsoft knows about this or something I'm not doing correctly. And by the way, if I have backup using stsadm can I read it using Content API or any other tool which wil read the data and restore it Any help will be greatly appreciated. Thanks Ramesh @Ramesh, Afraid I've not experienced this particular error but can imagine if different versions (service packs/hofixes etc.) are used in different environments there could be problems. Since STSADM export uses the content migration API underneath, I'm pretty sure you won't be able to use this API to help the situation unfortunately. HTH, Chris. I would try a different route. Get the last known sql backup. Create a temporary top level site from the sql backup. Uses stsadm -o export to grab the subsite and then use stsadm -o import to put the subsite where you want it. Thanks Chris and Gerry, The problem is that we have only Site Collection backup and the site has been already deleted. If we want the site that has been deleted we have to use the existing backup. Is there a way to find out what what are the hotfixes(we haven't applied the SP1 in production yet) Some of them are not showing up in the add/remove program. Thanks Ramesh Thanks Guys for the help Finally, I was able to find ou the issue. The size of the file is 10Gb and we;re trying to copy from Production Datacenter to dev box using Robocopy and it seems robocopy failed to copy after so many items and it leaves a same size file with some junk in the file. So, breaked up and compressed the backup using 7zip utility ( you would think, backup is compressed:), but it is not) using the and used robocopy to copy the file and it worked like a charm when we restored the site. I hope this saves some one some (or a lot of) time Thanks Ramesh Awesome. Thanks for building and sharing this great tool. Hi, Chris, This is a great tool, and we have been using it to migrate portals for customers. We have been enountering excepctions during the process. I there any chance of the new beta/rtm version coming out any time soon? Otherwise, is the source code available? I would like to try overcoming the issues we've encountered. @Adi, As I discuss on Recipe for successful use of the Content Deployment Wizard, the Wizard code itself is actually pretty stable despite the beta label. Your issues are more likely to come from the underlying MS API rather than the Wizard code, - suggest checking my earlier posts and also Stefan Gossner's blog for info on content deployment which might help. Otherwise, please feel free to post your errors here and I'll try to help you work through them. Cheers, Chris. Hi Chris, and thanks 4 this great tool. Is it possible to move(reparenting) an entire site collection to a subsite?? @Jose, Sorry for the delay in replying. Yes this should be possible - however, now I come to think about it, this could be a scenario I didn't cover in my series of tests. If you have any problems drop me a line and I will help. Thanks, Chris. Hello Chris, thanks for this tool!!! I have understood well, we dont have the feature Content Deployment in the WSS just in MOSS, is this right? Thanks, Fabiano Brito (MOSS Admin from Brazil) Hi Fabiano, As far as I understand the standard content deployment interface in SharePoint is only visible under MOSS (not WSS) as you say. However, the Wizard is capable of working with WSS-only sites since it uses the API directly. HTH, Chris. Hi Chris, First good job of this tool. Second, I got a issue: I am trying to move a site across different domain but I got this Error: Access denied. SharePoint.SPGlobal.HandleUnauthorizedAccessException() I am using the form authentication under my source web. Any ideal? Thanks. Ji @Ji, Thanks. Your error is likely to be because the Windows user you are running the Wizard as does not have permissions in the SharePoint site you are trying to export/import. The best way of working with forms auth sites to extend on to another web application which uses Windows auth - use this site when working with the Wizard. HTH, Chris. hi... we have used your tool & succesfully exported. but when we are going to import it into another server it gives an error "the SMS event handler is not found", we have removed that event handler form the main site & export it again. but when we are going to import it, the same erro is populated... plz help us.. thanks Hi Chanaka, Generally this error only occurs when there still is an event handler somewhere on the source, but it isn't possible to add it on the destination during the import (e.g. because the code isn't yet present on that environment). My suspicicion is that you still have the event handler registered somewhere on the source. Suggest writing some code to iterate through all your lists to check? HTH, Chris. Chris, We're facing a weird scenario with import/export. Appreciate your help on this. Our requirement is export a web and reimport to a new web ( in same site collection). Source web has pages based on custom content types (derived from Article Page). Import runs good, however in target web->Pages->Doc lib settings-> Click on custom content type, all the site columns appear in duplicate ( not only custom fields, but some OOB fields such as roll up image, image caption etc). So when someone edits the page properties, all these fields appear in duplicate - field id referred here is same for the duplicates. - Custom Content at site coll level is intact. no duplicates Any help on this is much appreciated. Attaching code snippet. private static void ExportImport() { SPSite spsite = new SPSite(""); SPWeb spweb = spsite.OpenWeb("/source"); SPWeb destspweb = spsite.OpenWeb("/target"); SPExportObject exportObject = new SPExportObject(); exportObject.Id = spweb.ID; //Only content ( pages, lists etc needed) exportObject.IncludeDescendants = SPIncludeDescendants.Content; exportObject.Type = SPDeploymentObjectType.Web; // Creating export settings object to export content SPExportSettings settings = new SPExportSettings(); settings.SiteUrl = spsite.Url; // Exporting all the sites,subsites and content pages settings.ExportMethod = SPExportMethodType.ExportAll; settings.FileLocation = @"C:\ExportPath"; settings.BaseFileName = "Test.cab"; settings.FileCompression = false; settings.ExcludeDependencies = true; settings.CommandLineVerbose = true; settings.ExportObjects.Add(exportObject); SPExport export = new SPExport(settings); export.Run(); Console.WriteLine("Staring Import........."); SPImportSettings impsettings = new SPImportSettings(); impsettings.SiteUrl = spsite.Url; impsettings.WebUrl = destspweb.Url; impsettings.FileLocation = @"C:\ExportTest"; impsettings.FileCompression = false; impsettings.BaseFileName = "Test.cab"; impsettings.CommandLineVerbose = true; impsettings.RetainObjectIdentity = false; SPImport import = new SPImport(impsettings); import.Run(); } @Sudhakar, First off, I've checked your code and it all looks good (don't forget to dispose the SPSite/SPWeb objects you create though!). I'm struggling to think of a reason why you'd get duplicate fields on the list. If I read what you say correctly, your list/content type ends up with 2 fields with exactly the same ID, which I find especially surprising. Are you up-to-date with service packs/content deployment hotfixes? Cheers, Chris. Chris, Looks like my issue of duplicate site columns is a known bug in Microsoft (as clarified by MS escalation engineer). The fix was supposed to be in MOSS Post SP1 Hot Fix - May 2008, but hasnt worked properly. MS plans for a fix Aug end. FYI - More digging revealed that even stsadm export, import has this issue. Even the OOB content types such as Page, Welcome Page, Article Page also have this issue.(Try exporting and importing Press Releases and explore content type in pages lib->doc lib settings) Thanks Hi! Great tool, but I was wondering if there is a way I can tell it to put it's temporary cache somewhere other than the temp folder on C:\Windows? I have a HUGE D:\ but little space on C:\ so I can't use your tool because it runs out of room on C:\ Hey Keith, Yes, you should be able to do this by modifying your TEMP/TMP environment variables. HTH, Chris. Awesome Utility, However I have question, how to migrate Workflows which were designed using Sharepoint Designer and associated to a Form Library. I was able to Import the Form Library but the workflows didn't get migrated. Is there anyway to migrate the custom workflows created using Sharepoint Designer 2007? Thanks Singh Hi Singh, I'm afraid SPD workflows do not get deployed by the underlying SharePoint Content Migration API. At Using the SharePoint Content Deployment Wizard I note: The following content does not get captured by the Content Migration API - alerts, audit trail, change log history, recycle-bin items, workflow tasks/state. Sorry if that's not the answer you were hoping for. Chris. Hi Chris, Great contribution. Dumb question - please explain why we should refrain from using a normal stsadm backup / retsore to move our projects from a dev to production environment. Thanks!. Thanks Chris, Would you suggest backup and restore is also the wrong approach when initially deploying sites to a customers live server, say from a VPC. I.e. we did the work on a VPC and then want to move it live so we ussually just backup and restore it. Backup restore seems to include workflows which is nice. Steve, Yep, there are benefits - I think backup/restore would be the only way to transfer SPD workflows (if that's what you meant). However my recommendation would probably to avoid it for the support reason - if you need to raise a call and MS find this was the deployment method, they might say they cannot offer full support - not sure. Certainly the other deployment methods are more involved, but I feel happier with them. HTH, Chris. Hi Chris, I just tried your tool to export a Publishing portal. I realise you will probably need more information. Attached is the part of the export log with the error. [2008/08/14 11:58:22 AM]: Progress: Exporting Web. [2008/08/14 11:58:22) [2008/08/14 11:58:23 AM]: Progress: Export Completed. [2008/08/14 11:58:23 AM]: Finish Time: 2008/08/14 11:58:23 AM. [2008/08/14 11:58:23 AM]: Completed with 0 warnings. [2008/08/14 11:58:23 AM]: Completed with 1 errors. Sorry Chris, did some homework and realise the error occurs with the native -o export as well. Its due to a missing feature. weird because I havent deployed any new features. I found info on this here: Hi Chris, I'm getting a rather disturbing error message when I attempt to import a list using the Content Deployment Wizard. Here's the scenario: Source Site: Target Web: The task is to copy 2 custom lists each with its own custom content type from the source site to the target web. The export works fine but during the import I get the folowing error message: FatalError: The element 'Fields' in namespace 'urn:deployment-manifest-schema' has invalid child element 'Field' in namespace ''. List of possible elements expected: 'FieldRef, Field' in namespace 'urn:deployment-manifest-schema'. I found a possible related hotfix from Microsoft; unfortunately this didn't fix the issue. Please let me know if you've got any ideas how to resolve the issue. Regards, Raphael. Raphael, Sorry for the delay in replying, I was on holiday when you posted. This issue arises when you're using the Content Deployment API (e.g. with the Wizard) and you also have lookup fields deployed by a Feature. A few people have blogged about this, see Michael Nemtsev's post for information on how to get around the problem. HTH, Chris. Hi Chris i have the following error when using SPDWizard to move entire site collection to different farm and different AD. I have already installed SP1 and infrastructure update. Can you help me what is the problem? I then try to import the cmp file using stsadm import, it was successful but the top navigation node shows error for every sub site. I have checked content and structure, the subsite was there, but it cannot show in the navigation bar. pls help me! thx [9/18/2008 10:09:07 AM]: Progress: Importing List List Template Gallery. [9/18/2008 10:09:12 AM]: Progress: Importing List Master Page Gallery. [9/18/2008 10:09:13() [9/18/2008 10:09:40 AM]: Progress: Import Completed. [9/18/2008 10:09:40 AM]: Finish Time: 9/18/2008 10:09:40 AM. [9/18/2008 10:09:40 AM]: Completed with 2 warnings. [9/18/2008 10:09:40 AM]: Completed with 1 errors. @lifelearner, Are all your content types present on the import site? Looks like one wasn't able to import for some reason - wasn't a content type deployed by a Feature was it? If so, you'd need to install this Feature on the import site. Otherwise, I'd actually be tempted to open a support case with MS, as I can't really see anything logical which would cause this. Sorry I can't be more help.. Chris. Hi Chris, I was hoping to start using your excellent tool, however when I try to access the codeplex home page, it is currently showing the message "This project is not yet published". Do you know if this is a short term issue or whether there is an alternative url available for the download. Many thanks, Robin. Hi Robin, Apologies - the Codeplex project has been unpublished by the adminstrators because I haven't published the source code. Whilst I'm working out what to do about this, suggest leaving another comment with your e-mail address (which I won't publish), and I'll mail you the tool. Sorry about the inconvenience, Codeplex site hopefully back soon. Cheers, Chris. Hi, Looks good does this use STSADM for site collection moves etcetera? Sorry but I forgot to ask if IDs get carried over, unlike DocAve Replicator which breaks lookups and such. Thanks! Hi, When I tried to download the project from the codeplex from the following URL: it says access denied. And asks to login even after logging in I am unable to access the project. @Ben B, The tool uses SharePoint's Content Deployment API which is what STSADM export/import uses underneath, but allows you to set more options and have more control than the standard methods. As an example, there is a checkbox to specify if you wish to retain the existing IDs - so this allows lookups etc. to continue to function. HTH, Chris. @Matharuajay, Sorry for the inconvenience - the Codeplex site is now back up and running! HTH, Chris. Hi Chris! Good work! I'm having an exception when importing: [30/09/2008 19:54:02]: Progress: Importing Role Assignment for Quick Deploy Items. [30/09/2008 19:54:02]: FatalError: User cannot be found. at Microsoft.SharePoint.SPUserCollection.GetByID(Int32 id) at Microsoft.SharePoint.Deployment.WebS() [30/09/2008 19:54:06]: Progress: Import Completed. [30/09/2008 19:54:06]: Finish Time: 30/09/2008 19:54:06. [30/09/2008 19:54:06]: Completed with 8 warnings. [30/09/2008 19:54:06]: Completed with 27 errors. I have deleted all paths and jobs in the source server, just in case, but error persists. Any ideas? Thanks in advanced. Chimo. @Chimo, First off, apologies for the delay in replying. I wonder of your error is due to the settings you selected for the import operation. It seems like your target site has a different set of users (e.g. different domain), but you selected all security information should be imported. Suggest trying the job again with 'include security' to 'None' and 'User info update' to 'ReplaceUserWithSystem'. HTH, Chris. Good tool!! I have a Document library when i export the library with IncludeDescendants, it exports the library with 0 errors. But when i import the file, it gets fail saying different document library not found. In export log it shows importing other libraries(other libraries not present so its getting fail). My Question is : Is there any way to find out the dependencies of document library before exporting so that i can export all of them at a time. Hi, I know this error is due to the underlying Content Deployment API rather than your excellent tool, but I was wondering if you knew of a workaround or a way of solving this problem when running an import (The same error occurs if you use the STSADM import command) [24/11/2008 10:40:28]: FatalError: The formula refers to a column that does not exist. Check the formula for spelling mistakes or change the non-existing column to an existing column. at Microsoft.SharePoint.Library.SPRequest.CallCalcEngine(Int32 operation, String bstrUrl, String bstrListName, String bstrString1, String bstrString2) at Microsoft.SharePoint.SPFieldCalculated.CheckFormulaForTemplate(SPWeb web, XmlDocument xd, XmlElement xroot)() Cheers Hi Chris. I'm trying to export a task list from site A and import into site B. I ran the export and copied the cmp file over. However when I do the import, I get this error. [11/25/2008 10:38:22 AM]: Start Time: 11/25/2008 10:38:22 AM. [11/25/2008 10:38:22 AM]: Progress: Initializing Import. [11/25/2008 10:38:23 AM]: Warning: Import requirement file C:\Documents and Settings\Administrator.BERMUDA\Local Settings\Temp\2bbf21ac-8e13-4512-970b-55262870b369\Requirements.xml was not found no verifications ran. [11/25/2008 10:38:23 AM]: FatalError: Could not find file 'C:\Documents and Settings\Administrator.BERMUDA\Local Settings\Temp\2bbf21ac-8e13-4512-970b-55262870b369() [11/25/2008 10:38:23 AM]: Progress: Import Completed. [11/25/2008 10:38:23 AM]: Finish Time: 11/25/2008 10:38:23 AM. [11/25/2008 10:38:23 AM]: Completed with 1 warnings. [11/25/2008 10:38:23 AM]: Completed with 1 errors. I'm also unclear when doing the import if I need to fill in the Import web URL field. It seems optional. Thanks. can this tool backup a subweb and restore it to a site collection? i hear there are issues doing this with stsadm. @Shobha, Unfortunately I'm not aware of any easy ways to find dependencies of a document library. However, if another library really is a dependent, I'd expect leaving 'Exclude dependencies of selected objects' unchecked should ensure the other objects also get included in the packge. This should then import fine. HTH, Chris. @Anonymous, It looks like the account you're running the Wizard as doesn't have permissions to read/write to the administrator's 'My documents' folder. Files in the .cmp package are likely unzipped to here as part of the import process. Suggest running the Wizard under an account which has NTFS permissions as well as permissions in the SharePoint db (or, amend the NTFS permissions). HTH, Chris. @Anonymous, Yes, the Wizard can be used to deploy a subweb as you describe. HTH, Chris. We are running MOSS 2007 with multiple load balanced WFE servers. Does this need to be installed on every web server? Thanks @Johanna, No - since when you import you are effectively updating data in SharePoint's SQL database, which is separate from your WFEs. Hence you can just nominate one WFE and install the Wizard there. That said, nothing stopping you having it on all your WFEs for convenience though, it really doesn't matter. HTH, Chris. Hi Chris, I am trying to migrate a Blog list, Comments list and Categories list to a Team site but I am getting an error "Invalid List Template" when ever im importing the list to the site. Is it possible to migrate a Blog site to a Team site? @MOSSkeeter, No, migration using the Wizard (or Content Deployment in general) needs be like for like in terms of the site template/definition used. HTH, Chris. Hi Chris, Thanks for the last reply! I got another question though, you mention that alerts will not be included in the export/import using the tool. I was just wondering if you have any idea in any way on how to migrate the alerts to another site? Thanks! @MOSSkeeter, You need to write code to do this - something like iterating through the alerts for the source site, writing them out to an XML file, then adding those alerts to the target site. Now that you come to mention it, I think I might have written something to do this once - could maybe help you get started. If you're interested, leave me another comment with your e-mail address (which I won't publish), and I'll dig it out and send it through. HTH, Chris. I am facing a unique problem. ---------------- Current Scenario ---------------- 1) There are sites built out of OOB MOSS Site definitions. 2) Custom Site templates were created and few sites were based out of them Today all such site templates have been deleted. Sites based out of it are still working as site templates are connected to the site definition & those site definitions (OOB) are still in place **To prevent errors, Two New Custom Site Definitions were created. All newly created sites are based out of either of these custom site definitions & have no problem. NOW CLIENT Wants to move existing sites built out of OOB site definition & the deleted custom site templates to be migrated to the 2 newly created custom site definition. Q1) I am trying to change a site's association with its site definition through code so that it points to new site definition(Corrected one with extra features) Q2) same question for site template scenario? Q3) If i use steps for changing site's association with site definition as mentioned then i am not able to migrate CUSTOM CONTENT TYPES but the sites association changes. NOw We have custom applications which refer to the custom content types through code! Is it possible to migrate custom content type preserving its GUID? ***Alerts, workflow states are lost when we use export import, can you please send me the code for migrating it. I guess you have it. Thanks a lot in advance Hi, Could this tool be used to migrate from WSS to MOSS 2007 ? Many Thanks Steve Hi, this tool gives me hope! I am trying to export files from one document library to another one (same web site). The export went OK. However, I got this error on the import. [2/17/2009 4:04:13 PM]: Start Time: 2/17/2009 4:04:13 PM. [2/17/2009 4:04:13 PM]: Progress: Initializing Import. [2/17/2009 4:04:14 PM]: Progress: Starting content import. [2/17/2009 4:04:14 PM]: Progress: De-Serializing Objects to Database. [2/17/2009 4:04:14 PM]: Progress: Importing Folder /Shared Documents/Forms/Document. [2/17/2009 4:04:14() [2/17/2009 4:04:14 PM]: Progress: Import Completed. [2/17/2009 4:04:14 PM]: Finish Time: 2/17/2009 4:04:14 PM. [2/17/2009 4:04:14 PM]: Completed with 0 warnings. [2/17/2009 4:04:14 PM]: Completed with 1 errors. Note: On the Bind to site, I put for both Site URL and Import web URL. Any help would be greatly appreciated! Hi Shirley, You don't need to use as the import web URL in this case. This is because the web that you are importing to is actually the root web of your site - the import process itself should be smart enough to work out that these are docs from the 'SharedDocs' library and need to be imported there. If modifying this doesn't change anything, it could be because you're not up-to-date on SP1 and/or cumulative updates - these make a difference when doing Content Deployment. See Content Deployment and Object Reference Not Set to an Instance for example. HTH, Chris. Thank you Chris for your quick response. I have not updated SP to SP1 yet. I will try your suggestion to see if it works for me. (I am new with this SharePoint world. I am taking baby steps with everything.) Thanks again! Shirley Shirley, You and I are in the same on SP1. I planned to do it this Sunday, but our change control committee nixed the plan. I'm rescheduled for March 7 weekend. If you want the information Microsoft sent me and an example of the batch files I will use, I can send you the information. Depending how your farm is setup, this may help you. My goal is to install SP1 and the December releases. Microsoft told me that SharePoint is not supported with out SP1 now. I'm pretty cautious w/ SharePoint as I have heard some pretty rotten stories from other admins. @Steve, Sorry for the delayed response. I've not specifically tested, but you should be able to move content from a WSS environment to MOSS without any issues whatsoever. Let me know if you find otherwise and I'll try to help. Thanks, Chris. @Peace, Sorry for the delay in responding to your comment. I'm afraid I haven't tried changing the site definition of an existing site - despite the article you point to, I still didn't think it was fully supported so I'm not entirely surprised you have run into issues. My recommendation would be to make changes to your existing sites another way (e.g. through additional Features, changes using API etc.). I'll send you the code I have to migrate alerts (unfortunately I now find it only writes out the details rather than doing a full migration, but if you need a full migration it should serve well as the starting point for you). Cheers, Chris. Chris, I have sort of a strange predicament. We have a MOSS site on a server that belongs to a different department. We need to move the content from that site to our server which only has WSS 3.0. Do you think your tool would work for our situation? Thanks in advance! @Mike S, I think it depends on what content you're moving - if you are moving documents and list items, you should be fine. If however, you're moving publishing pages, of course this is MOSS functionality so would not import to a WSS-only environment. The tool does support both WSS and MOSS, so I think it should come down to your content. HTH, Chris. Chris, The site only contains documents and lists, so I'm going to give it a try. I'll let you know how it goes. One other thing I forgot to mention is that the MOSS server is 32 bit and the WSS server is 64 bit. Will your tool work on 64 bit machines? Thanks again, Mike @Mike S, Yes it does, no worries there. Cheers, Chris. Hi Chris Good tool. When i was trying to export a site it is working fine and while importing it is saying the ioperation completed successfully but i am not able to see the result in the destination. Am i doing something wrong. would you help me? @Vinay, If the Wizard and the import log are reporting that the import was successful, this often means your content has imported to a different location in the hierarchy to where you are looking (perhaps because you aren't clear on the effect your settings will have). Suggest examining your entire site structure to look for the imported content. HTH, Chris. Chris, I tried exporting the content from the MOSS site to the WSS site. When I try to import, I get an error: Could not find Feature OffWFCommon. I'm guessing that has to do with a MOSS feature. Any ideas on how to get around that? Thanks! @Mike S, Aargh, I should have thought of this - what's happening here is that SharePoint's Content Deployment API is trying to ensure you have the same functionality in both source and target so the content will work in both places. Clearly this isn't the case for you because you're going for WSS -> MOSS, but the content you're moving probably doesn't use any MOSS functionality (I'm hoping). Unfortunately there is no way to disable this check - it's a fundamental part of the CD model. Really sorry Mike, I don't have any ideas to work around it using the Wizard - you'll need to use some other tool to move the content (Quest, Echo, AvePoint etc..) We can conclude then that it's not possible to go from MOSS -> WSS using the Wizard. Hope you get sorted. Cheers, Chris. Hei Chris, I've successfully migrated a large SP 2003 site to SP 2007. My problem now is I'd like to get rid of all the custom stuff, site/list definitions and revert to plain old MOSS document libraries. Simply put, I'd like to move the content(file/folders) from the customized doclibs to default MOSS doclibs - all within the same site collection. Is this possible using your wizard? I am migrating a site from MOSS to MOSS. I am facing strange error during stsadm import of a site. We are currently on December cumulative updates. I saw one of your blogs to install jan31,08 hotfix. 1) I did that as well but doesn't help. 2) Checked Features on source as well as destination. Everything is present & activated in the destination. Still import fails. Please HELP! Below is the error: [3/21/2009 4:48:50 PM]: Progress: Importing Role Assignment for en-us/About. [3/21/2009 4:49:05 PM]: FatalError: The given key was not present in the dictionary. at System.ThrowHelper.ThrowKeyNotFoundException() at System.Collections.Generic.Dictionary`2.get_Item(TKey key) at Microsoft.SharePoint.Deployment.ImportObjectManager.GetMappedRole(SPWeb web, Int32 ridIn, Int32& ridOut) at Microsoft.SharePoint.Deployment.RoleAssignmentsImport.ProcessComplexElement(ImportStreamingContext context, XmlReader xr, SqlSession session) at Microsoft.SharePoint.Deployment.SqlBatchImport.Run()/21/2009 4:49:05 PM]: Progress: Import Completed. [3/21/2009 4:49:05 PM]: Finish Time: 3/21/2009 4:49:05 PM. [3/21/2009 4:49:05 PM]: Completed with 13 warnings. [3/21/2009 4:49:05 PM]: Completed with 1 errors. @Roger, Unfortunately I don't think this would work - the Content Deployment API which the Wizard is based on is all about replicating from a source location to a destination. So what's likely to happen is that the customizations get added to your destination lists, which doesn't sound like what you're looking for. I think you'd need a fairly sophisticated migration tool to do something like this - something which would allow you to define mappings between old columns and new. I've not used either, but I think Metalogix and Tzunami Deployer could be options for you. Best of luck, Chris. @Peace, OK, have given this some thought and a couple of things spring to mind. If you have SP1/IU/Cumulative Updates up to December, then I'm wondering if this is a data issue - perhaps something along the lines of a user/group being deleted and the Content Deployment API failing to deal with this correctly. My suggestion would be to try importing the content without the security information. If you're using the Wizard you can do this by ensuring the 'Include Security' checkbox is not cleared on import. If you're using STSADM import, you should not specify the -includeusersecurity switch. If this succeeds, you've isolated the problem to the permissions data. From there you might be able to further identify the source, perhaps by splitting the export/import into smaller chunks. HTH, Chris. Hey Chris We are currently facing a scenario where we need to move content between two different sites. To put it in a brief detail: 1. We have two sites SITEA and SITEB with independent Content Type CONTA and CONTB. 2. We need to move content between these two sites from CONTA to CONTB. Would it be possible to do this using the Content Deployment wizard? Thank for your help, Great tool by the way, has helped us a lot previously. I can't thank you enough for developing this Deployment tool. You have made my life a lot easier. :) Please keep up the good work. Thanks...and thanks a bunch! Just to update! I have upgraded my servers to SP1 (3 wees ago) without any problem. @Sumant, Sorry for the delay in getting to your comment, I've been completely snowed under. If I understand correctly, yes this should be entirely fine with the Wizard. What will happen is that if any content types required will also be imported with the data. However, if this ISN'T what you want to happen (e.g. you want to change the content type) - this isn't what will happen I'm afraid as this isn't how the underlying Content Migration API works. HTH, Chris. Chris I have a question which you might be able to shed some light on. I have three MOSS 2007 farms 1. Staging 2. Live 3. DR I have Content Deployment setup between the farms to replicate the content from Staging to Live and DR. I now want to give access to a user so that he can Run the content deployment jobs himself but not have access to any other part of the Central Management page. I have thought about creating a script to do the content deployment and giving access to the user to that script. But it seems that stsadm.exe hasnt got anything for content deployment. I have also tried to play with the site permissions of the central admin site but have been unsucessful. Is this something I can setup with your tool or could you guide me in setting up correct permissions? Your help would be much appreciated. Regards Ad I'm using the deployment wizard to import a list between sites in two site collections. I keep getting the following error. Any ideas? Thanks! FatalError: The file Lists/Issues cannot be imported because its parent web /teamsite/parking() Chris, I'm trying to determine how to use your tool to migrate a MOSS 2007 blog with the Comments, Categories, Posts. I didn't understand your response from 23 January 2009 about the "like for like for the template/definition". In any case I tried to just export each List Item from the Categories, Posts, and Comments lists and re-import (with re-parenting) and this sort of works. But the relationship between the list items in the three lists are lost during the import. Do you have any recommendations on how to migrate a blog? Is your tool only useful for simple document libraries and lists that do not have these inter-relations like in a blog? @Ad, Yes, I think you could conveivably use my tool for this. If you've seen Command-line support for Content Deployment Wizard you might be able to use this support to get there. My thoughts would be around creating special admin for your user, and this page would start a process which would call my STSADM command with an appropriate XML file for the content you wish the user to be able to deploy. Hope that gives you some ideas, ping me again if you need more help. Cheers, Chris. @A.G., Generally this error will occur because you are importing the list to another parent web (known as re-parenting) and have the 'Retain object IDs and locations' box checked. In this scenario you should uncheck this box (since you are changing the location of the list, so it needs to be assigned a new ID) and ensure you have the correct parent web URL in the 'Import web URL' on the first screen. Hope that helps. Get in touch again if you're still struggling. Cheers, Chris. @Peter, If you're importing lists which have relationships you should try to ensure the lists are being deployed in the same package. This allows the import process to recognise and recreate the relationships on the target. I've not specifically tested deploying a blog site but don't think I'd anticipate any issues if done right. Suggest trying to grab all 3 lists in one package and then importing - that would be my recommendation. My comment on 23rd Jan to MOSSkeeter was because I thought he/she might be trying to move an entire site from one site type to another (blog site -> team site). Moving just the lists however, should be fine. Might need to ensure any list templates used by the blog site are available though - this might require the activation of whichever Feature defines these list templates. Hope that makes sense. Cheers, Chris. P.S. Hi, I would like to move documents between two doc libs and maintain the version history of document and corresponding metadata. I managed to move a doc lib with it's entire content and also to move a a doc lib cherry picking only one of the containing documents. Is it possible to move documents between doc libs without affecting the version history? Regards /Magnus @Magnus, Yes, it is possible to deploy files whilst maintaining metadata and version history. To do this, you should: - select 'All versions' for the 'Include versions' setting when exporting files - select 'Overwrite' for the 'Version options' setting when importing files HTH, Chris. Hello Chris, i try to copy list with the tool but i get this exception. Any idea how to resolve this one? Error: List AX 2009 Feedback could not be imported because it uses the IssueTracking base template and the destination uses the GenericList base template. Chris, I want to provide an update to my comment on April 24th about migration of a blog site. I tried again by using your tool for the entire blog site including the dependencies. The import worked and maintained the relationship between the various list items in Posts, Comments, and Categories. Since this is working I have not tried to export the individual lists or list items, which isn't a likely scenario that I will need. For the blog site import I did have a problem accessing the site afterwards and it gave me a "File Not Found". I think this has more to do with a branding issue in my original site. I fixed this by adding '/_layouts/settings.aspx' to access the site settings page and then setting the master page back to a default.master. I also re-inherited the permissions from the parent and will clean this up manually. But overall the blog site migration worked well with your tool. Thanks! @Jonam, It sounds like you're trying to import to an existing list but that list was created with a different template. This won't work unfortunately - the underlying template needs to be the same one. My suggestion would be to not create the list in the target environment if possible - 'create' it there by deploying it using the Wizard. If you do need it created before the first Wizard deployment, ensure it's created from the same template. HTH, Chris. @Peter, Thanks for following up - glad you got sorted. Tend to agree with your thoughts that the 'File not found' more likely to be a branding issue that. Also, permissions should be migrated successfully if you select the 'Include security' option on export and import? If you run into any other oddities with blog sites (or anything really), be interested to hear. Thanks again for the comment. Cheers! Chris. Thanks for your reply, however I'm not sure I expressed myself correctly, or highly possible I've missed something. I give it a second try. What I would like to do is to move one file (or a folder with several docs) from doc lib A to doc lib B. The doc libs A and B have nothing in common except having the same set of columns an house the same set of content types (to secure that tranferred metadata have a proper target). When trying to export a file (or a folder) I recieve an error message whereas selecting a doc lib works fine. It seems to me that a file needs it's parent doc lib to store information and can only be moved together with it's parent or to a doc lib previously copied. Is there a trick that I've missed? A comment to your answear, why is it important to have overwrite upon import, the file has never seen the target doc lib... Regards /Magnus @Magnus, Right, sorry I didn't understand some of the subtleties of what you're trying to do first time round. Trying to maintain the metadata across different doc libs with 'same named' columns is a scenario I've not actually tested I think. I think the issue here could be that the content types will always have different IDs (since the list content ID will definitely be different) - however, it could be that it falls back and uses the column name (suggest internal name first), so you might be in luck. However, in all this I would export any problem to occur on import, not export. Export should be fine. What error are you seeing on export? Cheers, Chris. Hi, I've had issues before with not having the server account to be SharePoint administrator but have sorted that out, some of my error messages in the past can have been related to this. I made an export/ import of a single file and yes it's at the export the error occurs. I've cut'n pasted the whole log-file [2009-05-11 11:49:05]: Start Time: 2009-05-11 11:49:05. [2009-05-11 11:49:05]: Progress: Initializing Import. [2009-05-11 11:49:06]: Progress: Starting content import. [2009-05-11 11:49:06]: Progress: De-Serializing Objects to Database. [2009-05-11 11:49:06]: Progress: Importing Folder /Documents/Forms/Document. [2009-05-11 11:49-11 11:49:06]: Progress: Import Completed. [2009-05-11 11:49:06]: Finish Time: 2009-05-11 11:49:06. [2009-05-11 11:49:06]: Completed with 0 warnings. [2009-05-11 11:49:06]: Completed with 1 errors. To secure no other issues with permissions I exported the same single file but within the context of the parent doc lib and that worked well. So the question still is can you move a single file between two doc libs? Regards /Magnus Hi Chris, Thanks for this tool, I have been appointed to test this tool out on our test-site. I have created an export of the full site colletion with all content etc. And then set it to start. I have one question though, does the tool take into concideration of the estimated size of the cmp-file and the actual available disc-space on the selected export-location? And maybe just a newbie-question, but does it export to a file the same size as the Content-db? This is the nature of my first question as the content-db currently is at an astounishing 181 GB and growing fast, while the server I am exporting the sitecollection to has only 12 GB free ;o) So far it has not errored out, and is starting to consume free space slowly. Now I wonder what happens when this VM testserver runs out of space? ;o) BR Morten @Magnus, OK now I'm really confused! You say you get the error on export but the log you pasted is from the import operation! I think I'm coming to the conclusion though that you need more than columns just having the same 'names' for metadata to be transferred successfully. Most likely the columns would need to have the same IDs, which would be accomplished if the lists were based on the same list template or used the same site columns etc. Does that make sense? Thanks, Chris. @Morten, No the tool doesn't do any "pre-flight" check for disk space - I'd expect it to fail during the operation when space runs out. In the export process things do get compressed, but I'm not sure what ratio you can expect - this is down to the underlying SharePoint content migration API and I haven't seen MS release such figures. One other thing that might be relevant here - when importing, extra disk space is required so the data can be "unpacked" prior to the actual import. Hence if you're importing say 100MB of data (and let's say SQL is hosted on the same box), you need way more than this free for the import to succeed. HTH, Chris. Hi again, Sorry for my last post, I didn't write that one very clear. It's the import that is the problem. Most of my doc libs are created from the same list template. However for trouble shooting I made a new export/ import of a folder. I made the import to a doc lib that I recently moved (through export/ import with your wizard) from site A to site B. This should secure that the column definitions are the same. However import failed again. The error log is pasted below, note that the "Fatal error" is not the same as in the last post. [2009-05-15 08:29:26]: Start Time: 2009-05-15 08:29:26. [2009-05-15 08:29:26]: Progress: Initializing Import. [2009-05-15 08:29:27]: Progress: Starting content import. [2009-05-15 08:29:27]: Progress: De-Serializing Objects to Database. [2009-05-15 08:29:28]: Progress: Importing Folder /electro/Development/Energizer. [2009-05-15 08:29:28]:.FolderSerializer.GetFolderUrl(Guid folderId, String folderUrl, Guid folderParentId, Guid listId, SPWeb parentWeb, ImportObjectManager objectManager, Boolean checkTargetUrl) at Microsoft.SharePoint.Deployment.FolderSerializer.GetFolderUrl(Guid folderId, String folderUrl, Guid folderParentId, Guid listId, SPWeb parentWeb, ImportObjectManager objectManager) at Microsoft.SharePoint.Deployment.FolderSerializer.Get-15 08:29:28]: Progress: Import Completed. [2009-05-15 08:29:28]: Finish Time: 2009-05-15 08:29:28. [2009-05-15 08:29:28]: Completed with 0 warnings. [2009-05-15 08:29:28]: Completed with 1 errors. As for trouble shooting I also export one single file from a doc lib, deleted the file in the source doc lib and then finally imported the file back into the source doc lib. This also failed! So the issue is something else than column definitions. Checked the error log and I saw that the string with "importing folder" the doc lib was repeated twice in the path. I then changed my "Import web URL" to and the import succeded! I made the same with the folder that generated the error log above and again success (however in that error log the doc lib was not repeated twice in the import path...)! As I have wanted to move my files and folders from doc lib A to doc lib B I have assumed that the way to do this is through the "Import web URL" but this seems to be the failing part. I change my question; To import a file to a doc lib (target) with another name than the source doc lib, do I state this in the "Import wb URL"? Thanks for your patience, hope we sort this out! Regards /Magnus @Magnus, OK maybe we're getting somewhere. Let me explain what the 'Import web URL' is used for and hopefully you can apply the information to what you're trying to do. The 'Import web URL' is only required when you are changing the location within the site collection of where the list lives. So think about it like this: - deploying list from farm A to farm B, list stays in same location in hierarchy: 'Import web URL' required = no - deploying list from farm A to farm B, list changes place in hierarchy: 'Import web URL' required = yes - deploying list within same farm, list changes place in hierarchy: 'Import web URL' required = yes Does that help at all? It might explain the error if you're not using this value as SharePoint expects. Thanks, Chris. Hi, I hope we're getting closer... As I want to move one single document or a folder from doc lib A to doc lib B (within or between sites) I guess ShP thinks this as a restructuring of the hierarchy and I need to use the Import URL field. To indicate the target doc lib, do I use the Import URL "" or how do I do? Regards /Magnus Hi Chris! Great tool! I was able to make it work in my DEV environment (it's a VM actually), but I'm having trouble in the production environment. The tool won't even run at all, after running the .exe file I get a "SPContentDeploymentWizard has encountered a problem and needs to close. We are sorry for any inconvenience." If I click the "Debug" button VS.NET comes up and I see a "NullReferenceException was unhandled" window - in the Troubleshooting tips reads "Use the new keyword to create an object instance." I probably need to download the source code and debug further, but I first wanted to check if this is a know issue. FYI: the user ID I'm using in the prod server is the moss ID. Does your wizard handle workflow list association? These workflows have no tasks, none would be in progress, they are all custom deployed features from VS2008 and the deployment would be from web to web on the same server at the same level in the root site collection heirarchy. I'm simply considering using it as a way to copy a site right next door. SITE0 begets SITE1 SITE2 ... SITEn where.. SITE0 is the web with the base content, structure, permissions and workflow feature list associations that all webs from SITE1 -> SITEn would be based on. A simple site template maintains the workflow association but will not maintain list level permissions. A Share Point Designer .cpm file will not maintain the workflow association but it will maintains list level permissions. I believe I read the deployment api does support workflow just that it can't keep all the workflow running or related things linked. Which makes sense because on export they may not be hydrated or even persisted. Hi again Chris, I guess I have found the answear at you blogg,, from 14 december 2007. I've read this and the introduction many times but this morning I understood what's written... It's not possible to reparent a document to another document library which is what I would like to do. And this is written in the third and second to last sections. Best regards and again thank's for you patience trying to help me. /Magnus @RobertT, I think you might be running into a permissions issue in production - try doing a right-click, then 'Run as...' and enter the credentials of the farm admin user to test this. Thanks, Chris. @John Sitka, I don't think workflow associations are retained (I thought these were also outside the scope of the content deployment API), but I actually don't recall if I ever tested this scenario. If you have time, I'd suggest setting up a quick test - sorry I don't have the answer off the top of my head.. Chris. @Magnus, Ah, yes you're right I'm afraid. Having gone back to read what I wrote in When to use the SharePoint Content Deployment Wizard in Dec 2007 I now remember the deal with this type of operation. Yes, it really isn't supported at the moment I'm afraid - I guess the Wizard code could be amended to deal with this (needs code similar to Stefan's 2nd sample in 'Method 2 - assign an individual parent to each orphaned object' section at), however I just don't have the bandwidth to take this on at the moment I'm afraid :-( Really sorry I wasn't able to help you reach this conlusion earlier Magnus, but I guess at least we got an answer in the end - just not the one we were hoping for. All the best, Chris. Hi, i m trying to import from a share point site..the exports works just fine..but while importing it gves the following error FatalError: Could not find WebTemplate #15 with LCID 1033 both the machines are running the same version of moss and and enterprise edition respectively.. @sumitD, I think you're getting this error because of a difference in the 12 hive of your 2 environments, specifically your onet.xml file. Suggest checking for differences between the source and target environment. HTH, Chris. Hi Chris... Can I use the same export file to import to another environment. Can I retract the deployed cmp file in a server like in using wsp deployment? Hi! I've found a solution for the reported issue (regarding GatWeb.SharePoint.EventsManager): Just download and install the events manager feature: Once this feature is installed and deployed on the targetserver, the Conten Deployment Wizard works OK. Thanks again!!! @JR, Good stuff, great to see you worked it out. Chris. P.S. Have just accidentally deleted your original comment whilst publishing this one - sorry about that! @Anonymous, In answer to your questions: 1. Yes, you can use the export file to import to another environment - that's what the Wizard is for. 2. Unfortunately you cannot retract a .cmp file, SharePoint does not support this. You should take a backup before importing so that you can rollback if needed. HTH, Chris. Hi, is that anyway i can export user information list from 1 top level site to another top level site? Thanks Hi Chris, Its a nice tool to workwith, I used it for quite a few projects. I have a quick query on this. My Problem is as below Source Site: Target Site: Is it possible to import data from Source Site to Target site which are not having same site structure. Appreciate your quick response. Thanks, Dhawal @Dhawal, It depends what you mean - it is possible to "re-parent" a site when importing, so that site and all it's contents move to a different place in the hierarchy on the import environment. So in your case, you can take the "XYZ" site and import it to a different place in the hierarchy such as. Otherwise if you wanted to deploy old "XYZ" to new "XYZ", where new "XYZ" has a completely different structure, this won't work as the deployment process won't be able to match up the items. Hope that makes sense. Thanks, Chris. Chris, Thanks a lot for your prompt response :) Yes it surly help me, thanks again -Dhawal Hi, While importing throwing an exception: [8/5/2009 3:07:34 PM]: Start Time: 8/5/2009 3:07:34 PM. [8/5/2009 3:07:34 PM]: Progress: Initializing Import. [8/5/2009 3:08:01 PM]: Progress: Starting content import. [8/5/2009 3:08:01 PM]: Progress: De-Serializing Objects to Database. [8/5/2009 3:08:01() if any one have an idea about this,reply me.Thanks @Anonymous, My guess would be that you're trying to import to an environment which is using a different schema - possibly because it's at a different patch level. Suggest checking the level of your export and import environments. HTH, Chris. I have created one site with subsite called Test[Team site],exported using tool and after that i have created one more site with subsite called Test[Blank site],trying to import using tool,throwing following exception.My environment is MOSS2007 with SP1. Error: An error occured while running the import.the import log file will now be opened. Exception details: System.IO.IOException:The process cannot access the file 'Manifest.xml' because it is beling used by another process. Note pad is opening with the following error: [8/6/2009 4:47:32 PM]: Progress: Initializing Import. [8/6/2009 4:47:36 PM]: Progress: Starting content import. [8/6/2009 4:47:36 PM]: Progress: De-Serializing Objects to Database. [8/6/2009 4:47:36() Please give suggetions on same. Hi, I am trying to import .cmp file,following error is showing: [8/6/2009 6:20:26 PM]: Start Time: 8/6/2009 6:20:26 PM. [8/6/2009 6:20:26 PM]: Progress: Initializing Import. [8/6/2009 6:20:27 PM]: Warning: Import requirement file C:\Documents and Settings\Administrator\Local Settings\Temp\23970679-cfc9-47b7-81f2-6586908846b4\Requirements.xml was not found no verifications ran. [8/6/2009 6:20:27 PM]: FatalError: Could not find file 'C:\Documents and Settings\Administrator\Local Settings\Temp\23970679-cfc9-47b7-81f2-6586908846b/6/2009 6:20:27 PM]: Progress: Import Completed. [8/6/2009 6:20:27 PM]: Finish Time: 8/6/2009 6:20:27 PM. [8/6/2009 6:20:27 PM]: Completed with 1 warnings. [8/6/2009 6:20:27 PM]: Completed with 1 errors. Thanks. Hi, I am trying to import .cmp file,while importing following error is throwing,import and export environments have the same versions,12.0.0.6510] [8/10/2009 5:30:46 PM]: Start Time: 8/10/2009 5:30:46 PM. [8/10/2009 5:30:46 PM]: Progress: Initializing Import. [8/10/2009 5:30:46 PM]: Warning: Import requirement file C:\Documents and Settings\testadmin\Local Settings\Temp\f3d2ff63-9c17-427c-9694-db89b84e5666\Requirements.xml was not found no verifications ran. [8/10/2009 5:30:46 PM]: FatalError: Could not find file 'C:\Documents and Settings\testadmin\Local Settings\Temp\f3d2ff63-9c17-427c-9694-db89b84e5666 5:30:46 PM]: Progress: Import Completed. [8/10/2009 5:30:46 PM]: Finish Time: 8/10/2009 5:30:46 PM. [8/10/2009 5:30:46 PM]: Completed with 1 warnings. [8/10/2009 5:30:46 PM]: Completed with 1 errors. [8/10/2009 6:47:03 PM]: Start Time: 8/10/2009 6:47:03 PM. [8/10/2009 6:47:03 PM]: Progress: Initializing Import. [8/10/2009 6:47:04 PM]: Warning: Import requirement file C:\Documents and Settings\testadmin\Local Settings\Temp\6b295654-b671-4188-a3d6-7eefc416a906\Requirements.xml was not found no verifications ran. [8/10/2009 6:47:04 PM]: FatalError: Could not find file 'C:\Documents and Settings\testadmin\Local Settings\Temp\6b295654-b671-4188-a3d6-7eefc416a906 6:47:04 PM]: Progress: Import Completed. [8/10/2009 6:47:04 PM]: Finish Time: 8/10/2009 6:47:04 PM. [8/10/2009 6:47:04 PM]: Completed with 1 warnings. [8/10/2009 6:47:04 PM]: Completed with 1 errors. Please give suggestions on the same Great program. Thanks ! Chris, This is a great tool. Thanks for creating it. I have a question. We used it today to import content and checked off the import of security. However, in the destination site we saw that the groups of users from the source site were not transfered. Is it that we did something wrong or this is a known limitation ? Thanks Zeev @Zeev, Migration of security groups should work if: - "Include security" is selected on export - "Include security" is selected on import If you find that isn't the case, let me know. Thanks, Chris. I have been using a previous version of the Wizards to do full export/import without issues, works great in fact. So I downloaded 2.7 to try the incremental export of a site/web. I am getting the "Unable to perform incremental export - the Wizard did not find a stored change token for the largest object you have selected to export. This could be because a full export for the site has not yet been performed using this version of the Wizard". So I run the full export, then go back and try again with all the same settings but using the ExportChanges option selected, and the same message appears (and ExportAll gets selected). Is there something I am missing in getting the incremental export to work? @David Perry, Hmm, that might be the second report I've had of this, indicating it could be a bug. Aside from trying closing/re-opening the Wizard, I'm not sure what to suggest. I'll make a note to go in and look, though I am wondering how it got through my testing. I'll do my best to look as soon as I can, though it might be little while unfortunately, I'm just flat out with other commitments right now. Sorry for the inconvenience David :-| Chris. I am very much impressed by this application. It helped me a lot.. Thanks Chris O'Brien nice work.. I love you for this tool Chris! I want to bear your children. Wait...I'm a guy. Well still, if I could... ;) I was able to move a WSS 3.0 document library from one site to another whilst retaining the dates & usernames. It took me hours of searching to find your program and 30 minutes to install and move the content. THANK YOU! @Anonymous, LOL! Glad you found it useful. Always great to hear good feedback, thanks for posting :) Chris. I am trying to move team discussion from a subsite to a root site. I think I tried all settings variations but still no luck. I always end up with some error when trying to import. Here is one: ================================ [11/13/2009 9:48:52 AM]: Start Time: 11/13/2009 9:48:52 AM. [11/13/2009 9:48:52 AM]: Progress: Initializing Import. [11/13/2009 9:48:56 AM]: Progress: Starting content import. [11/13/2009 9:48:56 AM]:() [11/13/2009 9:48:56 AM]: Progress: Import Completed. [11/13/2009 9:48:56 AM]: Finish Time: 11/13/2009 9:48:56 AM. [11/13/2009 9:48:56 AM]: Completed with 0 warnings. [11/13/2009 9:48:56 AM]: Completed with 1 errors. ================================ Any idea what I am doing wrong? Thanks @OPCadmin, What's happening here is that the SharePoint Content Deployment feature is returning an error, but my tool is not reporting it correctly. This is due to a recently-confirmed bug in version 2.7 beta. If you use an earlier version (e.g. 2.6), you'll at least see the real error which might help you resolve things. Otherwise, looking in the log file which gets saved might also be useful. HTH, Chris. Hi Chris, Great tool. I am facng a similar issue as opcadmin. I tried doing an import using the 2.7 beta but it failed with a message "[12/12/2009 4:40:03 PM]: FatalError: Object reference not set to an instance of an object. at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)" So i downloaded the old version 1.1 and i am doing an import using the version 1.1. It seems to be working fine for me. I will still prefer 1.1 over 2.7 @Anonymous, Yes, version 2.7 has a bug which means that if any error happens it gets reported as the message you describe. Any version before 2.7 (e.g. 2.6) does not have this bug - I'll hopefully be able to resolve it soon. Sorry for the inconvenience. Thanks, Chris. Chris, I posted some fixes on the issues list on the codeplex site. I've since started maintaining my own private version for myself, including not only those fixes, but also a browser to select the site, more feedback, and just now I also persisted the temp path. Are you interested in any of these improvements? (I didn't get any comments on my Issues posting at the codeplex site, so I figured it is maybe not maintained.) @Amores, Sorry - I don't seem to always get notifications from the Codeplex site. Sure I'd like to see your changes - if you post another comment with your e-mail address, I'll mail you so you can send it through. Thanks! Chris. Hi Chris, We are trying to move content from one farm to another. We do not have access to the Source farm from the Destination farm. We are not able to run successful imports in this scenario. Is this something that your tool is capable of? or are we trying to do something that your tool is not design to do... thanks in advance! David @David, Yes, my tool should help you here. You can run the export on the source machine, then assuming you can get the resulting .cmp file(s) to the destination machine somehow, you'll then be able to import them there. The Wizard does need to be installed on both source and destination though. HTH, Chris. Dear Chris, We are getting the following error: System.IO.FileNotFoundException: Could not find file 'D:\TEMP\3\8304690e-etc....\ExportSettings.xml The error comes when we try to import a .cmp file. All users have permissions to d:\Temp and it seems to create the 3 directory, but the long filename doesn't exist. Thanks, David Here is the full error from the log file: [05/02/2010 14:20:32]: FatalError: Could not find file 'D:\TEMP\3\cba2f7fa-d60c-451b-831e-4f743ba0910() [05/02/2010 14:20:32]: Progress: Import Completed. Thanks, David @David, Hmm, haven't seen anything like that I'm afraid. The .cmp file would be extracted to the temp directory, and it seems like that file is not there. - Does this happen for all imports? - Is there a problem with a specific .cmp file? - Does the disk where the temp directory is have enough free disk space? Thanks, Chris. Hi Chris, The tool seems great, I exported the entire site from server A, sent the file to server B. Try to import on server B and get the following error: The 'ASPXPageIndexMode' attribute is not declared. Have any idea? Thanks, GG @Anonymous, I did some research on this and the most likely cause seems to be that the source and destination are at different patch levels. See the following: HTH, Chris. I've upgraded my import site to the same version as the export one. But still have the error. here is the detail: [2010-02-18 11:32:00]: FatalError: The 'ASPXPageIndexMode' attribute is not declared. at System.Xml.Schema.XmlSchemaValidator.SendValidationEvent(XmlSchemaValidationException e, XmlSeverityType severity) at System.Xml.Schema.XmlSchemaValidator.SendValidationEvent(String code, String arg) at System.Xml.Schema.XmlSchemaValidator.ValidateAttribute(String lName, String ns, XmlValueGetter attributeValueGetter, String attributeStringValue, XmlSchemaInfo schemaInfo) at System.Xml.Schema.XmlSchemaValidator.ValidateAttribute(String localName, String namespaceUri, XmlValueGetter attributeValue, XmlSchemaInfo schemaInfo) at System.Xml.XsdValidatingReader.ValidateAttributes() at System.Xml.XsdValidatingReader.ProcessElementEvent() at System.Xml.XsdValidatingReader.ProcessReaderEvent() at System.Xml.XsdValidatingReader.Read() at System.Xml.XmlReader.ReadToDescendant(String name)() [2010-02-18 11:32:03]: Progress: Import Completed. [2010-02-18 11:32:03]: Finish Time: 2010-02-18 11:32:03. [2010-02-18 11:32:03]: Completed with 0 warnings. [2010-02-18 11:32:03]: Completed with 1 errors. I fixed the problem ('ASPXPageIndexMode' attribute not declared) by modifying the C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\XML\DeploymentManifest.xsd and adding the following code under section Hi Chris, I am trying to export and import files from one site to another on MOSS 2007 environment. Export works fine. Now when we trying to import the file I am getting the following error: Invalid file name. The file name you specified could not be used. It may be the name of an existing file or directory, or you may not have permission to access the file. at Microsoft.SharePoint.Library.SPRequest.CreateOrUpdateFileAndItem(String bstrUrl, String bstrWebRelativeUrl, Guid& docId, Object varDoc, Int32 docLength, Int32 exists, String bstrCreatedBy, String bstrModifiedBy, Int32 iCreatedByID, Int32 iModifiedByID, Int32 iVersion, Object varTimeCreated, Object varTimeLastModified, Object varProperties, String checkInComment, Int32 docLibRowID, String bstrListName, UInt32& pdwVirusCheckStatus, String& pVirusCheckMessage) at Microsoft.SharePoint.Deployment.FileSerializer.CreateOrUpdateFileWithGuid(SPFileStream spstm, SPWeb web, Guid fileId, String fileUrl, SPUser author, SPUser editor, String checkinComment, DateTime timeCreated, DateTime timeLastModified, MetaInfoHandler metaInfo, FileInfo fileInfo, Int32 iVersion, Boolean isFirstVersion, SPImportSettings settings, Int32 listItemId, String listInternalName) [3/11/2010 2:18:15 AM]: Progress: Importing File Information Technology Policies/106.003-IT User Access Re-Validation.docx. I have admin previledges on the farm and also I changed the file name as well. Please let me know if you have any clue on this. Thanks Sushank @sksmart, I haven't seen this error but it seems to be an issue with your data somehow. Are you able to identify the file in question? Is there anything strange about it? If it exists already, have you tried deleting it before import as a test? Thanks, Chris. Great tool even though I haven’t quite got it working yet. Basically my Export isn’t producing a cmp file even though it says there are 0 errors. I’ve used the Export several different times on our Staging and Live Farm with different subsites and Document Libraries with the same outcome (plenty of dat files but no cmp file). I’m using the Farm Admin account with 70Gb of free space on my E drive, 5Gb free on the C drive, 8Gb of RAM and 3 GHz CPU. I had thought it was because of the large amount of data being exported but I get the same issue when exporting a small Document Library. All suggestions gratefully received. Here’s an extract of one of My Export Settings … ExportSettings @Tim, This is the expected behaviour if you check the box to disable compression. Could this be the cause? HTH, Chris. My mistake I didn't realise that ticking the "Disable compression" option in the Export means that dat files will be created instead of a CMP file. I did see the "NB Import of uncompressed files is via command-line only" comment but didn't know that this meant no CMP file. I had originally disabled compression as the Export was not working for large content. On further reading I realise that this is because the Temp folder on my C drive hadn't enough space. Now that I've relocated the Temp folder it's working like a treat with compression. Incidently to import my earlier dat files am I right to say I need to use the Import option in the wizard( choosing the appropriate settings) and then "Save Settings". Following this run ... stsadm -o RunWizardImport -settingsFile " -quite Well done again on providing this tool and for all your help. @Tim, No problem at all. And yes, you're spot on about your understanding of how to import the uncompressed files. One thing to check though, is that the value in the saved XML file for 'BaseFileLocation' matches the directory containing all the .dat files. I'll add the capability to import uncompressed files via the GUI soon. All the best, Chris. Hi Chris, I used your tool and got this error : The element 'urn:deployment-manifest-schema:FieldRef' cannot contain child element 'urn:deployment-manifest-schema:FieldRef' because the parent element's content model is empty. any hints on how to solve that. @Anonymous, Yes I've hit that myself - see Editing .cmp files to fix lookup field issues. HTH, Chris. @lifelearner, Are you sure you didn't enabled a feature like publishing or something? if you did, before importing you must enable the same features in the new site. HI great tool, but why do it use the tmp folder for the temporary export and not the defined export path during downloading the documents. so we must set temp to a folder with a lot of more space than the servers c:\ drive. after the download when the tool create the packages then it us the export path. @MichaelW, This is just how SharePoint's Content Deployment feature works, whether you use my front-end or the OOTB pages in Central Admin. More details here (including how to change the location) - HTH, Chris. Hi Chris, Will this work with migrating a WSS 3.0 site to BPOS? Cheers @MikeP, That's a good question - if you're migrating to the same SharePoint version (e.g. 2007), then I think the answer would be 'yes, technically'. I've not yet had direct experience with BPOS, but I wonder if the issue you'd run into is not being able to install the tool on their servers. If you could get past that, then I think the tool would be an option. That said, do BPOS have their own tools to help migrate your content in? Chris. Hi Chris - Well I have tried several things and this Deployment Wizard gets an exception on startup. I really would like to use it so I am wondering what you might suggest. I hate to have to write something like this myself if I can avoid it. There is no msg at all, it just fails. Should I post any server details or other environment details? We are using WSS 2.0 so is that a problem? -Jeannine @Jeannine, Yes sorry - the Content Deployment Wizard is only for WSS3.0/SharePoint 2007 and later. Apologies if this wasn't clear. Chris. I am trying to import .cmp's that were exported from another site. It works until the end of the import when it breaks with, "WBSType is not installed properly". Is there a way to have it ignore this MS Project item and continue importing? @Scotty, Unfortunately, no. This is because SharePoint's Content Deployment infrastructure is based around the premise of "make that site exactly like this one". So if there's some missing prerequisite then the whole operation is designed to fail. Chris. Hey Chris, Thanks for the tool, it "almost" worked for me. "Almost" because I'm stuck with 2010 Beta to 2010 RTM migration... version conflicts.. :( Anyway, i bet I will use your tool later on for everyday migrations...from rtm to rtm !! @Alexaway, Yes, the tool won't help you with beta > RTM I'm afraid, that route is blocked by MS due to all the schema changes! Chris. I like the idea of the tool. Nice work. Is there any way to export a doc lib from MOSS and import into WSS? Also, since content types don't allow the import to work, is there any way to import content types? Sharepoint does not allow Document Libraries to be saved as templates and imported into WSS so a document library cannot be created from a template and then loaded from the export. Also, are you aware of any means to export a doc lib from one site and import into another site with a different name. The Export requires the entire URL to be identical.
http://www.sharepointnutsandbolts.com/2007/12/introducing-sharepoint-content.html
CC-MAIN-2016-44
refinedweb
16,144
64.91
_lwp_cond_reltimedwait(2) - set file access and modification times #include <sys/time.h> int utimes(const char *path, const struct timeval times[2]); int futimesat(int fildes, const char *path, const struct timeval times[2]);, however, futimesat() resolves the path relative to the fildes argument rather than the current working directory. If fildes is set to AT_FDCWD, defined in <fcntl. Upon successful completion, 0 is returned. Otherwise, -1 is returned, errno is set to indicate the error, and the file times will not be affected. The utimes() and futimesat() functions will fail if: Search permission is denied by a component of the path prefix; or the times argument is a null pointer and the effective user ID of the process does not match the owner of the file and write access is denied. The path or times argument points to an illegal address. For futimesat(), path might have the value NULL if the fildes argument refers to a valid open file descriptor. A signal was caught during the execution of the utimes() function. The number of microseconds specified in one or both of the timeval structures pointed to by times was greater than or equal to 1,000,000 or less than 0. An I/O error occurred while reading from or writing to the file system. Too many symbolic links were encountered in resolving path. The length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}. The path argument points to a remote machine and the link to that machine is no longer active. A component of path does not name an existing file or path is an empty string. A component of the path prefix is not a directory or the path argument is relative and the fildes argument is not AT_FDCWD or does not refer to a valid directory. The times argument is not a null pointer and the calling process's effective user ID has write access to the file but does not match the owner of the file and the calling process does not have the appropriate privileges. The file system containing the file is read-only. The utimes() and futimesat() functions may fail if: Path name resolution of a symbolic link produced an intermediate result whose length exceeds {PATH_MAX}. See attributes(5) for descriptions of the following attributes: For utimes(), see standards(5). futimens(2), stat(2), utime(2), attributes(5), fsattr(5), standards(5)
http://docs.oracle.com/cd/E19963-01/html/821-1463/futimesat-2.html
CC-MAIN-2014-23
refinedweb
405
61.36
Name | Synopsis | Description | Return Values | Errors | Usage | Examples | Attributes | See Also #include <sys/types.h> #include <unistd.h> int pthread_atfork(void (*prepare) (void), void (*parent) (void), void (*child) (void)); The pthread_atfork() function declares fork handlers to be called prior to and following fork(2), within the thread that called fork(). The order of calls to pthread_atfork() is significant. Before fork() processing begins, the prepare fork handler is called. The prepare handler is not called if its address is NULL. The parent fork handler is called after fork() processing finishes in the parent process, and the child fork handler is called after fork() processing finishes in the child process. If the address of parent or child is NULL, then its handler is not called. The prepare fork handler is called in LIFO (last-in first-out) order, whereas the parent and child fork handlers are called in FIFO (first-in first-out) order. This calling order allows applications to preserve locking order. Upon successful completion, pthread_atfork() returns 0. Otherwise, an error number is returned. The pthread_atfork() function will fail if: Insufficient table space exists to record the fork handler addresses. Solaris threads do not offer pthread_atfork() functionality (there is no thr_atfork() interface). However, a Solaris threads application can call pthread_atfork() to ensure fork()–safety, since the two thread APIs are interoperable. Seefork(2) for information relating to fork() in a Solaris threads environment in Solaris 10 relative to previous releases. All multithreaded applications that call fork() in a POSIX threads program and do more than simply call exec(2) in the child of the fork need to ensure that the child is protected from deadlock. Since the "fork-one" model results in duplicating only the thread that called fork(), it is possible that at the time of the call another thread in the parent owns a lock. This thread is not duplicated in the child, so no thread will unlock this lock in the child. Deadlock occurs if the single thread in the child needs this lock. The problem is more serious with locks in libraries. Since a library writer does not know if the application using the library calls fork(), the library must protect itself from such a deadlock scenario. If the application that links with this library calls fork() and does not call exec() in the child, and if it needs a library lock that may be held by some other thread in the parent that is inside the library at the time of the fork, the application deadlocks inside the library. The following describes how to make a library safe with respect to fork() by using pthread_atfork(). Identify all locks used by the library (for example {L1, . . .Ln}). Identify also the locking order for these locks (for example {L1 . . .Ln}, as well.) Add a call to pthread_atfork(f1, f2, f3) in the library's .init section. f1, f2, f3 are defined as follows: f1( ) { /* ordered in lock order */ pthread_mutex_lock(L1); pthread_mutex_lock( . . .); pthread_mutex_lock(Ln); } f2( ) { pthread_mutex_unlock(L1); pthread_mutex_unlock( . . .); pthread_mutex_unlock(Ln); } f3( ) { pthread_mutex_unlock(L1); pthread_mutex_unlock( . . .); pthread_mutex_unlock(Ln); } See attributes(5) for descriptions of the following attributes: exec(2), fork(2), atexit(3C), attributes(5), standards(5) Name | Synopsis | Description | Return Values | Errors | Usage | Examples | Attributes | See Also
http://docs.oracle.com/cd/E19082-01/819-2243/6n4i099bf/index.html
CC-MAIN-2013-48
refinedweb
537
55.34
Whether you work in a company, a big team or by yourself, having consistently formatted code is significant for maintainability and readability. Also, there are tons of ways and this is the standard way and most developers should look into it. Too Long; Didn’t Read Most developers know the tool of Prettier because it is very easy to use and it makes sense to run the command. npm run prettier -g However, we will forget or sometimes when you push to pipeline, you realize the problem that you didn’t run the prettier before you commit. Or sometimes, the VPS you used does not have prettier or nothing like linter install. That means it will make your pipeline fail. The major issue is that you forget to format the Ember Code, it can create the mess that other developers may have a problem reading the code. See. e.g. import Ember from 'ember'; import config from './config/environment'; const Router = Ember.Router .extend( { location: config.locationType, rootURL: config.rootURL } ); Router .map(function() { }); export default Router; As you can see, the code above does not make use to read easily, and you do not want to run npm prettier every single time. Format Code Like Pro: Is that an easier way to format your code without using any IDE like VS Code, IntelliJ, NetBeans, or Eclipse when you commit your project to Github/GitLab/Bitbucket? Of course, that can be as simple as it is. So, there are three packages you need to install before : npm i husky prettier pretty-quick --save-dev Now you should see the package that installs on your Emberjs: "husky": "^3.1.0", "prettier": "^1.19.1", "pretty-quick": "^2.0.1" Once you have all those packages installed, there is one last step before you will make your commit much efficient. First Step: // package.json "scripts": { prettier": "prettier --write \"app/*/*.js\"" } Second Step: // package.json "husky": { "hooks": { "pre-commit": "npm run prettier && pretty-quick --staged && git add ." } } Now you are all set up! Test out by running git command on your ember project. git add . git commit -m 'automation format' // output app/adapters/application.js 42ms app/components/article-body.js 24ms app/components/article-list.js 12ms app/components/article-share-menu.js 9ms app/components/bear-list.js 17ms app/components/loader.js 8ms app/components/nav.js 8ms 🔍 Finding changed files since git revision 123456. 🎯 Found 0 changed files. ✅ Everything is awesome! On branch master Your branch is ahead of 'origin/master' by 1 commit. (use "git push" to publish your local commits) Conclusion Prettier, husky and pretty-quick can improve your workflow by formatting your JavaScript files before every commit. If you want to learn more about how to use link-staged. Check out full repo on the link to see how easy it is. Discussion (1) I love these tools. This is what I put in place on dev.to, github.com/thepracticaldev/dev.to/...
https://practicaldev-herokuapp-com.global.ssl.fastly.net/shijiezhou/using-prettier-and-husky-to-make-your-emberjs-great-again-5790
CC-MAIN-2022-33
refinedweb
496
60.31
A lightweight kubernetes development setup A lightweight alternative to KinD for local development. Read the introductory blog post. There is a more updated tool rancher/k3d which has more functionality than this tool and is written in go, I'd urge you to give it a try over this repo. curl -sSL | sudo bash - k3d create cargo install k3d && k3d create Normal flow: k3d create export KUBECONFIG=$(k3d get-kubeconfig) kubectl get pods --all-namespaces k3d delete If port 6443 is occupied you can specify a different port in first step: k3d create -p 10001. This will create a docker container named k3s_default with port 10001 exposed. You can specify a different name for cluster with k3s create -n, but then keep in mind to do k3d get-kubeconfig -nwhen getting kubeconfig. k3d 0.1.0 Rishabh Gupta Run k3s in Docker USAGE: k3d [SUBCOMMAND] FLAGS: -h, --help Prints help information -V, --version Prints version information SUBCOMMANDS: check-tools Check docker running create Create a single node k3s server delete Delete cluster get-kubeconfig get kubeconfig.yaml location help Prints this message or the help of the given subcommand(s) list List all clusters start Start a stopped cluster stop Stop a cluster </r.g.gupta>
https://xscode.com/zeerorg/k3s-in-docker
CC-MAIN-2021-49
refinedweb
206
55.58
Wraps a python function into a TensorFlow op that executes it eagerly. View aliases Compat aliases for migration See Migration guide for more details. tf.py_function( func, inp, Tout, name=None ) This function allows expressing computations in a TensorFlow graph as Python functions. In particular, it wraps a Python function func in a once-differentiable TensorFlow operation that executes it with eager execution enabled. As a consequence, tf.py_function makes it possible to express control flow using Python constructs ( if, while, for, etc.), instead of TensorFlow control flow constructs ( tf.cond, tf.while_loop). For example, you might use tf.py_function to implement the log huber function: def log_huber(x, m): if tf.abs(x) <= m: return x**2 else: return m**2 * (1 - 2 * tf.math.log(m) + tf.math.log(x**2)) x = tf.compat.v1.placeholder(tf.float32) m = tf.compat.v1.placeholder(tf.float32) y = tf.py_function(func=log_huber, inp=[x, m], Tout=tf.float32) dy_dx = tf.gradients(y, x)[0] with tf.compat.v1.Session() as sess: # The session executes `log_huber` eagerly. Given the feed values below, # it will take the first branch, so `y` evaluates to 1.0 and # `dy_dx` evaluates to 2.0. y, dy_dx = sess.run([y, dy_dx], feed_dict={x: 1.0, m: 2.0}) You can also use tf.py_function to debug your models at runtime using Python tools, i.e., you can isolate portions of your code that you want to debug, wrap them in Python functions and insert pdb tracepoints or print statements as desired, and wrap those functions in tf.py_function. For more information on eager execution, see the Eager guide. tf.py_function is similar in spirit to tf.compat.v1.py_func, but unlike the latter, the former lets you use TensorFlow operations in the wrapped Python function. In particular, while tf.compat.v1.py_func only runs on CPUs and wraps functions that take NumPy arrays as inputs and return NumPy arrays as outputs, tf.py_function can be placed on GPUs and wraps functions that take Tensors as inputs, execute TensorFlow operations in their bodies, and return Tensors as outputs. Like tf.compat.v1.py_func, tf.py_function has the following limitations with respect to serialization and distribution:.py_function(). If you are using distributed TensorFlow, you must run a tf.distribute.Serverin the same process as the program that calls tf.py_function()and you must pin the created operation to a device in that server (e.g. using with tf.device():).
https://tensorflow.google.cn/versions/r2.1/api_docs/python/tf/py_function?hl=bn
CC-MAIN-2022-33
refinedweb
411
53.37
Log. Log message: Changes in 3.8.2 since 3.8.1: * bootstrap: fix build on mingw-w64 * cmFileCommand: Fix build on mingw-w64 * GNUtoMS: Add search path for VS 2015 environment scripts * GNUtoMS: Add search path for VS 2017 environment scripts * FindDevIL: Restore IL_FOUND result variable * FindOpenSSL: Restore support for crypto-only result * source_group: Restore TREE support for relative paths * VS: Fix debugging of C++ executables if CSharp is enabled Log message: Recursive revision bump for archivers/libarchive. Log message: Changes in 3.8.1 since 3.8.0: * FindOpenSSL: Add more library name alternatives * FindBoost: Restore tolerance of backslashes in paths * Tests: Fix FindModulesExecuteAll when KDE4 is installed * Tests: Simplify CMakeOnly.AllFindModules policy settings * FindBoost: Fix library directory for VS 2017 * CPack/RPM doc: CPACK_RPM_BUILDREQUIRES docs * source_group: Fix TREE with root that is not current source dir * FindMatlab: Add support for Matlab 2017a * VS: Fix project reference inspection in VS IDE * FindBoost: Allow testing for multiple compiler suffixes * FindBoost: Support prebuilt Windows binaries from SourceForge * VS2017: Verify Windows 8.1 SDK before using it Log message: cmake: revise netbsd-6 build fix patch as suggested by Brad King TagRunPath = 0 may cause client code such as cmSystemTools::RemoveRPath to misbehave. Define DT_RUNPATH to the expected value (29) instead. bump pkgrevision Log message: cmake: fix build under netbsd-6 don't use DT_RUNPATH if it's not defined include cstdlib as our patch uses exit from yancm via pkgsrc-users Log message: Changes 3.8.0: CMake learned to support CSharp (C#) as a first-class language that can be \ enabled via the project() and enable_language() commands. It is currently \ supported by the Visual Studio Generators for VS 2010 and above. C# assemblies and programs can be added just like common C++ targets using the \ add_library() and add_executable() commands. References between C# targets in \ the same source tree may be specified by target_link_libraries() like for C++. \ References to system or 3rd-party assemblies may be specified by the target \ properties VS_DOTNET_REFERENCE_<refname> and VS_DOTNET_REFERENCES. More fine tuning of C# targets may be done using target and source file \ properties. Specifically the target properties related to Visual Studio (VS_*) \ are worth a look (for setting toolset versions, root namespaces, assembly icons, \ ...). CMake learned to support CUDA as a first-class language that can be enabled via \ the project() and enable_language() commands. CUDA is currently supported by the Makefile Generators and the Ninja generator \ on Linux, macOS, and Windows. Support for the Visual Studio IDE is under \ development but not included in this release. The NVIDIA CUDA Toolkit compiler (nvcc) is supported. Compile Features functionality is now aware of the availability of C99 in \ gcc since version 3.4. A new minimal platform file for Fuchsia was added. The CodeBlocks extra generator may now be used to generate with NMake Makefiles JOM.. ...more... Log message: Changes 3.7.2: Bug fixes. Log message: Recognize libgnuform as valid implementation of a form library to match devel/ncurses. This is necessary due to cmake's insistance of scanning PREFIX/lib directly. Bump revision.
http://pkgsrc.se/commits.php?path=devel/cmake
CC-MAIN-2017-34
refinedweb
510
54.22
NWChem¶ NWChem is a computational chemistry code based on gaussian basis functions or plane-waves. Setup¶ You first need to install a working copy of NWChem for ASE to call; follow the instructions on the NWChem website. The default command that ASE will use to start NWChem is nwchem PREFIX.nw > PREFIX.out. You can change this command by setting the environment variable ASE_NWCHEM_COMMAND. (For example, add a line to your .bashrc with export ASE_NWCHEM_COMMAND="my new command".) The default command will only allow you to run NWChem on a single core. To run on multiple processors you will need to specify your MPI (or similar) command, which typically requires telling the MPI command the number of tasks to dedicate to the process. An example command to allow multiprocessing is mpirun -n $SLURM_NTASKS nwchem PREFIX.nw > PREFIX.out, for the SLURM queueing system. If you use a different queueing system replace $SLURM_NTASKS with the appropriate variable, such as $PBS_NP. Examples¶ Here is a command line example of how to optimize the geometry of a water molecule using the PBE density functional: $ ase build H2O | ase run nwchem -p xc=PBE -f 0.02 Running: H2O LBFGS: 0 09:58:54 -2064.914841 1.9673 LBFGS: 1 09:58:55 -2064.976691 0.1723 LBFGS: 2 09:58:55 -2064.977120 0.0642 LBFGS: 3 09:58:55 -2064.977363 0.0495 LBFGS: 4 09:58:56 -2064.977446 0.0233 LBFGS: 5 09:58:56 -2064.977460 0.0059 $ ase gui H2O.traj@-1 -tg "a(1,0,2),d(0,1)" 102.591620591 1.00793234388 An example of creating an NWChem calculator in the python interface is: from ase.calculators.nwchem import NWChem calc = NWChem(label='calc/nwchem', maxiter=2000, xc='B3LYP', basis='6-31+G*') If you need to request more memory, it is typically not sufficient to do so only through your queuing system. You need to also let NWChem know about the additional available memory, with NWChem’s \(memory\) keyword which in turn is added through ASE’s \(raw\) keyword (which puts raw text lines in the NWChem input file). An example is below; see the official NWChem documentation for the proper use of the \(memory\) keyword. calc = NWChem(label='calc/nwchem', raw='memory 2000 MB') Parameters¶ The list of possible parameters and their defaults is shown below. See the NWChem documentation for full explanations of these different options. See the source code link below for further details.
https://wiki.fysik.dtu.dk/ase/dev/ase/calculators/nwchem.html
CC-MAIN-2019-13
refinedweb
412
58.18
basic BDJO production problem Hi I have been doing a lot of research on development of BD interactivity,but have had little luck getting my helloworld example working. I have been trying to get the HelloTVXlet to work in conjunction with my software BD emulator (Scenarist QC), but have run into trouble in .bdjo production. I use the sample BDMV directory structure from the cookbook site, replace the jar file with the one I have produced (jar -cvf 00000.jar HelloTVXlet.class HelloTVXlet$1.class), and replace the bdjo file using the converter in the HDCOOKBOOK repository. I replace initialClassName with HelloTVXlet (have tried HelloTVXlet.class as well), yet when I test the helloworld disc image, Scearist's debug window states that Output: XletClassLoader.findClass HelloTVXlet not found. Error: java.lang.ClassNotFoundException I have looked at the xml file generated when using the sample disc image's default bdjo, and the initialClassName is prepended with some other structure that I do not understand (com.hdcookbook.bookmenu.monitor.MonitorXlet). I am assuming I need to prepend my class name, but with what? I hope that this is the root of my problem, as I have followed the wiki and readme files very closely up to this point. Any help would be greatly appreciated, I feel like I have tried everything : ( -Ryan B Hi Ryan, Just following up. Like szmarine said, BDJO's initial class name should be a fully qualified class name - which means, it should include the HelloTVXlet's package name. I believe we have a simple test project under hdcookbook/xlets/HelloWorldXlet, which makes a full disc image. Also, note that if you are jarring up the classes by using the "jar" command, then you're making the jar "unsigned". An insecure xlet will not be able to do much beyond helloworld... Chihiro Thanks a lot, will try to produce a full package name and test next time I'm in the office. Should I be producing my own index files as well? I know that there are parts of the puzzle I have yet to touch and I feel a bit naive copying full disc images and adding a few files. BTW I have been using Scenarist BD-J but decided to stick with the command line interface as I was a bit overwhelmed with the options available for output files. Do you think that this will be limiting for me in the future? Thanks again, I am very excited with the prospect of java on bluray players. -Ryan Hi Ryan, 1) I think you need to specify the full Xlet package/name, so that your Xlet can be found. For example, in your Xlet, there could be code like: package com.mycompany; .... public class HelloTVXlet implements Xlet { ... } Then with Scnarist BDJ, when export BDJO->add Xlet, inpurt the full package/class name com.mycompany.HelloTVXlet. 2) Make sure that 00000 is set to be the base directory, so that other resources or classes in this jar referenced by the Xlet can be found. Hope this helps.
https://www.java.net/node/694838
CC-MAIN-2015-22
refinedweb
509
61.87
Define-cmd This command defines a macro called macroName, and associates it with the given script. MacroName can then be used like a command, and invokes the given script. To see the script associated with a defined macro, use:define macroName. Macros can take up to five arguments. Use the %1, %2, %3, etc., notation within the script to indicate that the macro expects one or more arguments. A macro can accept a number, string, variable, dataset, function, or script as an argument, but all arguments are passed as strings. These are similar to MS-DOS batch command arguments. If arguments are passed to a macro, the macro can report the number of arguments using the macro.nArg object property. define macroName (script) Example 1 The following script defines the autoexec macro to create a new Origin worksheet from the ORIGIN.OTW template. def autoexec { window -T Data Origin; }; Example 2 The next script defines a macro that uses a loop to print a text string three times. def hello { loop (ii, 1, 3) { type "$(ii). Hello World"; }; }; Once the hello macro is defined, typing the word hello in the Script window results in the printout: 1. Hello World 2. Hello World 3. Hello World Example 3 The following script defines a macro named abc that expects a single argument. The given argument is then multiplied by 2, and the result is printed. def abc { type "$(%1 * 2)"; }; If you define this macro (previous example) and then type the following in the Script window: abc 5 Origin responds: 10 You could modify the abc macro (previous example) to take two arguments: def abc { type "$(%1 * %2)"; }; Now, if you type the following in the Script window: abc 5 4 Origin responds: 20
https://www.originlab.com/doc/LabTalk/ref/Define-cmd
CC-MAIN-2019-47
refinedweb
292
73.07
Recently I thought I would check out the charting controls in the Silverlight Toolkit. I’d been meaning to for awhile, but I was distracted by other tasks such as writing the documentation for the Silverlight 4 beta release. Well, those docs have gone out so I had some time on my hands. I fired up my machine with Silverlight 3 and the Toolkit for Silverlight 3 installed and got busy. I thought I’d start with a pie chart, because everyone loves pie charts, right? Okay, maybe it’s pie that everyone loves, but I do enjoy a good pie chart as well. One of the things we are always looking at on the User Education team is what a particular writer owns compared with other writers. This is one of the pieces of data we use to determine who should own new features. A pie chart is an easy way to visualize this data. For example, let’s say we have three writers with the following type distribution that I want to represent in a chart: To get started, I created a Silverlight project and added a very simple class to represent a writer and type ownership: public class Writer { public Writer() { } public Writer(string writerName, int numOfTypes) { Name = writerName; Types = numOfTypes; } public string Name { get; set; } public int Types { get; set; } } Next, in the constructor for my page, I created an ObservableCollection that contains the writers. public MainPage() { InitializeComponent(); ObservableCollection<Writer> Team = new ObservableCollection<Writer> { new Writer("Chris Sells", 114), new Writer("Luka Abrus", 225), new Writer("Jim Hance", 140) }; } A cool feature of the Toolkit for Silverlight 3 is the great designer support. The Toolkit controls display in the Visual Studio Toolbox so you can simply drag the desire controls onto the XAML editing surface. Doing so adds the necessary references, using statements and XAML namespace qualifiers to the XAML and code files. There are a few key steps to adding a chart to your application. First, drag a Chart control to the XAML editor. Here’s the Toolbox: I set the chart’s name and title properties. <chartingToolkit:Chart x: </chartingToolkit:Chart> Then you’ll need to add a chartNameSeries control inside the Chart control. In this case, I’ll add a PieSeries by dragging it from the ToolBox to the XAML editor, inside the <Chart> tags. I set the ItemsSource property to a {Binding}, the IndependentValue path to Name, which means my pie chart will have an entry for each writer name. and the DependentValuePath to Types so my pie chart will display the number of types that each writer is assigned as a portion of the pie. <chartingToolkit:Chart x: <chartingToolkit:PieSeries </chartingToolkit:PieSeries> </chartingToolkit:Chart> Lastly, in the code-behind file, I set the data context for MyPie to the collection of writers. MyPie.DataContext = Team; I pressed F5 and look at the beautiful pie chart I got: This chart is nice, and it was incredibly easy to create, but I decided I wanted to see this data in bar-chart format. I swapped my PieSeries for a BarSeries, keeping the same property settings (yes, I even left it named “MyPie” for now). Here’s the XAML: <chartingToolkit:Chart x: <chartingToolkit:BarSeries </chartingToolkit:BarSeries> </chartingToolkit:Chart> When I pressed F5, I got the this bar chart: This bar chart is okay, but the default scale the data is presented in makes Chris look like a slacker. Since I know he’s not (for the record, these names are out of our fictitious names list), I wanted to change the scale a bit. Also the “Series 1” title isn’t very helpful. Fixing the “Series 1” was easy…I added a title to my bar series. <chartingToolkit:BarSeries </chartingToolkit:BarSeries> I discovered that in order to change the scale in which my data is displayed, I needed to add some Axes to my chart. A Chart object has an Axes property that you set to a collection of Axis objects. There are many different types of axis for displaying different kinds of data. These different types of axis all derive from Axis are generally named using the following convention: DescriptionOfFunctionAxis. For my chart I’ll use a LinearAxis since I am displaying numbers. I set the properties of my LinearAxis to the following values: With these settings I adjust the scale of the X-axis to 0-300, with intervals of 50. I also opted to show gridlines and decided to use an italic font. Getting fancy now, I also added a CategoryAxis, used for displaying category information, with its Title property set to Writer, and an Orientation set to Y. This will add “Writer” along the Y-axis for clarity. When I was finished, my XAML looked like this (the newly added portion is in a bold font) : <chartingToolkit:Chart x: <chartingToolkit:Chart.Axes> <chartingToolkit:CategoryAxis <chartingToolkit:LinearAxis </chartingToolkit:Chart.Axes> <chartingToolkit:BarSeries </chartingToolkit:BarSeries> </chartingToolkit:Chart> I pressed F5 and here’s what I got: Yeah! Chris suddenly looks much more productive, and I’ve gotten started with charting!
http://blogs.msdn.com/b/silverlight_sdk/archive/2009/12/07/getting-started-with-the-charting-controls.aspx
CC-MAIN-2014-42
refinedweb
848
59.64
21 November 2008 16:50 [Source: ICIS news] LONDON (ICIS news)--The European hydrochloric acid (HCI) market has tightened significantly over the past few weeks due to production cutbacks in toluene diisocyanate (TDI) and methyl di-p-phenylene isocyanate (MDI), market sources said on Friday. As the global economic crisis has reduced demand for TDI and MDI, particularly from the construction and automotive industries, producers said they have been running operations at lower rates. Sources estimated that European TDI and MDI production was running at around 60-70% of capacity. This has led to curtailed production of HCI and reduced output of chlorine derivatives, sources said. With the reduction in HCI demand declining at a much slower rate than supply, sources said there was an imbalance in the market. While HCI demand from the steel industry has slowed, sources said there had been no downturn in requirements for water treatment, food, gelatine and power plants. Some suppliers in ?xml:namespace> Sources noted that the tight supply situation was strengthening producer targets of price increases of €10-20/tonne ($13-25/tonne) for 2009. With discussions underway, some producers said they were delaying talks until they had a clearer idea of what volumes they would have available next year. ($1 = €0.79) For more on HCI, MDI
http://www.icis.com/Articles/2008/11/21/9173786/europe-hci-market-tightens-on-tdi-mdi-cutbacks.html
CC-MAIN-2014-52
refinedweb
216
50.67
by Jeffrey Kantor (jeff at nd.edu). The latest version of this notebook is available at. The purpose of this Jupyter Notebook is to get you started using Python and Jupyter Notebooks for routine chemical engineering calculations. This introduction assumes this is your first exposure to Python or Jupyter notebooks. Jupyter notebooks are documents that can be viewed and executed inside any modern web browser. Since you're reading this notebook, you already know how to view a Jupyter notebook. The next step is to learn how to execute computations that may be embedded in a Jupyter notebook. To execute Python code in a notebook you will need access to a Python kernal. A kernal is simply a program that runs in the background, maintains workspace memory for variables and functions, and executes Python code. The kernal can be located on the same laptop as your web browser or located in an on-line cloud service. Important Note Regarding Versions There are two versions of Python in widespread use. Version 2.7 released in 2010, which was the last release of the 2.x series. Version 3.5 is the most recent release of the 3.x series which represents the future direction of language. It has taken years for the major scientific libraries to complete the transition from 2.x to 3.x, but it is now safe to recommend Python 3.x for widespread use. So for this course be sure to use latest verstion, currently 3.6, of the Python language. The easiest way to use Jupyter notebooks is to sign up for a free or paid account on a cloud-based service such as Wakari.io or SageMathCloud. You will need continuous internet connectivity to access your work, but the advantages are there is no software to install or maintain. All you need is a modern web browser on your laptop, Chromebook, tablet or other device. Note that the free services are generally heavily oversubscribed, so you should consider a paid account to assure access during prime hours. There are also demonstration sites in the cloud, such as tmpnb.org. These start an interactive session where you can upload an existing notebook or create a new one from scratch. Though convenient, these sites are intended mainly for demonstration and generally quite overloaded. More significantly, there is no way to retain your work between sessions, and some python functionality is removed for security reasons. This course will use a cloud-based service Vocareum to provide on-line access to Jupyter notebooks and Python through the Sakai learn management system. Once you log into Sakai, you can access Vocareum directly and use it to complete and submit course assignments. For regular off-line use you should consider installing a Jupyter Notebook/Python environment directly on your laptop. This will provide you with reliable off-line access to a computational environment. This will also allow you to install additional code libraries to meet particular needs. Choosing this option will require an initial software installation and routine updates. For this course the recommended package is Anaconda available from Continuum Analytics. Downloading and installing the software is well documented and easy to follow. Allow about 10-30 minutes for the installation depending on your connection speed. simplifies startup of the notebook environment and manage the update process. and execute the following statement at the command line: > jupyter notebook Either way, once you have opened a session you should see a browser window like this: At this point. New Notebookbutton, or An IPython notebook consists of cells that hold headings, text, or python code. The user interface is relatively self-explanatory. Take a few minutes now to open, rename, and save a new notebook. Here's a quick video overview of Jupyter notebooks. from IPython.display import YouTubeVideo YouTubeVideo("HW29067qVWk",560,315,rel=0) Python is an elegant and modern language for programming and problem solving that has found increasing use by engineers and scientists. In the next few cells we'll demonstrate some basic Python functionality. Basic arithmetic operations are built into the Python langauge. Here are some examples. In particular, note that exponentiation is done with the ** operator. a = 12 b = 2 print(a + b) print(a**b) print(a/b) 14 144 6.0 import numpy as np # mathematical constants print(np.pi) print(np.e) # trignometric functions angle = np.pi/4 print(np.sin(angle)) print(np.cos(angle)) print(np.tan(angle)) 3.141592653589793 2.718281828459045 0.707106781187 0.707106781187 1.0 Lists are a versatile way of organizing your data in Python. Here are some examples, more can be found on this Khan Academy video. xList = [1, 2, 3, 4] xList [1, 2, 3, 4] Concatentation is the operation of joining one list to another. # Concatenation x = [1, 2, 3, 4]; y = [5, 6, 7, 8]; x + y [1, 2, 3, 4, 5, 6, 7, 8] Sum a list of numbers np.sum(x) 10 An element-by-element operation between two lists may be performed with print(np.add(x,y)) print(np.dot(x,y)) [ 6 8 10 12] 70. This example also demonstrates string formatting. for x in xList: print("sin({0}) = {1:8.5f}".format(x,np.sin(x))) sin(1) = 0.84147 sin(2) = 0.90930 sin(3) = 0.14112 sin(4) = -0.75680 mw = {'CH4': 16.04, 'H2O': 18.02, 'O2':32.00, 'CO2': 44.01} mw {'CH4': 16.04, 'CO2': 44.01, 'H2O': 18.02, 'O2': 32.0} We can a value to an existing dictionary. mw['C8H18'] = 114.23 mw {'C8H18': 114.23, 'CH4': 16.04, 'CO2': 44.01, 'H2O': 18.02, 'O2': 32.0} CH4 is 16.04 The molar mass of C8H18 is 114.23 The molar mass of O2 is 32.00 The molar mass of CO2 is 44.01 %matplotlib inline import matplotlib.pyplot as plt import numpy as np112e79390>11439fda0>.
http://nbviewer.jupyter.org/github/jckantor/CBE30338/blob/master/notebooks/Getting%20Started%20with%20Python.ipynb
CC-MAIN-2018-26
refinedweb
987
69.18
93774/error-class-numberformatter-not-found I've been using this exact same code for ages, and I have never had a single problem. Now all of a sudden it has stopped working. I have read across the internet about this problem, and apparently you need PHP 5.3 or higher installed, and the PHP intl plugin installed. I have both of these, yet I am still receiving a Fatal error: Class 'NumberFormatter' not found error whenever I use the following function: function format_item($value) { $format = new \NumberFormatter('en_US', \NumberFormatter::CURRENCY); return $format->formatCurrency($value, 'AUD'); } Also, here is a snippit from my php.ini file showing that I have the PHP intl plugin installed: [intl] intl.default_locale = fr_FR ; This directive allows you to produce PHP errors when some error ; happens within intl functions. The value is the level of the error produced. ; Default is 0, which does not produce any errors. intl.error_level = E_WARNING I also have the extension=php_intl.dll in my php.ini, and it is also in my directory. Why am I getting this error? Hello @kartik, You just need to enable this extension in php.ini by uncommenting this line: extension=ext/php_intl.dll Hope it helps!! Hello @kartik, To install SOAP in PHP-7 run ...READ MORE Hello @kartik, Something is clearly corrupt in your ...READ MORE Hii, Use the --no-scripts flag to prevent artisan from executing .., You can use TestCase instead PHPUnit_Framework_TestCase // use the following namespace use ...READ MORE Hello @kartik, You may get this error because ...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/93774/error-class-numberformatter-not-found?show=93775
CC-MAIN-2022-33
refinedweb
281
59.7
There's a mobile version of our website. You need to configure a bridged interface that is linked to your ethernet-interface and your wlan-ap0-interface. On the bridged-interface you set the IP-address. Search on cisco's website to set it up. Thank you for the reply but when I try to bridge the wlan-ap0 interfae it says it does not support bridging. This is the command I used: bridge-group 1 This isthe output I get wlan-ap0 does not support bridging Any other ideas? Maybe this link will help: Haven't looked though it, but if there is an answer for your question, it should be there. I think the very first thing they show might be the thing you are looking for. You need to create a vlan en BVI interface in you're config ! ip dhcp pool LAN-WiFi import all network 192.168.0.0 255.255.255.0 dns-server 194.109.6.66 194.109.9.99 default-router 192.168.0.1 domain-name WORKGROUP lease 7 ! ..... ! interface wlan-ap0 ip unnumbered BVI1 arp timeout 0 no mop enabled no mop sysid ! interface GigabitEthernet0/0 no ip address duplex auto speed auto no cdp enable bridge-group 1 hold-queue 100 out ! interface Vlan1 no ip address bridge-group 1 ! interface BVI1 ip address 192.168.0.1 255.255.255.0 ip nat inside ip virtual-reassembly in no ip route-cache ! and do not forget bridge 1 protocol ieee bridge 1 route ip in you're AP config you can set both ( 2.4 and 5Ghz ) to the vlan1 now the LAN and WLAN have the same IP.
https://supportforums.cisco.com/thread/2144961
CC-MAIN-2014-10
refinedweb
282
76.42
I have a input file of 20 whole numbers, the user enters a number and it searchs the array for a match, if a match is found it tells you the number enterd was found and displays the number. What i need to be able to do is add a counter of how many times that number appears in the infile, currently it stops as soon as the number is found. Code:#include <iostream> #include <fstream> #include <string> #include <cassert> using namespace std; const int MAXSIZE = 20; void get_score(int code[], int& count); int find_match(int inCode, int code[], int count); int main() { int code[MAXSIZE] = {0}; int inCode = 0, count = 0, location = 0; int total = 0; get_score(code, count); cout << "Enter a score: "; cin >> inCode; while(inCode != -1) { location = find_match(inCode, code, count); if(location < MAXSIZE) { cout << "Code: " << total << " "<< code[location] << endl; } else cout << "Code not found\n"; cout << "Enter a Code: "; cin >> inCode; } return 0; }//end main //------------------------------------------ void get_score(int code[], int & count) { ifstream fin; fin.open("pricelist.txt", ios::in); fin >> code[MAXSIZE]; assert(!fin.fail()); int c; while(fin >> ws && !fin.eof()) { if(count < MAXSIZE)//still room { fin >> code[count]; fin >> ws; count++; } else { fin >> c; fin >> ws; cout << "No room for " << c << endl; } } } //search int find_match(int inCode, int code[], int count) { int total = 0; int sub = 0; bool found = false; while(sub < count && ! found) { if(inCode == code[sub]) found = true; else sub++; } if(found) return sub; else return MAXSIZE; }
http://cboard.cprogramming.com/cplusplus-programming/59307-question.html
CC-MAIN-2014-52
refinedweb
245
60.89
The Ribbon RTM release was built against .NET 3.5, but our October 2010 release of Ribbon includes both .NET 3.5 and .NET 4.0 Ribbon DLLs. With the v4.0 Ribbon, we have enabled ClearType on all of the Ribbon controls using RenderOptions.ClearTypeHint. WPF applications using RibbonWindow must also opt-in to enable ClearType for all content below the Ribbon. This article describes ClearType technology and requirements and then specifies how a WPF Ribbon application enables ClearType. We refer to RibbonWindow and Ribbon applications specifically, but similar steps to enable ClearType apply for any WPF app that uses WindowChrome. - I. What is ClearType and where is it available? - II. Why is it necessary to opt in to ClearType when using RibbonWindow in Aero theme? - III. How WPF Ribbon achieves ClearType - IV. Example: Enable ClearType for body text of RibbonWindow - V. IRTs and ClearTypeHint - VI. Determining if text is rendering as ClearType - VII. Conditional Compilation of ClearType for .NET 4.0 - VIII. Sample Code & Related Links I. What is ClearType and where is it available? ClearType is a subpixel anti-aliasing technique for improving text smoothness. Wikipedia has a nice overview of the technology here. WPF supports ClearType and extends ClearType in .NET 4 by allowing app developers to electively use ClearType on surfaces that are otherwise considered transparent and hence inappropriate for ClearType. Read more about WPF support for ClearType here. ClearType support in WPF has a couple requirements: - Opaque surface - ClearType is incompatible with alpha blending, so text cannot render as ClearType on top of a transparent background. In .NET 4.0, ClearTypeHint allows developers to enable ClearType where it is otherwise disabled, though this could make text worse or cause rendering issues when used over a non-opaque background. - OS support - ClearType is available on all Windows OS’s where WPF runs, starting with Windows XP. However, ClearType is only enabled by default on Vista & later. So, Windows XP users must go through Control Panel to enable ClearType. More information is available in this white paper on WPF text clarity. Here is some text rendering as ClearType (shown at 800% magnification):Here is some text rendering as ClearType (shown at 800% magnification): Notice the red and the blue hues. These indicate the text is rendering on subpixel boundaries. Rendering this text on subpixel boundaries gives 3x higher horizontal resolution than rendering on pixel boundaries, although there is a chromatic cost – some color is introduced to create the smoothing effect. This snapshot was taken at 800% magnification, and when I zoom out to normal resolution the red and blue hues are unnoticeable and you see smooth text. II. Why is it necessary to opt in to ClearType when using RibbonWindow in Aero theme? Normal WPF 4.0 Window will support ClearType by default, so you get it for free. However, if you are using RibbonWindow, you need to opt in using the RenderOptions.ClearTypeHint attached property (System.Windows.Media namespace, PresentationCore.dll). This is necessary because RibbonWindow extends glass into the client area using DwmExtendFrameIntoClientArea. (RibbonWindow claims the entire native window as client area so that it can draw the Quick Access Toolbar in what is normally non-client area. Therefore, RibbonWindow must extend glass into the client area to attain the appearance of a normal Aero window.) It is only necessary for RibbonWindow apps to set RenderOptions.ClearTypeHint for their Aero themes, but setting ClearTypeHint.Enabled for all themes shouldn’t hurt. III. How WPF Ribbon achieves ClearType All of the WPF Ribbon controls render as ClearType as long as they are rendering against solid backgrounds (most controls are). Examine this screenshot: Notice how the “Home” RibbonTab is rendering as ClearType with warm and cold hues, while the RibbonTitlePanel’s text is using grayscale anti-aliasing. This screenshot was taken on Win7 Aero, and the RibbonTitlePanel renders directly on glass, so it doesn’t support ClearType. The grayscale text is choppier, while ClearType offers a general improvement in text clarity. The text sharpening provided by ClearType is a cumulative effect, so the improvement in clarity becomes more evident at the document/app level. The “Home” tab has ClearType “because the v4.0 Template for RibbonTabHeader sets RenderOptions.ClearTypeHint=“Enabled” on its “InnerBorder” element. Other Ribbon controls set ClearTypeHint in their templates also, and the Ribbon sample apps (e.g. RibbonWindowSample.exe) set ClearTypeHint similarly in their XAML. IV. Example: Enable ClearType for body text of RibbonWindow While Ribbon is fully ClearType-enabled, an app using Ribbon must opt-in to ClearType for the Aero theme. To achieve this, we simply make sure RenderOptions.ClearTypeHint=“Enabled” is set wherever text is hosted. Examine the following XAML: <ribbon:RibbonWindow …> <Grid x:Name=”LayoutRoot” …> <ribbon:Ribbon x:Name=”Ribbon” … /> <Border Grid.Row=”1″> <StackPanel> <TextBlock Text=”ClearType ENABLED.” RenderOptions.ClearTypeHint=”Enabled”/> <TextBlock Text=”ClearType OFF.”/> </StackPanel> </Border> </Grid> </ribbon:RibbonWindow> Running this on Win7 Aero produces the following text rendering: Notice ClearType rendering in the top TextBlock, which opts in to ClearType. Besides the chromatic differences, from this screenshot it’s not immediately obvious what improvements ClearType brings to the table. Bear in mind that ClearType rendering creates an accumulative effect to improve general text crispness. Generally one should set RenderOptions.ClearTypeHint=“Enabled” at some root element, since the setting propagates down the visual tree unless another IRT (Intermediate Render Target, see next section) gets in the way. For example: <ribbon:RibbonWindow …> <Grid …> <ribbon:Ribbon …/> <Border Grid.Row=”1″ RenderOptions.ClearTypeHint=”Enabled”> <StackPanel> <TextBlock>My app</TextBlock> <Button Width=”Auto” HorizontalAlignment=”Left”>body has</Button> <Label>ClearType!</Label> </StackPanel> </Border> </Grid> </ribbon:RibbonWindow> Notice that we set ClearTypeHint=“Enabled” on the Border element below the Ribbon rather than on the parent Grid that contains everything. This was deliberate – the Ribbon’s quick access toolbar and title draw over the transparent glass at the top of the window, and setting ClearTypeHint=“Enabled” for text over transparent backgrounds may cause rendering issues. V. IRTs and ClearTypeHint IRT stands for Intermediate Render Target. An IRT is a common WPF graphics term used to refer to a surface that a tree of WPF visuals render to. Every separate visual tree (e.g. contents of a Popup in WPF) renders to a separate IRT. In addition, applying a Clip/Opacity to a Visual causes a new IRT to be generated. ClearTypeHint, when set, propagates to the subtree under that Visual that renders to the same IRT. If a descendant node in this subtree has a Clip applied to it or causes a new IRT to be created for another reason, it no longer honors the ClearTypeHint settings. These settings will need to be redefined on a Visual within the scope of this new IRT. A common instance where this behavior manifests is in the case of a ScrollContentPresenter of a ScrollViewer. A ScrollContentPresenter inherently clips the contents that are beyond the viewport. By doing so, it causes its contents to be rendered to a separate IRT. Now consider a RichTextBox hosted in the content pane of a RibbonWindow. A RichTextBox’s built-in template uses a ScrollViewer that contains a ScrollContentPresenter. Thus to turn on ClearType for text rendered within this ScrollContentPresenter, we must do two things: - Render an opaque Background within this ScrollContentPresenter. - Set ClearTypeHint=“Enabled” within the scope of this ScrollContentPresenter. The attached sample code demonstrates such usage. Similar techniques have been implemented in the RibbonControlsLibrary to enable ClearType for the various subcomponents within the Ribbon. For further reference, Lester Lobo’s blog discusses IRTs and when to use ClearTypeHint in WPF. VI. Determining if text is rendering as ClearType As seen in this article’s screenshots, text rendering as ClearType has red and blue hues since glyphs cut across subpixel boundaries. It can be difficult to verify ClearType rendering at normal resolution, so we use a magnification technique to zoom in. Windows ships with a magnifier accessibility tool we can launch from the Start Menu: When you magnify 800%-1000%, you can readily see the ClearType effect. The magnifier’s Full screen mode works great on Aero but isn’t available on other themes, so I often use MSPaint to magnify screenshots on non-Aero themes. VII. Conditional Compilation of ClearType for .NET 4.0 ClearType is only available in .NET 4.0, but some WPF apps and custom controls may want to support both .NET 3.5 and 4.0, lighting up with ClearType on .NET 4.0. To support both platforms from a single codebase, some conditional compilation is required. Ribbon itself requires conditional compilation. The Microsoft Ribbon for WPF Source and Samples MSI includes a perl script that pushes XAML files for the Ribbon sample apps through the C preprocessor to create separate 3.5 and 4.0 XAML. The 4.0 XAML has ClearTypeHint specified in several control templates, and #ifdef directives in the XAML direct the conditional compilation. VIII. Sample Code & Related Links Sample Code for this article is attached. - Microsoft Ribbon for WPF – Download the WPF team’s Ribbon release, a managed Ribbon implementation. - Downloading the Ribbon MSI is necessary to run this article’s samples. You can also download the Ribbon Source & Samples MSI from here. RibbonClearTypeSamples.zip Join the conversationAdd Comment Patrick, thank you!!! I beat my head against this wall for awhile last week. I sprinkled that ClearTypeHint all over my XAML and got ClearType to work in every place in my app except the one place I really wanted it: the caption text underneath image thumbnails for items in a ListBox control. Space is at a premium here and this text needs to be as clear as possible. The DataTemplate for these items consists of a Border containing a few Grids, an Image, and a TextBlock. The ListBox control uses a WrapPanel to get the kind of layout you see in say, large icon view in Explorer. Then the ListBox is inside a Grid which is inside a DataTemplate for a TabItem of a TabControl which is inside a Grid and so on. It turned out the key piece I was missing was setting a solid background color. If I add Background="White" to the Border of the item's DataTemplate or just the TextBlock itself, then ClearTypeHint actually takes effect for the text inside. I hadn't specified any background before so it wasn't like I'd gone out of my way to do some transparent background. This tip about setting an opaque background is really key. I'd read about this issue elsewhere before finding your blog post, but I didn't see this one crucial bit of information. Now I've got to make sure the background is only set when the item is not selected so it doesn't screw up the item's appearance when selected, but I can work that out. This is really a nasty bit of low level detail that the platform should be taking care of automatically. Failing that, it would be nice if ClearTypeHint would just work regardless of where you put it or whether or not an opaque background has been set. Failing that, there should probably be an error in the debug output or something if what was requested by ClearTypeHint was not possible because of these implementation details. Finally, the documentation for ClearTypeHint should be improved to have the level of detail you have in this blog post – especially the tip about the opaque background. I realize this problem is a tricky one that hasn't come up until well after WPF was written, and we're probably lucky to have ClearTypeHint at all. I hope you guys can improve this in a future version of WPF though. Otherwise there's probably going to be an awful lot of grayscale anti-aliasing going on out there. (Not disastrous, but just another thing setting WPF apps apart.. not in a good way.) Now if I could just get the text for some of these items to stop randomly blurring when I try to use cached composition, I'd be golden! @Tom I'm glad you found this post helpful. Thanks for the detailed feedback about ClearTypeHint! It can be tricky to know exactly where it needs to be used, and writing this post was a learning experience for me. Looking at the RenderOptions.ClearTypeHint documentation, I did find this line about using an opaque background under the Remarks section: "Assign an opaque background that is as close as possible in the visual tree to the text." I'll make sure the PM leads and the graphics team see your feedback on ClearTypeHint. I was talking to Rob Relyea & Troy Martez about ClearType in WPF yesterday, and we would indeed like to get better default ClearType behavior in WPF. Thanks. WOW Great post. I've been trying to get ClearType work for the last couple of days. It's a pain I must say. This post helped me a lot. I have found ClearType to be very inconsistent in RibbonWindow. 1) When I enabled UseLayoutRounding in Ribbon, some of the RibbonTab Headers went to Greyscale Cleartype. 2) I can't get Cleartype to work in a listView that uses a VirtualizingStackPanel. 3) Simple Textboxes and Buttons are also reveting to Greyscale Cleartype. I just can't get these work properly. In concluion: it still needs a lot of work. Patrick, thanks again, that's good to hear. I double checked the docs and you're right of course, it's right there in plain sight and seems familiar enough. Not sure how I missed it before, sorry about that! By the way, there's also a note there that says "On many controls, the ClearTypeHint attached property has no effect unless you set a non-opaque background behind the text." I wonder if this should say "opaque" instead of "non-opaque". @James – Glad you found this helpful! Agreed, enabling ClearType in RibbonWindow is a pain because ClearType rendering is turned off for RibbonWindow's entire tree by default and one must set ClearTypeHint="Enabled" every time the tree branches into a new IRT. This is certainly a subpar experience that we would like to improve upon (ideally getting the expected ClearType experience by default for RibbonWindow). #1 – I tried setting Ribbon.UseLayoutRounding, but still saw the RibbonTabHeaders render in ClearType. Are you styling them or setting clip or Background in a way that would affect ClearType rendering? I'm happy to take a look if you have a repro or more detailed repro steps. #2 – I was able to get ClearType in a ListView that uses VirtualizingStackPanel. In ListView.ItemTemplate, I include a Border element with RenderOptions.ClearTypeHint="Enabled" and Background="White" (the same as the RibbonWindow), and with this I get clear type for the ListViewItems. You may want to try something similar. #3 – TextBox contains new IRTs in its tree but Button does not. Button should be able to inherit RenderOptions.ClearTypeHint. I'll check with our Text team about the best way to enable ClearType for TextBox since it seems tricky. I agree with your conclusion that work is needed here. We have filed a bug to investigate and improve customer experience for ClearType in RibbonWindow. @Tom – You're right, that note should say "opaque" instead of "non-opaque". Thanks, we'll get this fixed! @James I spoke to Varsha, and we have a good example of how to enable ClearType for TextBox family of controls in our RibbonWindowSample. TextBox has a ScrollViewer in its template that is an IRT. Basically, to enable ClearType for TextBox you restyle ScrollViewer and set ContentTemplate to include a Border element with an opaque background and RenderOptions.ClearTypeHint="Enabled". Look for this Style in the v4.0 UserControlWord.xaml. The default Style for RibbonTextBox also restyles ScrollViewer like this.
https://blogs.msdn.microsoft.com/wpf/2010/10/29/enabling-cleartype-for-ribbon-applications/
CC-MAIN-2017-34
refinedweb
2,640
65.22
Hello all, First of all I would like to state that I will maintain this topic as long as I can. I have intention to make this question a collection of up-to-date guidelines/resources that people can benefit from. The reason I'm not using Forum is people tend not to look forum posts and prefer to go with UA. If this post becomes too big, I'll create a forum post and give a link to it here. Now to the question, what is you own way to maintain your code base/project along with your team that will prevent it to be a complete mess on a large scale ? Or what needs to be done to be experienced in creating/maintaining a code base that will not be a mess on a large scale ? In order for everyone to benefit from your answer I recommend you to keep it as simple as possible and explain hows/whys of the reason. I will try to update this to make it easier to read. And try not to give theoretical or general answers like "separate your game logic and you will be fine" try to be specific, provide sources and/or sample code. Thanks. According to my findings; Design Patterns These are some generic code patterns that will help solve some specific problems that has been recognized in programming. For me, you should at least know what they do. You should also know that design patterns are not voodoo magic, they solve some problems but they may have some limitations or create other problems. A good source that explains design patterns in C# [] Explains game programming patterns(unfortunately in c++ but it's very explanatory) [] Some design patterns applied in unity [] Model-View-Controller(MVC) and it's Variations Very simply put, it's like seperating your project in to three parts. Model is only responsible from data part(CRUD)and nothing else(i.e. increasing/decreasing enemy health), View is responsible from representation(i.e. position of enemy, enemy health bar HUD), lastly Controller is the middle-man between Model and View. Passes information from Model to View and vice versa. Now the reason that I've written "it's Variations" in title is that I've seen many arguments about unity being a "component-based" engine and an MVC architecture falls into Object Oriented Programming style. And a lot of people disagrees with this notion with having strong reasons to disagree, you can look into it but nevertheless you should learn about MVC. There are lots of sources in web that explains MVC in not game-engine specific ways, you can look it up if you like but I will only give engine-specific sources. Good explanation of problem(s) and why you need MVC-like architecture(a variation of MVC). [] A bit more advanced version which is really good in my opinion. [] Note that MVC is also a framework but the reason I separated it from "Frameworks" section is that MVC is a starting point to the things I will list in "Frameworks" section. Frameworks Some of previous things + bunch of other things = framework. Frameworks are prepared to make things more standardized and clean with principles like Inversion of Control(IoC), Dependency Injection(DI) etc. If you don't know these terms, I suggest you to look them up. Entitas: Actively updated and maintained, free, Open-Source Entity-Component System Framework, created by Wooga[] also in Asset Store which will include more features in future but costs 45$ [] StrangeIoC: Free, Open-Source IoC framework, a good one but not updated for a long time [] also in Asset Store [] Zenject: Zenject is a lightweight highly performant dependency injection framework. Up to date and very performant. [] uFrame : MVVM Framework that comes with cool features like diagram engine but not maintained for a long time and I'm not sure if it works with Unity 5.6] also in Asset Store [] Probably one of the most important things is notations and summaries. I personally don't do this in my own projects, but that could be in part due to laziness. However, when reading someone elses code, it is very important to know what they were thinking at the time. No amount of standards and design patterns are going to make shotty code readable. Secondly, the MVC thing is relatively new in the software industry, and it is not a bad design pattern, but to effectively do that in game design, you would be looking at something like this. public class PlayerModel { public PlayerController controller; private int _health; private int _maxHealth; public int GetHealth() { return _health; } public int GetMaxHealth() { return _maxHealth; } public void Remove(int amount) { if (_health -= amount < 1) { controller.PlayerDies(); _health = 0; } controller.UpdateHealth(); } } then public class PlayerController { public PlayerModel playerModel; public PlayerView playerView; public void AdjustHealth(int amount) { playerModel.RemoveHealth(amount); } public void UpdateHealth() { playerView.SetHealthBar(Mathf.InverseLerp(0, playerModel.GetMaxHealth(), playerModel.GetHealth())); } } and public class PlayerView { public Image HealthBar; SetHealthBar(float percent) { HealthBar.fillAmount = percent; } } As you can see, this does indeed work nicely and look clean, but is it actually necessary? No. It is usually used in large companies for when the code structure is so large, that no single person knows every file. So they split every concept into 3 ideas so that editing it becomes easier. However, I personally prefer Model-ViewControl, meaning the Model is the data, and the ViewControl is the view and the controller. It might be personal preference, but a lot of the coding design patterns are meant for large companies to keep things organized, in a smaller company this sort of organization can actually do the reverse, and over-complicate what may have been a simple thing to begin with. Hey @RobAnthem, thank you for your contribution. I agree about notions and summaries, but I'd like to make an addition here. You will be a stranger to your own code after 1 week. I personally try to make it a practice of "if you can't read the code like English, add comments". Sometimes it might feel redundant to add comments, but when you done working with that class and you came back to that class after couple of days, it will take a lot more of your time than commenting it. Also sometimes you do complicated things and might get confused. Commenting it greatly helps you grasp what's going on exactly. And about MVC, most of the things I wrote up there is mainly focused on keeping things clean and separated team-wise so people will not interfere with each other. But also, MVC can help you store your codes for later use. Perhaps you would like to make a series of games that are about, lets say idle clickers. You want different implementations in each game but base mentality is the same. If you work with MVC this way, you will save a lot of time. Or, you want to have an inventory system in the game, if you make it as generic as possible, you could use it in any project that requires inventory system(who doesn't need a good inventory system, right?). I think it is necessary for a lot of developers to learn this kind of stuff if they would like to work in this industry in a professional scale. before i comment, I will say this is place for people to get specific answers to specific questions. and i'm surprised this question got past our moderation. but since it did, I will through my honest opinions out here for once. Contrary to other types of programming or wherever your programming background might be from, I believe coding in game development is an art form. No different than the people creating music and meshes and textures and concepts for a game. coding formats should allow for creative systems and formats in coding. originally is the only thing that keeps the indie game industry alive among the larger companies. if you are working with other programmers my advise is to use as many comments in your code as you have to. unless you are relying on asset stores. at somepoint you will be forced out of the box to achieve a full featured game. video game programming is just different than other programming like that. I will say many programmer personalitys might disagree with me on this opinion. but i am good at what i do and thought i would share my style. While I do agree that game programming is a lot more of an art than basic programming, as we are not only solving more complex issues than software developers, but we are creating these complex issues as we go. Also I'd like to put my two cents in here, I don't think anyone should be making games if they either A. aren't a programmer, or B. don't have one on their team. No amount of prepackaged solutions will give you what you want, and worse yet, the more pre-made code assets you purchase, the harder it becomes to integrate them. Hell I remember when I first started in this industry, and thought I could do it without coding, I spent a lot of money on assets that I now consider to be useless pieces of garbage. Frameworks, project templates, and so many other things that I would rather just code myself. I know a lot of devs say that you should always search for libraries that will cover aspects of what you are doing so you don't have to, but the way I see it, if it takes me close to the amount of time to write the library as it does for me to learn/integrate it, then I should just write it. So I really only use libraries like Math, Noise, Networking, etc, and would rather make my own for everything else. As I'm sure you are aware @toddisarockstar once you understood programming as a whole, creating any kind of solution is relatively easy. I understand peoples desire to want an easy solution, and it is of course more cost effective to spend $100 on a framework that may take a dev like us to build in a week or two, but as we all know, you will quickly find that framework doesn't do everything you want it to, and trying to add implementations onto it may be much more effort than you want. As well, it screws the entire "coding standard" if the pre-packaged asset is using a different standard. Personally I like the C# standards, and I really wish Unity devs would stop using the C++ standards of using _variableName and m_variableName, mostly because they are ugly to look at lol. I like my art to be appealing :P Here is a link to Insomniac games core coding standards, something that is generally useful for game development, and just development in general: hopefully you find it useful. Answer by Eicher · May 21, 2017 at 03:45 PM Hi, only a few points from my side (not just Unity specific, but for coding projects in general). If you work in a team, take a few minutes at the start of the project to decide on common code conventions Use a source control tool (like Git) for managing your Code (maybe not the binary data and .meta files from Unity - I don't know what a good source control approach for binary files would be) Keep your code readable and understandable. That means for example, that a function should only do what the name is indicating. Have clear conventions for variable names etc. Avoid to make many comments. It is very likely that if you or someone else of your team is rewriting a function, they will not update the comment describing the function etc. If possible, express what your code is doing via the variable and function names. Write tests for your code: Now I do not have any experience for Unity specific tests. But if you have static functions or regular classes, for example, it should not be hard to write some Unit tests for them. This way you can ensure that you see it immediately if some new code breaks your current code if you execute the tests. Have as few dependencies as possible in a class. Communicate with other classes over interfaces. Let me explain: Say for example you have a class "CustomPlayer" in your project. Many other classes store a CustomPlayer instance and maybe call a function on the class or retrieve values from the class. If later in the development, you decide to change or rewrite your CustomPlayer class because some features you planned would not work with the current implementation of the CustomPlayer class, the changes are high that you break the code of other classes that are referencing the CustomPlayer class. Use an interface instead, so that you have no hard dependencies to the CustomPlayer class. Also, design patterns like Dependency injection and interface driven design makes it much easier to test your classes (Test frameworks allow you to write a "mock" that is used as referenced interface of a class you are testing. You can tell the mock how to behave when the test class calls specific functions on the mocked interface. For example, what return value should a function have if you call it with certain argument values). If you have no interface driven design and many dependencies, it would be pretty hard to test your code I suppose. I agree with separating data classes from functionality classes. A good book for writing maintainable code is "Clean Code: A Handbook of Agile Software Craftsmanship" by Robert C. Martin. The examples in the book are written in Java, so they should not be too hard to understand if you already know how to code in C# Cool input, thanks! Didn't look at that angle about commenting codes, makes sense. Also it would be great for new people here if you could provide an example about the importance of using interface. Also for Unit Testing, a lot people doesn't know Unity Test Tools. It's a good tool to make unit tests. About using Interfaces, I stated in my answer that it is beneficial for a class to have as few direct dependencies to other classes as possible. Using interfaces as suggested by the Dependency Injection design pattern is also very important if you want to write Unit tests for your classes. I looked up a quick example that gives an introduction on Dependency Injection. This may not have the best explanation, but it shows the concept with C# code: Also, I would like to recite the section abou the usefulness of DI (dependency injection): "Even after a demonstration of how to use DI, you still might wonder why it is useful. Two answers are that it is useful for unit testing, validation and exception management. Unit Testing. Unit testing, or white box testing, tests a unit of work (often, this is a method). The assumption is that the developer writes the tests because it is the developer who knows the implementation details of what is being tested. A proper unit test can run without any reliance on external dependencies. DI enables you to replace complex dependencies, such as databases, with mocked implementations of those dependencies. This allows you to completely isolate the code that is being testing. For more information about unit testing in WCF, see. Validation/Exception Management. DI allows you to inject additional code between the dependencies. For example, it is possible to inject exception management logic or validation logic, which means that the developer no longer needs to write this logic for every class. For more information about how to use DI for validation and exception management, see." Answer by McLoud · May 24, 2017 at 07:40 AM Also take a look to Entity-Component-System and use class diagram to design the code. I Like NCode, wich is free. Answer by Nocktion · Feb 01, 2019 at 09:23 PM I use something similar to MVC and ECS. I created a system that uses three types of classes. Data Data classes contain pure data and they are mostly ScriptableObjects to make simple presets (e. G.: items, world generation presets, etc..). The other type of Data class inherits directly from object and their primary purpose is to make instances of scriptable objects with additional functionalities and methods. Functionality Functionality classes do all the calculations and contain all the functionalities that your project will include. However it does not interact with "physical" parts of the system. It's entirely for handling functionalities. PhysRep (Physical Representation) PhysRep classes link functionalities with GameObjects. Theese are the only class types in the system that inherits from MonoBehaviour and therefore must be added to GameObjects as Components. They contain a few static variables, so you will be able to handle a few things from Functionality classes. These PhysRep classes are mostly singletons. So this is my system design that works pretty well. It organizes the codes and also has some performance benefits. Sounds actually very interesting. Do you have any link to a repo with an example? Would love to see it in action. @Nock 331 People are following this question. Notifying about character/item selection 1 Answer make a system for me 0 Answers Is DateTime working on iOS? 0 Answers How can I make a patch system for my game? 0 Answers Sharing Variables Between Projects 3 Answers
https://answers.unity.com/questions/1354956/what-are-the-best-practices-of-designing-code-arch.html
CC-MAIN-2020-29
refinedweb
2,944
60.65
Hi all, my first time posting here. I’m looking forward to interacting with everyone. So, I’m working on my game for exercise 36. I’m coming up on the end of it, and wanted to share with a few questions/concerns: -I feel like the game is more text-intensive than code-intensive. While it was amusing to write, I’m wondering what kind of ideas you might have for increasing the complexity of the code and structure -I initially wanted to use the car() function as something reusable (basically any time you move between locations), but then I realized I didn’t know how to soft code it so it could wind you up at somewhere other than hotel() -I like that I have the global DIPL, yuan, and list, and that I have an object always being passed between functions, but with the list especially, I just don’t know how to integrate it more into the game -The last room or two I want to turn into a kind of classic battle with the final boss, using DIPL as HP. No idea how to do that yet; I’m still looking into how to make weapons, give them strength, use random codes to determine success of strikes, etc. If anyone can point me to somewhere I can read up on that, I’d appreciate it! Here goes (I hope this pastes in properly): import random DIPL = 0 INV = [] yuan = 10000 def check(DIPL): if DIPL >= 1000: print("Diplomacy: ", DIPL) print("You win! You collected: ") print(INV) exit(0) elif DIPL < 1000: print("Diplomacy: ", DIPL) return else: exit(0) #def znh1(obj): def zhongnanhai(obj): global DIPL global yuan check(DIPL) input() print("""As the car pulls through the front gate, two stoic guards in green PLA uniforms posted on pedestals on either side, the door next to you clicks unlocked. You get out and the car backs away, the gate slamming shut.""") input() print("""Green tiled roofs over rust red walls stretch in all directions around you: countless, identical rooms. Nobody is around, nothing moves. You realize the twenty closest rooms have numbers posted over the doors, so you decide to try one of them.""") while True: room = input("> ") if room == "1": print("Empty, dusty, cobwebs and broken tiles. Very CCP.") elif room == "2": print("""Rows and rows of broken stone lions, the balls removed from their mouths. A repository of entrances past.""") elif room == "3": print("""The walls are papered with yellowing posters of Mao. Listen to the Party, do what the Chairman says. Happy, happy, happy. See how much grain we have? We never go hungry.""") elif room == "4": print("""A young woman, hair unwashed, sits at a rickety desk littered with paper, red kerchiefs in cheap plastic envelopes, and a yellowing, cold cup of tea. She is staring at her phone intensely and does not seem to notice you. You take a kerchief before leaving.""") INV.append("red kerchief") DIPL = DIPL + 2 elif room == "5": print("""This room is full of sound which, oddly, you couldn't hear at all before you entered the door. Staticky speakers, enthusiastic but weirdly monotone shouting, barked syllables. It is mollifying, frightening, and obnoxious all at the same time.""") elif room == "6": print("""This is some sort of camera workshop. Dozens of children sit crosslegged, holding screwdrivers from eyeglass repair kits, determinedly assembling and disassembling "public security" cameras into their consituent thousands of parts. One of them looks at you before standing up, angrily, the screwdriver held like a weapon. It sounds like he says "America" as he walks toward you, barefoot. You make like a tree.""") DIPL = DIPL - 1 elif room == "7": print("""Instant cloud of cigarette smoke. Goons, a mah jongg game. One of them stands up, a thick rope of gold around his neck, and you feel a flash of pain in the back of your head...""") DIPL = DIPL - 7 input() wake(obj) elif room == "8": print("""You remember reading that 8 is a lucky number for Chinese. Unforunately, the same is not true for you. A woman sits at a plastic desk and starts handing you forms, yelling "sign, sign!" and chopping them with her stamp. "Money, money!" She indicates values on the forms with aggressive finger jabs: 150 yuan, 75 yuan, 83 yuan. Death by a thousand cuts. Pay up, bud.""") yuan = (yuan - 150 - 75 - 83) elif room == "9": print("""The number 9 is a pun in Chinese--it means long. They like to say it alludes to how long one will live, but in this case it is for how long the "line" is. This room is packed with people, crowding a desk at the back of the room that you can barely see, with no semblance of order. Getting there is a long, long ways away.""") DIPL = DIPL - 2 elif room == "10" and "red kerchief" in INV: print("""A steely guard stands blocking a door, but when he sees your red kerchief, he steps aside.""") znh1(obj) elif room == "10": print("A steely guard stands blocking a door, staring you down.") elif room == "11": print("""A round table crowded with cards, peanut shells, bottles of beer, cigarette butts. Rowdy, pink-faced, mid-level CPC placeholders wave you over, jolly, loud. You drink with them, many back pats are exchanged. Long discourses are given, none of which you understand.""") DIPL = DIPL + 40 elif room == "12": print("""An empty room. You'd think they would be more efficient with their real estate, right?""") elif room == "13": print("A pile of coats on the floor.") INV.append("random coat") elif room == "14": print("There's a... there's a bunch of bicycles in here?") elif room == "15": print("""You see an array of television screens long the walls. On each is playing, on loop, recordings... of you. Recordings of you coming out of the airport, you walking through the lobby of your hotel, and you, standing in room 15, watching recordings of you.""") DIPL = DIPL + 15 elif room == "16": print("""\"Mister! Mister!" That voice again. You feel a pair of hands on your back, sliding around to your stomach.""") input() if obj == "fake passport": print("""\"I'm so sorry mister, I meant to give this back." You feel your passport slide into your pocket. So it was her! When you turn around to look, though, nobody is there.""") ") if tip.isdigit(): if int(tip) in range (0, 100): print(f"""She lowers her hand, leaving the {tip} yuan dangling from your fingers, and goes back into the hotel, the tight jacket sliding against her back.""") DIPL = DIPL + 1 yuan = yuan - int(tip) input() zhongnanhai(obj) elif int(tip) in range(100, 1001): print(f"""She takes the {tip} yuan from you without saying a word, turns, and goes back into the hotel.""") DIPL = DIPL + 2 yuan = yuan - int(tip) input() zhongnanhai(obj) else: print(f"""Smooth move. She takes the {tip} yuan from you and presses a small paper into your hand, then turns and walks back into the hotel. When you look at the paper, you see it's a note with "<3" and a phone number written on it.""") DIPL = DIPL + 3 yuan = yuan - int(tip) INV.append("<3 note") input() zhongnanhai(obj) else: print("""She stares at you long and hard before turning slowly and going back into the hotel.""") DIPL = DIPL + 2 input() zhongnanhai(obj) def hotel(obj): global DIPL global yuan check(DIPL) input() print("""As you finally walk through the brass-rimmed glass doors of your hotel, a sense of calm envelops you. Nearly 24 hours after departing, you will finally get some rest. A high-gloss, white marble floor stretches between you and the mahogany, gold filmaneted front desk. Elegant, hardwood tables flank either side of the lobby.""") input() print("""You approach the desk, your footsteps ricocheting from the walls. A tight-suited, perfectly made up young woman seems to rise from nowhere. You reach in your pocket to take your passport and slide it across the gleaming surface of the desk. She pulls it toward herself with a leather-gloved hand and flips it open to the first page.""") input() if obj == "fake passport": print("""She then pages slowly through the whole booklet, picking it up, with a slight frown flickering across her face. "Sir, we can only accept genuine documents.\"""") INV.append("fake passport") input() print("""Damn! Either that girl, or someone on the subway switched out your passport. You see a bellboy, with a very large head and no neck, walking menacingly toward you. You then remember the 10,000 yuan your boss gave you. How much do you give her?""") bribe = input("> ") if bribe.isdigit(): if int(bribe) in range(0, 2001): print("""No good, no good my friend. You'd better study exchange rates. Though, the only exchange you're going to be doing for a while is converting number of punches to days of pain.""") DIPL = DIPL - 25 yuan = yuan - int(bribe) ") while True: if "yes" in react and not fed: print("""You manage to break free and run back down the stairs, frustrated cries of "Mister!" getting fainter behind you. In the alleys, steam drifts from stacks of bamboo bun trays and salted pork legs hang from the bars on windows. Eventually, you get a taxi back to your hotel.""") DIPL = DIPL - 1 fed = False input() hotel(obj) elif "no" in react or fed: print(f"""She guides you to the bed, and what you thought was going to happen, happens. As you clean up, she looks at you sheepishly: "Mister, I'm sorry." She squats on the floor to take a {obj} from your pants pocket (when did she switch your passport??) and gives you your real, but still damaged, passport back.""") input() print(""""Mister, I hope I can help you more in the future." She walks with you downstairs and through the alleys, steam drifting from stacks of bamboo bun trays and salted pork legs hanging from the bars on windows. Eventually, you get to a street where she finds you a taxi to your hotel.""") DIPL = DIPL + 6 fed = True input() hotel("damaged passport") else: print("It doesn't matter.") fed = True DIPL = DIPL -4 input() def subway(obj): global DIPL check(DIPL) input() print("""Three cars pass before you're able to board. Thirty grannies cut in front of you... three hundred? The shouting is unbearable. There are no seats, no space to bend your knees to sit if there were. An hour later, you're swept off, swept up the stairs to the street.""") DIPL = DIPL - 2 input() hotel(obj) def subway2(obj): global DIPL check(DIPL) input() print("""She takes you to the subway, an unbearable crush of people. There are no seats, no space to bend your knees to sit if there were. She holds your arm the whole time, her fingers sweaty, grip loosening.""") print("Do you stay with her or escape?") failtry = False choice = input("> ") while True: if "stay" in choice or failtry: print("""An hour later, she leads you off the car. You take a dark, narrow stairway at the back of the subway station, emerging in some kind of alley.""") DIPL = DIPL + 1 input() seedyhotel(obj) elif "escape" in choice and not failtry: print("""You squirm away just as the doors are about to close, onto the platform, alone. Ahem, not at all alone, but without her. You fish in your pocket and still have the Beijing subway map... Sanlitun. Sanlitun. You find the line and push into the crowd.""") print("""Three cars pass before you're able to board, but finally you do. An hour later, you're swept off, swept up the stairs to the street.""") DIPL = DIPL + 4 input() hotel(obj) else: print("Nothing works, nothing would work, she's alert, eyes jumpy.") DIPL = DIPL + 2 failtry = True input() def car(obj): global DIPL check(DIPL) input() print(f"""The driver throws your {obj} into the trunk with a crash. You hear it banging around as he drives. Races? You feel a little sick.""") INV.append(f"{obj}") speak = input("> ") if "please" in speak: print("The bastard speeds up, and you puke on yourself for the rest of the ride.") print(f"""He screeches up to the front door of your hotel and you find yourself on the curb with your {obj} on the ground, not feeling so hot.""") DIPL = DIPL - 5 input() hotel(obj) else: print(f"""He ignores you, screeching up to your hotel. You find yourself left on the curb with your {obj} on the ground, not feeling so hot.""") DIPL = DIPL - 1 input() hotel(obj) def alone(obj): global DIPL check(DIPL) input() print("""As you walk away from the crush, the voices seem to muffle into the smog. There is still a steady flow of passengers passing in all directions around you, but it somehow feels lonlier. Quieter. Just as you start to notice the concrete tiles of the walkway are loose, some cracked, some missing, you hear a voice: "Mister!""") print("""You're standing at the sliding door of some forgotten corner of the airport, the sound of oversized heels clacking toward you. "Mister!" Do you turn around or go through the door?""") react = input("> ") if "turn" in react: print("""You turn to see a young woman running toward you. She's wearing a black bra, white shirt with the hem high above her belly button, with bleached orange hair and cutoff jeans shorts so tiny the pockets flap outside of them.""") input() print(""""Mister," as she grabs your arm, her fingers surprisingly strong, "come with me.\"""") DIPL = DIPL + 8 input() subway2("fake passport") elif "door" in react: print("""You slip inside the door, a blast of dank, air conditioned air hitting your face. You realize it's the entrance to the subway. You fish in your pocket and still have the Beijing subway map... Sanlitun. Sanlitun. You find the line, drop a coin in the meter, and push into the crowd.""") DIPL = DIPL + 3 input() subway(obj) else: print("""Her voice suddenly stops, but when you turn back around, you can't find the door. Just then a taxi pulls up and the driver waves at you, so you get inside.""") DIPL= DIPL + 2 input() car(obj) def start(): global DIPL print("""You see a brown haze slide past the window of the plane as the landing gear grinds lower. Slowly, the patches of remaining hutong, willow trees, and crowded bicycles that are signatures of the Beijing streets grow visible below through the grime.""") print("""As the plane lands, and while it taxis, the people around you unbuckle their seatbelts and begin to stand, pulling luggage from the overhead compartments.""") print("""After hours of being jostled and pushed while waiting in line at customs, and after being shouted at by an immigration officer who refuses to recognize your diplomatic passport, you are let into the country. Standing outside the gate is a Chinese man playing on his mobile phone and holding a placard with your name. Nobody told you he would be picking you up; what do you do?""") outside = False choose = input("> ") while True: if "ask" in choose and not outside: print("""Without speaking or looking at you, he turns around and begins to walk. You grab your luggage, pushing through the constant crowd to hurry after him.""") DIPL = DIPL + 1 outside = True input() car("luggage") elif "out" in choose or outside: print("""Outside the airport, a swarm of taxi drivers surrounds you. In the push and pull, your luggage is twisted from your grasp. Even your passport, which you were still holding in your hand, is almost taken, but you manage to hold onto it.""") DIPL = DIPL - 5 outside = True input() alone("damaged passport") else: print("""Jet lag is sinking in. You wander through endless halls at the airport, bumped and pushed, until you suddenly find yourself outside.""") outside = True input() start()
https://forum.learncodethehardway.com/t/ex36-game-complexity-and-questions/4890
CC-MAIN-2020-45
refinedweb
2,667
80.72
Scripts from Notepad++ do not run in Python/Jupyter 3.5(already read prior help discussions) My Python scripts from Notepad++ do not run in Python/Jupyter 3.5. I have a 64 bit operating system and installed the appropriate version of Python. On the prior help discussions it was suggested that one install the NppExport Plugin which was installed automatically with the current version of notepad++. It also was suggested that this command be placed in the run box within notepad: cmd /K “D:\Program Files (x86)\Python\python.exe” “$(FULL_CURRENT_PATH)” I also tried placing this command in the run box in notepad: cmd /K D:\Python35\python.exe -i -c “execfile(‘$(FULL_CURRENT_PATH)’)”. When I run both of the above commands it opens up a black python window with the following message: The device is not ready and the next line gives me a command prompt with C:\Program Files (X86)\Notepad++>. On the upper menu bar it has Select C:\Windows\ System32\cmd.exe. It doesn’t import the notepad script into python or run it. It is unclear to me how to fix this as I have python open at the time so it looks ready to me. I also haven’t seen this error message in the prior help requests on this forum. Please help me fix this. Thank you. it isn’t the NppExport but the NppExec plugin. $(FULL_CURRENT_PATH) evaluates to the file path only if the current document has been saved already otherwise it would return something like new … which of course cannot be found. Concerning your call cmd /K D:\Python35\python.exe -i -c “execfile(‘$(FULL_CURRENT_PATH)’)" You normally would do it rather like this cmd /K D:\Python35\python.exe -i "$(FULL_CURRENT_PATH)" Cheers Claudia Thank you very much for the help but I am still getting the same response from Python (it opens the black python window with the following message: The device is not ready) after I followed your instructions of installing the NppExec plugin and placing this command in the run bar of notebook: cmd /K D:\Python35\python.exe -i “$(FULL_CURRENT_PATH)”. Do you know how to fix this? Scott OK - step by step. - right-click on the tab of your current script and select Full File Path to Clipboard - open a cmd - type in **cmd /K D:\Python35\python.exe -i ** and paste the content of the clipboard - enter does this work? What exactly happens? If you installed nppexec - press F6 Does the nppexec dialog open? Cheers Claudia Note, type in **cmd /K D:\Python35\python.exe -i ** and paste the content of the clipboard without the asteriks of course. Cheers Claudia Thank you again for the help. However it still doesn’t work. If I press f6 then a dialogue box opens that contains my scripts from the page. When I click ok for this to execute it opens a box at the bottom of the page that contains an endless loop of error messages. This script is from a university course so shouldn’t have this output. Do you know how to fix this? Scott. But then it means that you did not install python to D:\python35, didn’t you? . When I click ok for this to execute it opens a box at the bottom of the page that contains an endless loop of error messages. Which error is it? Cheers Claudia Good point Claudia. When I installed Python through the Anaconda program it saved it to C:\Users\myname\Anaconda3. The error messages that I get at the bottom of the page when I run this script in the nppexec dialog box is: “CreateProcess() failed with error code 2: The system cannot find the file specified.” Do you know how to fix this? Thank you very much for the help Scott depends what exactly is used in nppexec dialog. Normally something like this cd C:\Users\myname\Anaconda3\ python "$FULL_CURRENT_PATH” Cheers Claudia I greatly appreciate all of your help and patience but still cannot get it to work. Scott Scott, you need to be more descriptive what you get and/or what isn’t working. Maybe include a Screenshot (upload to e.g imgur) and use the syntax like to embed it in a post. Cheers Claudia In the run box in notepad++ I have placed the following commands: - cd C:\Users\myname\Anaconda3\python "$FULL_CURRENT_PATH” - cmd /K C:\Users\myname\Anaconda3\python.exe -i “$(FULL_CURRENT_PATH)” - cmd /K C:\Users\myname\Anaconda3\python "$FULL_CURRENT_PATH” - cmd /K C:\Users\myname\Anaconda3\python "$(FULL_CURRENT_PATH)” On all 4 of these tries python opened up with a message stating “the system cannot find the path specified.” I would greatly appreciate it if you have any additional suggestions on how to get this to work. Scott Sorry, you cannot get the same error message on all 4 runs. The message “the system CANNOT find the path specified.” is descriptive isn’t it. I start thinking you are trolling. Cheers Claudia Your right. 1. from above doesn’t give me the same output as the others but just shows “run…” in the dialogue box. It was sloppy of me to post that. I am a novice at programming, not a troll. I am trying to learn programming. I can understand if you run out of patience trying to help me with this as the amount of times that I have tried to fix this is also trying my patience. I did not plan on spending since yesterday trying to get notepad++ to communicate with python but rather to learn how to use python. Can you suggest any basic resources that I can look at to learn how to fix this? Thanks for all of your help Scott Scott, we can get this work in maybe 2-3 posts if you would describe step by step what you do instead of writing “I did what you do”, because any slight modification could break it. What do you want to do? I assume you want to run python with the current script you have open with notepad++. What do you use to execute the script? I assume you use the Run dialog from the run menu and not the nppexec plugin. I would suggest you use the nppexec plugin. - Find out where your python.exe is located. We need to know the directory. - Press F6 to open the nppexec dialog - put the the following into the dialog opened by pressing F6 cd PATH_OF_THE_DIRECTORY_WHERE_YOUR_PYTHON_EXE_IS python "$(FULL_CURRENT_PATH)" - Press ok A console opens and either shows the expected result or an error. If an error appears copy it and post it then we see what is going on. Do not interpret it - copy the real output. If there is sensitive data in it - replace it with question marks - but only that part. Cheers Claudia @scott-grossberg as you are a beginner, I suggest you to remove Anaconda and install the official python Here is my solution. - uninstall anaconda - install python 3.6 in c:\python36 - do an “hello world” script to test 4 append to the end of script os.system(“pause”) in order to pause your script and be able to read the result import os print("Hello World") os.system("pause") 5 run your script with “notepad++ run” command C:\python36\python.exe "$(FULL_CURRENT_PATH)" Here is what i got screenshot @scott-grossberg any news ? I followed your suggestion of removing anaconda and installing python directly and I can run notepad++ scripts in python (I tested this with the hello world program). Unfortunately the class that I am using this for has extra formatting in the scripts since they were saved as a python notebook. Therefore I get an error message when I try to run these scripts with notepad++ with my current set up. This is the error message: C:\Anaconda\python.exe “C:\Users\scott grossberg\Downloads\controlflow_demo_test” Process started >>> Traceback (most recent call last): File “C:\Users\scott grossberg\Downloads\controlflow_demo_test”, line 21, in <module> “execution_count”: null, NameError: name ‘null’ is not defined <<< Process finished. (Exit code 1) I placed the command below into the run box (I saved Anaconda to C:\Anaconda) as well as within the box when I hit the f6 key and it successfully runs the hello world program above in python and the lower console box respectively: C:\Anaconda\python.exe “$(FULL_CURRENT_PATH)” Do you know how I can get the notepad++ script to run in the jupyter notebook? Thank you very much for the help. Scott Thank you very much for the help.================ READY ================ I should have mentioned in the above post that after I successfully installed and tested the notepad++ and the python 3.6 integration I removed python 3.6 and re-installed Anaconda. I did this to try to get notepad++ to run the scripts in the python notebook rather than directly on python. I greatly appreciate all of your help. Scott Scott Sorry I don’t know Jupiter and I didn’t understood your issue.
https://notepad-plus-plus.org/community/topic/13157/scripts-from-notepad-do-not-run-in-python-jupyter-3-5-already-read-prior-help-discussions/6
CC-MAIN-2018-39
refinedweb
1,502
73.27
27 August 2009 21:49 [Source: ICIS news] WASHINGTON (ICIS news)--The EU programme for the registration, evaluation and authorisation of chemicals (REACH) will cost six times more and need 20 times more test animals than projected, and thus it cannot be completed on time, two European scientists said in a study made available on Thursday. In research done at and funded by Johns Hopkins University in Baltimore, Maryland, toxicologist Thomas Hartung of Germany and chemist Costanza Rovida of Italy said that animal testing of substances registered under REACH will cost $13.6bn (€9.5bn) over the next ten years, rather than the $2.3bn estimated by the EU when the programme was drafted. Hartung and Rovida also contend that instead of requiring some 2.6m vertebrate animals to complete REACH testing, some 54m animals will be needed. The study authors said that their estimates of much greater financial costs and test animal requirements are based on an analysis that uses a best-case scenario and the most optimistic assumptions. The actual costs, both in terms of financial burden and the number of lab animals needed, could well be much higher, they said. Noting that they both support the aims of REACH, Hartung and Rovida contend that EU legislators badly underestimated the scale of the testing challenge. They said that when REACH was negotiated in 2001-2005, “it was expected that 27,000 companies would submit 180,000 pre-registrations on 29,000 substances”. “Instead, some 65,000 companies made more than 2.7m pre-registrations for in excess of 140,000 substances,” they said, citing data from the European Chemicals Agency (ECHA). The authors said that several factors contributed to the EU’s underestimation of costs and testing requirements. They said the EU relied on chemical production data from 1991-1994, but the European chemicals industry has grown by about 5% annually since 1994, almost doubling production and sales by 2008. In addition, they note that in 1994 the EU had 12 member nations, but it now contains 27 states - plus three non-EU countries - that will adhere to REACH. They said that the final REACH programme also requires more animal testing - such as second-generation evaluations - than first envisioned. The study said that ?xml:namespace> To meet the testing and cost requirements of REACH, each year over the next decade the EU will require 60 times more lab animals (5.4m) at costs 16 times higher ($1.4bn) than current annual expenditures, the study suggests. “The feasibility of the [REACH] programme is under threat,” the study said. The authors recommend that REACH be refocused to concentrate on chemicals that pose the greatest risk to consumers and that the deadline for completing data collection be pushed beyond the current 2018 target date. Hartung, a professor at the Their report was published by the Trans-Atlantic Think Tank for Toxicology at Johns Hopkins, and they published a brief analysis of their research in the current issue of the weekly science magazine Nature. (
http://www.icis.com/Articles/2009/08/27/9243428/costs-for-reach-could-jump-6-fold-to-13.6bn-study.html
CC-MAIN-2013-48
refinedweb
502
50.36
Feature #7051 Extend caller_locations API to include klass and bindings. Allow caller_locations as a method hanging off Thread. Description The new caller_locations api allows one to get label, base_label, path, lineno, absolute_path. I feel this API should be extended some what and cleaned up a bit. - I think there should be complete parity with caller and backtrace APIs. As it stands caller_locations is a fine replacement for caller, however the same code responsible for caller is also responsible for Thread#backtrace. As it stands there is no equivalent Thread#backtrace_locations API that allows one to grab OO backtraces for a thread. For sampling profilers a common technique is to spin a thread that grabs stack traces from a profiled thread. I played around with some of this here: - I think there should be a way to get the class the method belongs to where possible. At the moment you need to use something like ruby2ruby to determine the class of a frame in a backtrace. Getting the class is actually very important for auto-instrumentation techniques. A general approach is to grab stack traces, determine locations that seemed to be called a lot, and then instrument them. Trouble is, without a class it is very hard to pick a point to instrument. I got this working with my stacktrace gem so I think it is feasible. - Ability to grab bindings up the call chain For some advanced diagnostic techniques it is very handy to grab bindings up the chain, that way you can print out local vars in a calling method and so on. It would be handy if this api exposed bindings. - Naming and longer term deprecation of caller The name caller_locations to me feels a bit unnatural, as an API it is superior in all ways to the current caller, yet is far harder to type or remember. I am not really sure what it should be named but caller feels a bit wrong. Also it feels very tied to MRI returning RubyVM:::Backtrace::Location , Location seems to me in the wrong namespace. Is JRuby and Rubinius going to be expected to add this namespace? Is this going to be spec? Has any though been given to longer term deprecation of 'caller'. - What about exceptions? Exception has no equivalent of caller_locations, for exceptions it makes much more sense to cut down on allocations and store a thinner stack trace object, in particular for the massively deep stacks frameworks like rails have. Then materialize the strings if needed on iteration through Exception#backtrace Also available in: Atom PDF
https://bugs.ruby-lang.org/issues/7051?tab=properties
CC-MAIN-2020-24
refinedweb
429
71.24
adrian suri wrote: > Hi > > Sorry for cross posting, No you're not or you wouldn't have crossposted as you did... but I have simply followed a posting by a > person who sometimes (it appears) goes by the name The OS/2 Guy. There are a great many "imposters" aka "sock puppets" posting as "The OS/2 Guy" "OS2 Guy" "OS/2 Guy" "Real OS/2 Guy" "Genuine OS/2 Guy" "Best OS/2 Guy" "Oldest OS/2 Guy" "Cutest OS/2 Guy" "OS/2 Man" "OS2 Man" "The OS2 Man" "OS2 Aunt" None of them are me. I am the official OS/2 Guy. I have > been viewing these pro/anti ecomstation, Yeah, we're sick of it too. Postings regarding OS/2 belong in the OS/2 newsgroups. Posting regarding the problematic eComStation belong in the eComStation newsgroups. eCS Lusers refuse to post them there because nobody visits the eComStation newsgroups and those who have purchased eCS know that it is a piece of crap. these > message not only over-populate the advocacy groups, but also all other > OS/2 and ecomstation news groups , Oh? So you know there are eComStation newsgroups. Then you can understand why *real* OS/2 users object to all these ridiculous eComStation pieces of spam appear here in the OS/2 newsgroups. I am not at all impressed. Neither are we. Surely > the point should be this, at a time when development of OS/2 and for > that matter ecomstation is down we need all and every development of > OS/2 based systems, not simply trash them. OS/2 users shouldn't give a damn about eComStation because it isn't OS/2 at all. It simply 'uses" OS/2 as the base operating system. eCS itself is a minor vendor's proprietary problematic product that uses a bastardized version of OS/2. > I have been a user of OS/2 since version 3, I started with 2.0... which came pre-installed on > a now defunct Escom (German Brand) computer brought in England. I have > no illusion that this letter will stop this situation but I have reached > a point where I feel enough is enough. Ok. So we can assume you won't be back? We need a bit of sanity here, > such banter in these groups is far from productive and becomes overly > personal, why not post a note instead like hey I have had this idea that > would be a really cool feature for OS/2 what do you think, can you help, > would you like to help etc. We do that often. But we also have to wade through phony eCS marketing spiels disguised as ridiculous eCS testimonials repeatedly by the handful of desperate eCS salesmen who plagued these OS/2 newsgroups. Why not point your frustration and wrath at them rather than whine to *real* OS/2 users about it? Or for that matter I tried this freeware > Software and would really like to thanks the author for his/her had efforts We thank DinkMeister all the time. Dink's software is free. eCS is not free - in fact it costs more than OS/2 itself - year after year after year. > Well that my rant for the day, please keep supporting OS/2 We will always support OS/2 or > ecomstation, There is no reason to support eComStation because it doesn't belong here. Take it to the eComStation newsgroups, please. and developing software and drivers..... IBM has just released a new OS/2 update called FixPak 5. IBM continues to support, enhance, fix, adjust, alter and develop drivers and new software. Thank IBM for that. > Kindest Regards > > Adrian Suri > > ps > > > I have been trying to get visual age to work work with the free stl > libraries, including the iostream.h and namespace.... but my cpp is not > as it should be, anyone want to help????? Ummmmmm.... nope. -- Tim Martin, The Official and Only OS/2 Guy Warp City Web Site -
http://fixunix.com/os2/45142-fed-up-fud.html
CC-MAIN-2014-15
refinedweb
664
71.85
It appears Paramiko is trying a relative import, which is not recognised in this form in Python 3 anymore. See the changes in Python 3. The import statements in Paramiko should be one of from .transport import SecurityOptions, Transport (note the leading dot), or from paramiko.transport import SecurityOptions, Transport You can either fix the paramiko source code, or as a workaround, you could add /Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/site-packages/paramiko to your PYTHONPATH. Neither are preferred. Did you run the 2to3 tool before you ran python3 setup.py install? I'm not sure if that would fix this though, since the tool probably can't distinguish between a relative or absolute import in the way it is used here. Do check on the Paramiko forums (if there Check with another constructor for htmlView: ContentType mimeType = new System.Net.Mime.ContentType("text/html"); var htmlView = AlternateView.CreateAlternateViewFromString(bodyMessage, mimeType); Most likely, you have not installed django in the virtual environment. Either install django in virtual environment. Activate the environment and then install django using pip or other methods. Or link/copy django installed on the system (somewhere in /usr/lib/python-XXX) to python site packages in the environment. No recommended. Install OpenCV It needs this package to function Tkinter (capitalized) refers to versions <3.0. tkinter (all lowecase) refers to versions ≥3.0. Source: You need to use either explicit relative or absolute imports when you use python3, so from wordpress_xmlrpc import base # or from . import base In python3 import base would only import an absolute package base, as implicit relative imports are no longer supported. think you have not installed fsevents, you can download fsevents from here extract the repository and cd into and do python setup.py install.. Running scripts from the middle of a package is a bad idea, for a number of reasons, the most obvious of which is the one you're running into: When you import generator.the_generator somewhere, generator ends up as a package, so an absolute import of generator.the_page, or a relative import, will work fine. But when you just run the script generator/the_generator.py, there is no generator.the_generator, just __main__, and there is no generator package. The only other way Python could know how to find generator.the_page would be if the parent directory of generator were on sys.path, which it isn't. As you can guess, you can work around this by munging sys.path to put the appropriate parent directory on there… but this is a bad idea too. There are also many other problems with this solut Why is there any need for a Python module??? All can be done from the command line! E.g. take a look at: Get the commands needed and execute them from Python. >). ive only used cx_freeze a few times and was successful using these steps (you were possibly missing something in this): first create a setup.py from cx_Freeze import setup, Executable import sys exe = Executable( script="yourmodule.py", base="Win32GUI", ) setup( name = "desiredname", version = "1", description = "example program", executables = [exe] ) before running this make sure that you have all non default(built in) modules and the setup.py in the same folder as the "yourmodule.py" then from the command line run "python setup.py build" You are using Python 3. Do from .Courses import Courses from .Fridge import Fridge Python 2 would look for Courses module in the same dir, but Python 3 looks for Courses module in site packages - and, obviously, it's not there. P.S. "Phython" - sounds interesting ;) Well, I think I found the answer, but it doesn't look like I'm going to be able to use the bulk uploader anyways since my objects use ndb. See these answers: bulkloader not importing ndb.model dowload app engine ndb entities via bulk exporter / bulk uploader Have you installed it using apt-get or built from sources? If built from sources, are you sure the installation has finished successfully? Usually in order to build Python from sources one has to do the following steps ./configure make sudo make install (sudo might not be required, but the make script will attempt to change files in /usr/ directory. in your python sources directory. The last command, amongst others, copies python to the /usr/ directory. If you want to have it installed somewhere else you'd have to pass --path=XXX (if i'm not mistaken) to ./configure. Try setting your PYTHONPATH environment variable. If you need to find where pip is, you could try the locate command if you're on Linux. I hope you had installed virtualenv and if you have create the virtual environment (virtualenv), you have to use . . venv/bin/activate command to activate the enviroment in unix or OSx. Hope you will get information from this source After client.connect(. . .) you need to use this command session = client.get_transport().open_session() then use session.exec_command(. . .). Take) Please use for pxssh module this is very useful for your application if work for windows Python: How can remote from my local pc to remoteA to remoteb to remote c using Paramiko this example very helpful for you Python - Pxssh - Getting an password refused error when trying to login to a remote server i think u check for your server settings in remote host machine I don't think any bashrc or profile scripts are being sourced when you use exec_command(). Maybe try the following: stdin, stdout, stderr = ssh.exec_command("bash -lc 'echo $PATH'") my_path = stdout.read().rstrip() If the problem is that you are trying to run a command that's normally in your PATH, but isn't when you use exec_command(), you're probably better off calling the command by its absolute path (run "which [command]" when you're logged into the other machine normally to find out what that is). An easy way (and scary) would be to define an external bash file with execution permissions: installer.sh #!/bin/sh pip install paramiko I'm assuming pip is installed, but you can concatenate any set of commands in order to install paramiko. Then from your Python file foo.py try: import paramiko except: import subprocess subprocess.call('./installer.sh', shell=True) However installation issues are not subject of your application, you should considerate using distutils to define dependencies in your installation setup.py of your package using the install_requires cat is reading from stdin. Use echo instead. 'echo ' + localstring + ' > newfile.txt' If you need to echo multiple lines, use -e flag: echo -e "Line1 Line2 " > file.txt You run into the same problem with FTP, you can't mkdir /some/long/path, you have to cd / mkdir some # ignore errors if it exists cd some mkdir long # ignore errors if it exists cd long mkdir path # ignore errors if it exists cd path I'm guessing that the historical reason for this model is to provide a simple boolean SUCCEED/FAIL for any command issued by the client. Having some fuzzy error like 'Couldn't make directory /some/long/path because directory /some/long doesn't exist' would be a pain in the ass to handle on the client side. In looking at the SFTP protocol spec re: filenames ( ), it's unclear to me if clients are expected to understand '/' as a path separator in the context of making a directory - since you The problem is that xprop is blocking for the mouse click so it needs to be done in the background. The wait is not strictly necessary, but makes the script exit more cleanly by waiting for xprop to complete. #!/bin/bash xprop | grep WM_NAME(STRING) & pid=!$ sleep 1 xdotool mousemove 10 40 click 1 wait $pid If I remember correctly the Dajaxice tutorial leaves out the part where you actually have to install Dajaxice... If you haven't already you should try pip install django-dajaxice the problem is in the resources.py file for tastypie. It has the following line: from django.db.models.constants import LOOKUP_SEP That import will only work on 1.5+. For django < 1.5, it should be: from django.db.models.sql.constants import LOOKUP_SEP Upgrading to 1.5 will definitely fix it, but for those who can't, temporarily downgrade tastypie or do that fix yourself. In trying to sort this out, I have broken python, and eventually I got it going again. I think initially I had not run one of the port select --set... commands. Once I realised this might be the case, I did so, but that produced the errors at the top. MAXREPEATS, a circular reference perhaps? No idea. I have read here (macports didn't place python_select in /opt/local/bin) and here (How do I uninstall python from OSX Leopard so that I can use the MacPorts version?) about the --set command not working and to try sudo port select python python26 (i used python27) instead. I checked the PATH and python didn't appear, so I updated that as well. I got my python interpreter back and low-and-behold imports requests now works. I think at the end of it all, there were two errors: I_ From your drawing, app1 is a sibling to mysite—that is, it's in /home/jack/workspace/Project1/app1/, not /home/jack/workspace/Project1/mysite/app1/. So, sys.path.append("/home/jack/workspace/Project1/mysite") isn't going to do you any good; you need `sys.path.append("/home/jack/workspace/Project1/")'. You need to install PyDispatcher separately. Please take a look at the required packages for the tutorial to work along with the installation instructions here: PyOpenGL Introduction Check particularly within the section named Package Installation Your base module is located in the ui module. Hence from base import BasePage shoul dbe from ui.base import BasePage). Thanks for your commentary @Marcin. Turns out that I had a file called location.py in my views.py folder, which was causing some kind of conflict. I renamed this file location_view.py and voila. So moral of the story, I guess, is check to make sure that you dont have any name conflicts in an app when you are trying to import an app of the same name..)
http://www.w3hello.com/questions/Ubuntu-Python-ldquo-No-module-named-paramiko-rdquo-
CC-MAIN-2018-17
refinedweb
1,718
64.91
span8 span4 span8 span4 Idea by stevenjh · · fme logsworkbench If you're having to rerun a translation multiple times or coming back to a workbench after working on something else I think it would be really handy if the translation log showed the date and time the job finished. Two year old idea and not implemented. Not very hard. Wasn't it good enough? Here's a small workaround using a Python shutdown script. It will print the current timestamp in the log window (not in the log file) after the translation has terminated: from datetime import datetime print datetime.now().strftime('Translation terminated on %Y-%m-%d %H:%M:%S') David I like pasting the log summary as annotation after I have finished the workspace. Then I have what is expected next time I need to edit the workbench. I currently need to add the date manually, so it would save me a step. That's one approach, drawback is the log isn't as nice to read when every line is prefixed with a timestamp . Does it help if you turn on "Log timestamp information"? It's in Tools > Options > Translation > Log Settings. Share your great idea, or help out by voting for other people's ideas. Go to error button to Translation Log window FME Workbench Accessibility Options (color blindness) Clicking on a Selection Instead of Directly on a Transformer when Displacing a Group of Transformers Ability to freeze the translation log during a translation (pause the auto scroll) Manhattan connector routing When Creating a Tunnel the annotation background colour is unique Ability to play a sound at any stage of a translation Different shapes for annotations and bookmarks Zoom Enhancements - Selected Object Zoom, Zoom In/Out Tool, Bookmark Zoom
https://knowledge.safe.com/idea/28258/add-translation-end-datetime-to-the-log.html
CC-MAIN-2019-43
refinedweb
293
59.74
mutex (mutual exclusion) is generally used to block threads that are initiated by the same calling process. Same principle as a semaphore, but used to protect resources (including variables) in your multi-threaded app. So, for example, if you have a multithreaded application that has an open file handle to a log file, and you have a function or method that writes to the log file, you do not want 2 of your threads trying to write to the same log file at the same time. So at the beginning of the function that writes to the file, you would set a mutex (call pthread_mutex_lock with posix threads). The first thread that tries to call that function will be successful (it will successfully create the mutex), and will be able to execute the write function. If another thread tries to call the write function at the same time, then it will be blocked when it tries to call pthread_mutex_lock, and will continue blocking until pthread_mutex_unlock is called, which you would place at the end of your write function. Here is a quick example of how to protect a variable from being changed by 2 threads at the same time. (better to check for errors in here, but this is the simplest possible example). #include <pthread.h> void incrementMyGlobalCounter(i static pthread_mutex_t localMutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&localM myGlobalCounter += incVal; pthread_mutex_unlock(&loca } I will leave the following recommendation for this question in the Cleanup topic area: Accept: BlackDiamond {http:#7157666} Please leave any comments here within the next seven days. PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER! jmcg EE Cleanup Volunteer
https://www.experts-exchange.com/questions/20323800/How-pthread-mutex-t-is-different-from-semaphore.html
CC-MAIN-2018-26
refinedweb
270
55.58
This statechart "engine" (implemented as a C++ template class) implements the most commonly used aspects of UML statecharts. All you need to do is define an array of states and implement event checking and handling methods. Then call the engine when an event occurs. The engine calls your event checking and handling methods in the correct order to figure out what event happened, and tracks the current state. This is a lightweight implementation that compiles under Visual Studio 2005 and, with some slight modifications, under VC++ 6.0. This implementation requires less statechart-related housekeeping code than other C++ implementations. (See Miro Samek's, for example.) Statecharts were developed by David Harel to add nesting and other features to flat state machines. (See David Harel, "On Visual Formalisms", Communications of the ACM, Vol. 31, No. 5, pp 514-530, 1988.) Statecharts were later added to the Unified Modeling Language (UML) and standardized. They are an excellent tool for modeling classes, sub-systems and interfaces that have many distinct states and complex transitions among them. My personal need for them arose while implementing a software interface between two real-time, embedded systems that controlled separate machines requiring physical synchronization. I have also used them for modeling and implementing user interfaces that featured many modes. The following is a brief summary of the notation and behavior of statecharts. For a full presentation of the UML statechart notation, see the UML 2.0 specification available here. Graphically, UML shows states as boxes with rounded corners, and transitions as arrows between boxes. (See Figure 1.) The transitions are labeled with the event that causes the transition, optionally followed by a forward slash, and the action(s) that will be taken upon transition. A condition, called a "guard," can be indicated in square brackets. If the event happens, the guard condition is evaluated and the transition is taken only if the condition is true. States can be nested (See Figure 2.), which allows high-level events to invoke transitions that leave any of several states with just one arrow. The use of so-called "composite" states keeps statechart diagrams much simpler than what flat state machines would require. Even though states can be nested, the system must always transition to some simple (i.e. non-composite) state. A solid circle at the beginning of an arrow indicates a default start state. A statechart must have at least one default start state designated, indicating the initial state of the system. If any transition -- including a default one -- ends on a compound state, then there must be a default state designation inside that compound state, and so on, eventually leading to a simple state. One exception to this is described below. States can have internal transitions that do not take the system to another state, yet do have associated actions. These are shown inside the state where they are handled. Compound states may also have internal transitions. Two special internal transitions are "entry" and "exit." These are executed upon entry to, and exit from, the corresponding state. This allows common actions such as initialization and destruction to be expressed one time, rather than as actions on every event leading to/from a state. Custom internal events can also be specified. If a transition takes the system across several state boundaries, the various actions are executed in the following order: Statecharts allow a transition to return to a previous state within a composite state, without requiring that you specify what state you were in previously. This is represented by a transition arrow that ends in an encircled "H" for "history." (See Figure 3.) For example, say an event can be handled from any of two simple states within a compound state. If you show a transition from the compound state, back inside it to the encircled "H," this means "handle the event and return to the state you most recently left." That is much simpler than showing two (or more) transitions with identical event/action labels. There are two kinds of history returns in UML statecharts: shallow and deep. Shallow transitions (indicated by an "H") return to the most recently exited state at the level where the "H" is shown. If that does not lead to a simple state, then it is an error. Deep history (indicated by an "H*") means that the system will return to the most recent simple state within the compound state that it most recently exited. So, if the system in Figure 3 was in state A when event x happened, the system would return to state A. This implementation supports state nesting, entry, exit and custom internal events, default states and deep history transitions. If a history return cannot find a recently exited state at a given level, it will try to use default state designations to get the system to a simple state. Only failing that will it be considered an error. This implementation does not currently support orthogonal states, factored transition paths, forks, joins, synch states or message broadcasting. Many of those unsupported features depend heavily on the system you are integrating this code into and can be simulated in your event handlers. Once you have designed your statechart, do the following. First, define an enumeration of states. The following comes from the included sample application, which illustrates all of the above features. This application performs a path-cover test of the statechart engine. enum eStates { eStateA, eStartState = eStateA, eStateB, eStateC, eStateD, eStateE, eNumberOfStates }; Here I name the start state and I also designate the number of states by the last enum value, so it will always be correct. Your specific state names will likely be more meaningful than these. Next, I allocate an array of the following: typedef struct { int32 m_i32StateName; std::string m_sStateName; int32 m_i32ParentStateName; int32 m_i32DefaultChildToEnter; int32 (T::*m_pfi32EventChecker)(void); void (T::*m_pfDefaultStateEntry)(void); void (T::*m_pfEnteringState)(void); void (T::*m_pfLeavingState)(void); } xStateType; For example, TStatechart<CStateClass>::xStateType xaStates[eNumberOfStates] = { /* name */ {eStateA, /* string name */ "A", /* parent */ -1, /* default_substate */ eStateB, /* event-checking func */ &CStateClass::evStateA, /* default state entry func */ &CStateClass::defEntryStateA, /* entering state func */ &CStateClass::entryStateA, /* exiting state func */ &CStateClass::exitStateA}, /* name */ {eStateB, /* string name */ "B", /* parent */ eStateA, /* default_substate */ eStateC, /* event-checking func */ &CStateClass::evStateB, /* default state entry func */ &CStateClass::defEntryStateB, /* entering state func */ &CStateClass::entryStateB, /* exiting state func */ &CStateClass::exitStateB}, /* name */ {eStateC, /* string name */ "C", /* parent */ eStateB, /* default_substate */ -1, /* event-checking func */ &CStateClass::evStateC, /* default state entry func */ &CStateClass::defEntryStateC, /* entering state func */ &CStateClass::entryStateC, /* exiting state func */ &CStateClass::exitStateC}, /* name */ {eStateD, /* string name */ "D", /* parent */ eStateA, /* default_substate */ -1, /* event-checking func */ &CStateClass::evStateD, /* default state entry func */ &CStateClass::defEntryStateD, /* entering state func */ &CStateClass::entryStateD, /* exiting state func */ &CStateClass::exitStateD}, /* name */ {eStateE, /* string name */ "E", /* parent */ eStateB, /* default_substate */ -1, /* event-checking func */ &CStateClass::evStateE, /* default state entry func */ &CStateClass::defEntryStateE, /* entering state func */ &CStateClass::entryStateE, /* exiting state func */ &CStateClass::exitStateE} }; The structs must be initialized in the same order as the states in the enumeration above. Only the top-most state, here eStateA, will have -1 for its parent designation. States without a default sub-state (which will include all simple states) must specify -1 for the default sub-state. Every state must have an event checking/handling method, but need not have the last three fields filled in. Specify 0 for those if they are not defined. eStateA -1 0 The string name field is used in printing out trace information. In the file TStatechart.hpp, set TRACING_STATUS to 1 to activate this. If compiled with MFC, the information will be written via the TRACE() macro. Otherwise, the text is sent to cout. The engine is referenced internally via a void pointer, so the class using the statechart must have a void pointer for its use: TRACING_STATUS 1 TRACE() cout class CStateClass { . . . void *engine; }; The engine must be created and destroyed in your class. These macros and the ones below hide some of the necessary details. The engine name appears in all of them so that you may have more than one declared in the same client class. CStateClass::CStateClass(void) { CREATE_ENGINE(CStateClass, engine, xaStates, eNumberOfStates, eStartState); } CStateClass::~CStateClass(void) { DESTROY_ENGINE(CStateClass, engine); } At the point where events happen, place the following call: PROCESS_EVENT(CStateClass, engine) Since an event may be far more complex than examining a mere scalar value, the engine does not pass the event around to your event checking/handling methods. Rather, you must store the event in member variable(s) in your class before calling PROCESS_EVENT so that the event checking/handling methods can test for it. Thus, it does not appear in the above call. PROCESS_EVENT For each state in your statechart diagram, an event checking/handling method must be defined that checks for all events that can be handled by that state. Simply test for each event that can happen while you are in the given state, as in the following: uint32 CStateClass::evStateA(void) { // Checking for event in state A. if ('g' == m_cCharRead) // include any guard conditions here { BEGIN_EVENT_HANDLER(CStateClass, engine, eStateA); // Put the transition action code here. END_EVENT_HANDLER(CStateClass, engine); return (iHandlingDone); } return (iNoMatch); } This arrangement allows any guard conditions to be tested at the same point in the code as the event itself, simplifying the code. Return iNoMatch from a handler that does not find an event it is supposed to handle. iNoMatch The BEGIN_EVENT_HANDLER macro lets the engine know that you have found a match for an event. It records this fact and executes the exit handlers for every state that must be exited to get to the destination state. It also records the fact that eStateA will be the state the system goes to after executing the handler code. If the given state is a composite state, then of course you will end up in some simple state inside that composite state. BEGIN_EVENT_HANDLER Control then returns to this method, where any transition actions are carried out. The END_EVENT_HANDLER macro executes any state entry handlers for states that you must enter to end up in the correct simple state. If you wish to transition to a composite state with history, "OR" the history flag onto the state name in the BEGIN_EVENT_HANDLER macro: END_EVENT_HANDLER BEGIN_EVENT_HANDLER(CStateClass, engine, eStateA | iWithHistory); For an internal transition, use the "no state change" flag: BEGIN_EVENT_HANDLER(CStateClass, engine, iNoStateChange); That's it! Internally, the state definition array is parsed upon initialization and more sophisticated data structures are created from it. Those data structures, plus the state definition array, are referenced when an event is being processed. Don't even think about changing the state definition array at run-time! Because your code must call the statechart engine, it calls your event handlers back in order to find out who will be handling the event and where to go next. Hence, when executing an event handler, you are on the same thread that initially called the engine. The code contains numerous assert() statements, which check for a variety of simple mistakes that can be made when defining the array of states. Examples are failure to have an initial default state, and a state not having a valid parent state. Such errors are caught during initialization, rather than at run-time. assert() This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below. A list of licenses authors might use can be found here Article author wrote:This implementation does not currently support orthogonal states, ... , forks, joins, synch states... General News Suggestion Question Bug Answer Joke Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
https://www.codeproject.com/Articles/11398/A-Lightweight-Implementation-of-UML-Statecharts-in
CC-MAIN-2017-47
refinedweb
1,958
52.7
Complete roguelike tutorial using C++ and libtcod - part 10.1: persistence In this part, we will implement saving and loading the game to be able to close it and resume it later. And this is not going to be pleasing. C++ has a few great feats, but it certainly sucks at type introspection and object serialization. Most modern languages have these features built in. For this reason, the article 10 of Jotaf's python tutorial will be split in two for the C++ version. In fact, there's a way to serialize a C++ object and store it on the disk using only a couple of lines of code : using boost Serialization library. But we're not going to use it for several reasons : - this tutorial is not about using boost but rather how to code the features yourself using basic C++. - even if using boost would considerably reduce the size of the code to write, you still have to embed boost in your game. Using hand-made code will replace 8000 lines of boost code with less than 300 lines of specific code, resulting in a lighter executable and a simplified compilation process for your project. - using libtcod's zip toolkit means that the save file will be compressed. Of course, this means less space used on the disk, but also harder to hack savegame files. Of course, using boost doesn't keep you from compressing the file, but it just comes at no cost when using libtcod. Anyway if you prefer to use boost, you can follow this article to reorganize the Map and Engine code, and just skip the whole Persistent stuff and replace Engine::load and Engine::save code with boost invocation. libtcod features used in this article : The plan Since this part does not include a game menu, we're going to do a minimal savegame support : - when the player closes the game window, the game state is saved to a file - when the player starts the game, it resumes the last saved game - when the player dies, the savegame is deleted (you wouldn't write a roguelike without permadeath, would you?) While this simplifies the article, it leaves an annoying case : when the player manage to kill all monsters, he will be stuck. The only way to restart a game is to erase the savegame by hand. This will be fixed in the next article. Refactoring The engine The first thing, obviously, is to be able to save and load the whole game. We also need to remove the initializing code from the Engine constructor, because when the Engine is created, we don't know yet if we have to generate a new map or load a previously saved one. We put the functions in the Engine class : Engine.hpp bool pickATile(int *x, int *y, float maxRange = 0.0f); void init(); void load(); void save(); }; The new constructor doesn't create the map and actors anymore : Engine::Engine(int screenWidth, int screenHeight) : gameStatus(STARTUP), player(NULL),map(NULL),fovRadius(10), screenWidth(screenWidth),screenHeight(screenHeight) { TCODConsole::initRoot(screenWidth,screenHeight,"libtcod C++ tutorial",false); gui = new Gui(); } All the initialization code has been moved to the init function : void Engine::init() { player = new Actor(40,25,'@',"player",TCODColor::white); player->destructible=new PlayerDestructible(30,2,"your cadaver"); player->attacker=new Attacker(5); player->ai = new PlayerAi(); player->container = new Container(26); actors.push(player); map = new Map(80,43); map->init(true); gui->message(TCODColor::red, "Welcome stranger!\nPrepare to perish in the Tombs of the Ancient Kings."); } Now the load function will either load a saved game or call Engine::init to create a new one. We simply call it before the main loop. We also save the game once the player closes the game window. main.cpp : int main() { engine.load(); while ( !TCODConsole::isWindowClosed() ) { engine.update(); engine.render(); TCODConsole::flush(); } engine.save(); return 0; } The map We could save the map by putting every tile property in the file. Or we can only save the seed of the random number generator and re-generate the map. For this, we need to store the seed and the random number generator in the map class. Previously, we were using libtcod's default random number generator with an unknown seed. We also have to move the map initialization code out of the constructor so that we're able to call it when the map is loaded from the file : Map.hpp void init(bool withActors); protected : Tile *tiles; TCODMap *map; long seed; TCODRandom *rng; friend class BspListener; void dig(int x1, int y1, int x2, int y2); void createRoom(bool first, int x1, int y1, int x2, int y2, bool withActors); The withActors parameter tells the map whether it should create monsters and items or if they will be loaded from a saved game. The constructor new only gets some random seed : Map::Map(int width, int height) : width(width),height(height) { seed=TCODRandom::getInstance()->getInt(0,0x7FFFFFFF); } In case you wonder, 0x7FFFFFFF is the highest possible 32 bit signed integer value. The init function uses the code that was previously in the constructor, but the splitRecursive function now uses the map's RNG : void Map::init(bool withActors) { rng = new TCODRandom(seed, TCOD_RNG_CMWC); tiles=new Tile[width*height]; map=new TCODMap(width,height); TCODBsp bsp(0,0,width,height); bsp.splitRecursive(rng,8,ROOM_MAX_SIZE,ROOM_MAX_SIZE,1.5f,1.5f); BspListener listener(*this); bsp.traverseInvertedLevelOrder(&listener,(void *)withActors); } The withActors boolean is passed the the BSP listener in the userData parameter. It's a void * parameter that can contain pretty much anything. You can use it to store any numeric value (an int, a float, a boolean, a char...) or the adress of some struct/class. Here, we're simply casting the boolean into void *. The room creation code now uses the map's RNG instead of libtcod's default one. It also retrieve the withActors value to pass it to the createRoom function. In Map.cpp, BspListener::visitNode : bool withActors=(bool)userData; // dig a room w=map.rng->getInt(ROOM_MIN_SIZE, node->w-2); h=map.rng->getInt(ROOM_MIN_SIZE, node->h-2); x=map.rng->getInt(node->x+1, node->x+node->w-w-1); y=map.rng->getInt(node->y+1, node->y+node->h-h-1); map.createRoom(roomNum == 0, x, y, x+w-1, y+h-1, withActors); The createRoom function digs the room, then handle actors only if withActors is true : void Map::createRoom(bool first, int x1, int y1, int x2, int y2, bool withActors) { dig (x1,y1,x2,y2); if (!withActors) { return; } if ( first ) { If you want to be able to restart a game using the exact same map as before by entering the same seed, you also need to use the map's RNG in the createRoom, addMonster and addItem functions. But since there's no way to enter a seed right now, we won't do it. A persistent engine Now everything is ready and all we have to do is to implement the Engine::save and Engine::load functions. If you want to use boost, it's time you leave this tutorial and go on your own. For the others, brace yourselves ! It's time to reinvent the wheel ! Let's define some abstract interface for everything that must be saved : Persistent.hpp : class Persistent { public : virtual void load(TCODZip &zip) = 0; virtual void save(TCODZip &zip) = 0; }; This file has to be included early in main.hpp as pretty much everything must inherit from Persistent. main.hpp : #include "libtcod.hpp" class Actor; #include "Persistent.hpp" #include "Destructible.hpp" We're going to use the top-down way, starting with the higher level class down to the smallest ones. In the attached source code, all the save/load method have been implemented in the Persistent.cpp file. While that might not be very orthodox, it helps keeping the bloat out of all the cpp files and having all the persistent stuff in a single file. Let's start with the Engine class. We obviously have to save the map and the actors. Another thing is the message log. First, handle the permadeath : void Engine::save() { if ( player->destructible->isDead() ) { TCODSystem::deleteFile("game.sav"); else save the map : } else { TCODZip zip; // save the map first zip.putInt(map->width); zip.putInt(map->height); map->save(zip); The map could save the width/height fields in its own save function, but since it won't be able to load them (because we need them to create the Map object), we keep the symmetry between the load and save functions and handle the width/height field in the Engine. then the actors. Note that since we want to be able to know who is the player, we save him first. That's why we decrement the number of remaining actors (actors.size()-1). // then the player player->save(zip); // then all the other actors zip.putInt(actors.size()-1); for (Actor **it=actors.begin(); it!=actors.end(); it++) { if ( *it != player ) { (*it)->save(zip); } } Finally, the message log. Then dump the compressed data to a file : // finally the message log gui->save(zip); zip.saveToFile("game.sav"); } } I always start with the save function because it seems more intuitive to me. Then, writing the load function is just a mirroring process : void Engine::load() { if ( TCODSystem::fileExists("game.sav")) { TCODZip zip; zip.loadFromFile("game.sav"); // load the map int width=zip.getInt(); int height=zip.getInt(); map = new Map(width,height); map->load(zip); Then we load the player. // then the player player=new Actor(0,0,0,NULL,TCODColor::white); player->load(zip); actors.push(player); The rest of the code is almost copied and pasted from the save function : // then all other actors int nbActors=zip.getInt(); while ( nbActors > 0 ) { Actor *actor = new Actor(0,0,0,NULL,TCODColor::white); actor->load(zip); actors.push(actor); nbActors--; } // finally the message log gui->load(zip); } Note that we have to call the Actor constructor with dummy parameters. We could define some default Actor::Actor() constructor for that. If there is no game.sav file, we initialize some new random map : } else { engine.init(); } } A persistent message log Ok that was pretty easy so far. The message log persistence is also quite simple to implement : Gui.hpp : class Gui : public Persistent { public : Gui(); ~Gui(); void render(); void message(const TCODColor &col, const char *text, ...); void load(TCODZip &zip); void save(TCODZip &zip); void Gui::save(TCODZip &zip) { zip.putInt(log.size()); for (Message **it=log.begin(); it != log.end(); it++) { zip.putString((*it)->text); zip.putColor(&(*it)->col); } } Note that TCODZip can store C strings (char *) and TCODColor as easily as an int. It can also store a whole TCODConsole or a TCODImage. The putColor function's parameter is a pointer to a TCODColor. void Gui::load(TCODZip &zip) { int nbMessages=zip.getInt(); while (nbMessages > 0) { const char *text=zip.getString(); TCODColor col=zip.getColor(); message(col,text); nbMessages--; } } The data returned by TCODZip::getString() won't be available once the TCODZip object is destroyed (as soon as we exit the Engine::load function). So it's very important to always duplicate the string. In our case, we don't need to do it because the message function already duplicates the text parameter using strdup. A persistent map Let Map implement the Persistent interface : Map.hpp class Map : public Persistent { public : int width,height; ... void load(TCODZip &zip); void save(TCODZip &zip); We save the seed that will allow to reconstruct the dungeon without having to save the whole tile grid, and the memory map (list of explored tiles). void Map::save(TCODZip &zip) { zip.putInt(seed); for (int i=0; i < width*height; i++) { zip.putInt(tiles[i].explored); } } We store the explored booleans as int since TCODZip only support a few basic types. The conversion is implicit (false=0, true=1). Now let's implement the loading part : void Map::load(TCODZip &zip) { seed=zip.getInt(); init(false); Initializing the map with withActors = false will dig the rooms, but create no actor nor try to move the player in the first room. Then we restore the memory map : for (int i=0; i < width*height; i++) { tiles[i].explored=zip.getInt(); } } Persistent actors Ok that was the easy part. It's not too late to go back to boost, or switch to another language, or give up game programming and instead focus on something else like narwhals... or bacon... Well at first, it doesn't seem much different. Actor implements Persistent : class Actor : public Persistent { public : int x,y; // position on map ... void load(TCODZip &zip); void save(TCODZip &zip); }; We save all the basic properties of the actor : void Actor::save(TCODZip &zip) { zip.putInt(x); zip.putInt(y); zip.putInt(ch); zip.putColor(&col); zip.putString(name); zip.putInt(blocks); Then a boolean for each feature available (we could use a bit field but why bother, the file is compressed) : zip.putInt(attacker != NULL); zip.putInt(destructible != NULL); zip.putInt(ai != NULL); zip.putInt(pickable != NULL); zip.putInt(container != NULL); Then the features themselves : if ( attacker ) attacker->save(zip); if ( destructible ) destructible->save(zip); if ( ai ) ai->save(zip); if ( pickable ) pickable->save(zip); if ( container ) container->save(zip); } The loading part is symmetric. Properties : void Actor::load(TCODZip &zip) { x=zip.getInt(); y=zip.getInt(); ch=zip.getInt(); col=zip.getColor(); name=_strdup(zip.getString()); blocks=zip.getInt(); Features booleans : bool hasAttacker=zip.getInt(); bool hasDestructible=zip.getInt(); bool hasAi=zip.getInt(); bool hasPickable=zip.getInt(); bool hasContainer=zip.getInt(); Then comes the feature loading. Attacker is easy : if ( hasAttacker ) { attacker = new Attacker(0.0f); attacker->load(zip); } Once again, we use a dummy value in the constructor but you could add a constructor with no parameter. Now Destructible is quite different because our actors don't contain Destructible fields, but rather MonsterDestructible or PlayerDestructible. Since we can't call the load function on an object because we don't know what to create, we'll use some simplified factory pattern, using a static function on the Destructible class to create the Destructible object for us ; if ( hasDestructible ) { destructible = Destructible::create(zip); } The same happens for the Ai and Pickable classes since they both have descendant classes : if ( hasAi ) { ai = Ai::create(zip); } if ( hasPickable ) { pickable = Pickable::create(zip); } Finally, back to the classic way with the Container feature : if ( hasContainer ) { container = new Container(0); container->load(zip); } } Persistent attackers This one is very easy : class Attacker : public Persistent { public : float power; // hit points given Attacker(float power); void attack(Actor *owner, Actor *target); void load(TCODZip &zip); void save(TCODZip &zip); }; void Attacker::load(TCODZip &zip) { power=zip.getFloat(); } void Attacker::save(TCODZip &zip) { zip.putFloat(power); } Persistent containers A bit harder but we already know how to load and save actors : class Container : public Persistent { public : int size; // maximum number of actors. 0=unlimited ... void remove(Actor *actor); void load(TCODZip &zip); void save(TCODZip &zip); }; void Container::load(TCODZip &zip) { size=zip.getInt(); int nbActors=zip.getInt(); while ( nbActors > 0 ) { Actor *actor=new Actor(0,0,0,NULL,TCODColor::white); actor->load(zip); inventory.push(actor); nbActors--; } } void Container::save(TCODZip &zip) { zip.putInt(size); zip.putInt(inventory.size()); for (Actor **it=inventory.begin(); it != inventory.end(); it++) { (*it)->save(zip); } } Persistent destructibles To be able to restore the right type of destructible, we'll store some type information in the savegame file. The factory function will first read this type, then instantiate the Destructible and finally call the load function. class Destructible : public Persistent { public : float maxHp; // maximum health points ... void load(TCODZip &zip); void save(TCODZip &zip); static Destructible *create(TCODZip &zip); protected : enum DestructibleType { MONSTER,PLAYER }; }; The load and save functions only deal with the generic part : void Destructible::load(TCODZip &zip) { maxHp=zip.getFloat(); hp=zip.getFloat(); defense=zip.getFloat(); corpseName=_strdup(zip.getString()); } void Destructible::save(TCODZip &zip) { zip.putFloat(maxHp); zip.putFloat(hp); zip.putFloat(defense); zip.putString(corpseName); } Note how we always duplicate the data returned by the getString function. This will create a small memory leak since the corpseName field is not destroyed when the Destructible is deleted. In fact we cannot delete the corpseName field because it does not always contain a dynamically allocated string (using new, _strdup of malloc/calloc). So far, corpseName always contained a static string (like "dead orc") that cannot be deleted because it points to a static part of memory inside the program's code (in fact if you open the .exe file with an hexadecimal editor, you will find those strings). One way to get rid of the memory leak is to always use dynamically allocated strings : Destructible::Destructible(float maxHp, float defense, const char *corpseName) : maxHp(maxHp),hp(maxHp),defense(defense){ this->corpseName = _strdup(corpseName); } Destructible::~Destructible() { free((char*)corpseName); } The destructor already has a body in the header file, so we must remove some curly brackets: virtual ~Destructible(); Now we can implement the save function on the MonsterDestructible and PlayerDestructible class. They put the type value in the file before calling the generic save function : void PlayerDestructible::save(TCODZip &zip) { zip.putInt(PLAYER); Destructible::save(zip); } void MonsterDestructible::save(TCODZip &zip) { zip.putInt(MONSTER); Destructible::save(zip); } Now, the factory function can use this information : Destructible *Destructible::create(TCODZip &zip) { DestructibleType type=(DestructibleType)zip.getInt(); Destructible *destructible=NULL; switch(type) { case MONSTER : destructible=new MonsterDestructible(0,0,NULL); break; case PLAYER : destructible=new PlayerDestructible(0,0,NULL); break; } destructible->load(zip); return destructible; } Persistent pickables Well now that you've seen the method on the destructibles, you can apply it to the pickable. There's a small difference though. The destructible child classes share the same data, thus can use generic save/load function on the base class. On the other hand, the different Pickable child classes are quite different and have to implement their own persistence functions. The only place where we can reuse some code is in the Fireball class. Since it shares the same data as the LightningBolt class, it only needs to implement the save function (to put the right PickableType). class Pickable : public Persistent { public : bool pick(Actor *owner, Actor *wearer); void drop(Actor *owner, Actor *wearer); virtual bool use(Actor *owner, Actor *wearer); static Pickable *create (TCODZip &zip); protected : enum PickableType { HEALER,LIGHTNING_BOLT,CONFUSER,FIREBALL }; }; class Healer : public Pickable { public : float amount; // how many hp Healer(float amount); bool use(Actor *owner, Actor *wearer); void load(TCODZip &zip); void save(TCODZip &zip); }; class LightningBolt : public Pickable { public : float range,damage; LightningBolt(float range, float damage); bool use(Actor *owner, Actor *wearer); void load(TCODZip &zip); void save(TCODZip &zip); }; class Confuser : public Pickable { public : int nbTurns; float range; Confuser(int nbTurns, float range); bool use(Actor *owner, Actor *wearer); void load(TCODZip &zip); void save(TCODZip &zip); }; class Fireball : public LightningBolt { public : Fireball(float range, float damage); bool use(Actor *owner, Actor *wearer); void save(TCODZip &zip); }; The implementation : void Healer::load(TCODZip &zip) { amount=zip.getFloat(); } void Healer::save(TCODZip &zip) { zip.putInt(HEALER); zip.putFloat(amount); } void LightningBolt::load(TCODZip &zip) { range=zip.getFloat(); damage=zip.getFloat(); } void LightningBolt::save(TCODZip &zip) { zip.putInt(LIGHTNING_BOLT); zip.putFloat(range); zip.putFloat(damage); } void Confuser::load(TCODZip &zip) { nbTurns=zip.getInt(); range=zip.getFloat(); } void Confuser::save(TCODZip &zip) { zip.putInt(CONFUSER); zip.putInt(nbTurns); zip.putFloat(range); } void Fireball::save(TCODZip &zip) { zip.putInt(FIREBALL); zip.putFloat(range); zip.putFloat(damage); } And the factory : Pickable *Pickable::create(TCODZip &zip) { PickableType type=(PickableType)zip.getInt(); Pickable *pickable=NULL; switch(type) { case HEALER : pickable=new Healer(0); break; case LIGHTNING_BOLT : pickable=new LightningBolt(0,0); break; case CONFUSER : pickable=new Confuser(0,0); break; case FIREBALL : pickable=new Fireball(0,0); break; } pickable->load(zip); return pickable; } Persistent A.I. Nothing much different here. class Ai : public Persistent { public : virtual void update(Actor *owner)=0; static Ai *create (TCODZip &zip); protected : enum AiType { MONSTER,CONFUSED_MONSTER,PLAYER }; }; class MonsterAi : public Ai { public : MonsterAi(); void update(Actor *owner); void load(TCODZip &zip); void save(TCODZip &zip); protected : int moveCount; void moveOrAttack(Actor *owner, int targetx, int targety); }; class ConfusedMonsterAi : public Ai { public : ConfusedMonsterAi(int nbTurns, Ai *oldAi); void update(Actor *owner); void load(TCODZip &zip); void save(TCODZip &zip); protected : int nbTurns; Ai *oldAi; }; class PlayerAi : public Ai { public : void update(Actor *owner); void load(TCODZip &zip); void save(TCODZip &zip); protected : bool moveOrAttack(Actor *owner, int targetx, int targety); void handleActionKey(Actor *owner, int ascii); Actor *choseFromInventory(Actor *owner); }; And the implementation. The only subtlety is that ConfusedMonsterAi contains another Ai. void MonsterAi::load(TCODZip &zip) { moveCount=zip.getInt(); } void MonsterAi::save(TCODZip &zip) { zip.putInt(MONSTER); zip.putInt(moveCount); } void ConfusedMonsterAi::load(TCODZip &zip) { nbTurns=zip.getInt(); oldAi=Ai::create(zip); } void ConfusedMonsterAi::save(TCODZip &zip) { zip.putInt(CONFUSED_MONSTER); zip.putInt(nbTurns); oldAi->save(zip); } void PlayerAi::load(TCODZip &zip) { } void PlayerAi::save(TCODZip &zip) { zip.putInt(PLAYER); } The factory : Ai *Ai::create(TCODZip &zip) { AiType type=(AiType)zip.getInt(); Ai *ai=NULL; switch(type) { case PLAYER : ai = new PlayerAi(); break; case MONSTER : ai = new MonsterAi(); break; case CONFUSED_MONSTER : ai = new ConfusedMonsterAi(0,NULL); break; } ai->load(zip); return ai; } Afterword You can now compile and should be able to exit the game and restart it where you left it. I'm conscious that that's a damn lot of code and a quite boring article and I really wish libtcod provided something out of the box for this (I mean something more elaborated than TCODZip). If you want to use this method for a more complex game, be also aware that this code is very error prone. You have to be very careful to always maintain the symmetry between the save and load functions. Forget a field in one of the functions and it's crash time. A better way to organize the savegame file would be to store data using some kind of TLV encoding (tag, length, value). Providing a tag for each field would at least allow some error checking while reading the file along with a possibility for backward compatibility (being able to load an older version of a savegame file). All this is beyond the scope of this tutorial.
http://www.roguebasin.com/index.php?title=Complete_roguelike_tutorial_using_C%2B%2B_and_libtcod_-_part_10.1:_persistence&oldid=44507
CC-MAIN-2019-22
refinedweb
3,724
55.24
Version: (using KDE KDE 3.5.5) Installed from: Gentoo Packages Compiler: gcc (GCC) 4.1.1 (Gentoo 4.1.1-r1) OS: Linux 1. Open a window that can be resized to be very narrow - e.g., xclock 2. Decrease its width to about 80px - until the close button disappears 3. Run ksnapshot, select the "Section of window" mode, and take a screenshot. KSnapshot shows no error messages, but doesn't do anything. Works fine here (SVN just pre 3.5.5 on freebsd) I've been able to reproduce this with xclock, but not with anything else. What other apps show this behaviour? I ran into this problem when I was using GLUT, and created a very small window. But, here's a Qt example: #include <qapplication.h> #include <qpushbutton.h> int main( int argc, char **argv ) { QApplication a( argc, argv ); QPushButton hello( "Hello", 0 ); hello.resize( 70, 30 ); a.setMainWidget( &hello ); hello.show(); return a.exec(); } Same problem. Now try this, though: #include <qapplication.h> #include <qpushbutton.h> #include <qvbox.h> int main( int argc, char **argv ) { QApplication a( argc, argv ); QVBox box; box.resize( 70, 60 ); QPushButton hello1( "Hello1", &box ); QPushButton hello2( "Hello2", &box ); a.setMainWidget( &box ); box.show(); return a.exec(); } You can take a screenshot of the whole window and the second button - but not the first button! So it seems that the first widget is causing problems... And in the first example and in xclock, there is only one widget. Well, I actually have no idea how widgets and X work, so it's just a guess. Another example. 1. Add a new panel (right-click on the main panel, or whatever; Panel Menu->Add New Panel->Panel). 2. Move it to the left of the screen. 3. Take a screenshot of it. Doesn't work! 4. Right-click, "Configure Panel...", make it shorter than 100%. An arrow appears at the bottom. (Though now you can make it 100% again - the arrow stays. Bug?) 5. Take a screenshot of the panel. It works now! 6. Take a screenshot of the arrow... Doesn't work. i can reproduce #4 but all the rest work just fine here with 3.5.6 on Kubuntu Edgy I’ve just opened a review request for a patch. For more details, see Git commit b3fa5727d56f93d14ecba8f7ed2f969dcb1d9961 by Albert Astals Cid, on behalf of Adrián Chaves Fernández. Committed on 14/01/2013 at 22:25. Pushed by aacid into branch 'KDE/4.10'. take screenshots of windows no matter how narrow they are REVIEW: 107555 M +1 -1 windowgrabber.cpp
https://bugs.kde.org/show_bug.cgi?id=136142
CC-MAIN-2022-21
refinedweb
430
79.87
Created on 2008-05-06 21:30 by ambarish, last changed 2008-08-16 14:45 by facundobatista. Try the following code: import urllib import urllib2 url = '' data = urllib.urlopen(url).read() data2 = urllib2.urlopen(url).read() The attempt to get it with urllib works fine. With urllib2, the request is malformed and I get back a HTTP 404 Request in the 2nd case is: GET //autos/news/95ED98EE-A837-11DC-BCB3-4F218271.html HTTP/1.1\r\n Accept-Encoding: identity\r\n Host: autos\r\n Connection: close\r\n .... The host line seems to be looking for the last // rather than the first. Sorry, should have added another line: The reason this is important to fix, is I am getting that URL with a // in a Moved (HTTP 302) message, so I can't just get rid of the // The problem lines are in AbstractHTTPHandler.do_request(): scheme, sel = splittype(request.get_selector()) sel_host, sel_path = splithost(sel) if not request.has_header('Host'): request.add_unredirected_header('Host', sel_host or host) When there is a double '/' sel is something like '//path/to/resource'. splithost(sel) then gives ('path', '/to/resource'). Therefore the header 'Host' gets set to 'path'. I don't understand why sel_host is used in preference for host. host holds the correct value, even with the double slashes. Could someone explain why sel_host is used at all? Ordinarily, request.get_selector() returns the portion of the url after the host, and sel_host is None. However, if a proxy is set on the request, the request's host is set to the proxy host, get_selector() returns the original full url, and sel_host is the host from the original url (and different to the host set on the request). This bug is only triggered if the double slash comes directly after the host and there is no proxy set on the request. do_request_ does not check what get_selector() is returning, so the output is passed through splithost even when this is not necessary, and in this particular case it causes undesirable behaviour. My patch causes do_request_ only to attempt to extract the host from get_selector() if the proxy has been set. I have written a test to go with my patch. I could reproduce this issue on trunk and p3k branch. The patch attached by Adrianna Pinska "appropriately" fixes this issue. I agree with the logic. Attaching the patch for py3k with the same fix. Thanks, Senthil Commited in revs 65710 and 65711. Thank you all!!
http://bugs.python.org/issue2776
crawl-002
refinedweb
413
66.64
This action might not be possible to undo. Are you sure you want to continue? : Public International Law Disclaimer: The risk of use, non-use and misuse of this material shall be solely borne by the user. 2008 LEI Notes in “Nam omnia praeclara tam difficilia quam rara sunt” For all that is excellent and eminent is as difficult as it is rare 2 -Spinoza on Ethics PUBLIC INTERNATIONAL LAW 2008 Notes: INTRODUCTION Definition Public v Private International Law Basis of Public International Law 1. Naturalist 2. Positivists 3. Eccletics Three Grand Divisions Relations between International and Municipal Law 1. From the viewpoint of doctrine a. Dualist b. Monists 2. From the view of practice a. Doctrine of Transformation b. Doctrine of Incorporation ¯°º°¯ DEFINITION OF Public International Law It is the body of rules and principles that are recognized as legally binding and which govern the relations of states and other entities invested with international legal personality. Formerly known as “law of nations” coined by Jeremy Bentham in 1789. Public International Law Distinguished From Private International Law/Conflict of Laws It is that part of the law of each State which determines whether, in dealing with a factual situation, an event or transaction between private individuals or entities involving a foreign element, the law of some other State will be recognized. Public 1. Natur e Public is internatio nal in nature. It is a law of a sovereign over those subjected to his sway [Openhei m – Lauterpac ht, 38.] Private As a rule, Private is national or municipal in character. Except when embodied in a treaty or convention, becomes international in character. It is a law, not above, but between, sovereign states and is, therefore, a weaker law. [Openheim – Lauterpacht, 38.] Recourse with municipal is 5. Respo nsibili ty for violat ion Infractions are usually collective in the sense that it attaches directly to the state and not to its nationals. Generally, entails only individual responsibility . 4. Subje ct of Dispu te through internatio nal modes of settlemen t – like negotiatio ns and arbitration , reprisals and even war Derived from such sources as internatio nal customs, internatio nal conventio ns and the general principles of law. Applies to relations states inter se and other internatio nal persons. tribunals through local administrativ e and judicial processes. 3. Sourc e Consists mainly from the lawmaking authority of each state. Regulates the relations of individuals whether of the same nationality or not. BASIS OF PIL – 3 SCHOOLS OF THOUGHT [Why are rules of international law binding?] 1. Naturalist – ★ PIL is a branch of the great law of nature – the sum of those principles which ought to control human conduct, being founded on the very nature of man as a rational and social being. [Hugo Grotius] ★ PIL is binding upon States 2. Positivist – 2. Settle ment Disputes are resolved 3 ★ Basis is to be found in the consent and conduct of States. ★ Tacit consent in the case of customary international law. ★ Express in conventional law. Presumed in the general law of nations. [Cornelius van Bynkershoek] 3. Groatians or Eclectics – ★ Accepts the doctrine of natural law, but maintained that States were accountable only to their own conscience for the observance of the duties imposed by natural law, unless they had agreed to be bound to treat those duties as part of positive law. [Emerich von Vattel] ★ Middle ground 3 GRAND DIVISIONS 1. Laws of Peace – normal relations between states in the absence of war. 2. Laws of War – relations between hostile or belligerent states during wartime. 3. Laws of Neutrality – relations between a nonparticipant state and a participant state during wartime. This also refers to the relations among non-participating states. RELATIONS BETWEEN INTERNATIONAL LAW AND MUNICIPAL LAW From the Viewpoint of Doctrine 1. Dualists – ★ International Law and Municipal Law are two completely separate realms. ★ See distinctions Nos. 1,3 &4. 2. Monists – ★ Denies that PIL and Municipal Law are essential different. ★ In both laws, it is the individual persons who in the ultimate analysis are regulated by the law. That both laws are far from being essentially different and must be regarded as parts of the same juristic conception. For them there is oneness or unity of all laws. ★ PIL is superior to municipal law— international law, being the one which determines the jurisdictional limits of the personal and territorial competence of States. From the Viewpoint of Practice 1. International Tribunals ★ PIL superior to Municipal Law ★ Art. 27, Vienna Convention in the law of Treaties – A state “may not invoke the provisions of its internal law as justification for its failure to perform a treaty” PUBLIC INTERNATIONAL LAW 2008 ★ State legally bound to observe its treaty obligations, once signed and ratified 2. Municipal Sphere – depends on what doctrine is followed: Doctrine of Incorporation Rules of international law form part of the law of the land and no further legislative action is needed to make such rules applicable in the domestic sphere. [Sec. of Justice v. Lantion GRN 139465, Jan. 18, 2000] This is followed in the Philippines: Art. II, Sec. 2 – “The Philippines…adopts the generally accepted principles of international law as part of the law of the land…” However, no primacy is implied. Q: What are these generally accepted principles? A: Pacta sunt servanda, sovereign equality among states, principle of state immunity; right of states to self-defense Secretary Of Justice v. Judge Lantion and Jimenez [GR 139465, 18 Jan. 2000] FACTS: A possible conflict between the US-RP Extradition Treaty and Philippine law ISSUE: WON, under the Doctrine of Incorporation, International Law prevails over Municipal Law HELD: NO. Under the doctrine of incorporation, rules of international law form part of the law of the land and no further legislative action is needed to make such rules applicable in the domestic sphere. The doctrine of incorporation is applied whenever local courts are confronted with situations in which there appears to be a conflict between a rule of international law and the provisions of the local state’s constitution/statute. First, efforts should first be exerted to harmonize them, so as to give effect to both. This is because it is presumed that municipal law was enacted with proper regard for the generally accepted principles of international law in observance of the incorporation clause. However, if the conflict is irreconcilable and a choice has to be made between a rule of international law and municipal law, jurisprudence dictates that the municipal courts should uphold municipal law. This is because such courts are organs of municipal law and are accordingly bound by it in Notes: ★ 4 all circumstances. The fact that international law was made part of the law of the land does not pertain to or imply the primacy of international law over national/municipal law in the municipal sphere. The doctrine of incorporation, as applied in most countries, decrees that rules of international law are given equal standing with, but are not superior to, national legislative enactments. In case of conflict, the courts should harmonize both laws first and if there exists an unavoidable contradiction between them, the principle of lex posterior derogat priori - a treaty may repeal a statute and a statute may repeal a treaty - will apply. But if these laws are found in conflict with the Constitution, these laws must be stricken out as invalid. In states where the constitution is the highest law of the land, such as in ours, both statutes and treaties may be invalidated if they are in conflict with the constitution. Supreme Court has the power to invalidate a treaty – Sec. 5(2)(a), Art. VIII, 1987 Constitution Q: What is the doctrine of incorporation? How is it applied by local courts? Held: Under the doctrine of incorporation, rules of international law form part of the law of the land and no further legislative action is needed to make such rules applicable in the domestic sphere. PUBLIC INTERNATIONAL LAW 2008. Hon. Ralph C. Lantion, G.R. No. 139465, Jan. 18, 2000, En Banc [Melo]) Q: Is sovereignty really absolute and allencompassing? If not, what are its restrictions and limitations? Held: While sovereignty has traditionally been deemed absolute and all-encompassing on the domestic level, it is however subject to restrictions and limitations voluntarily agreed to by the Philippines, expressly or impliedly, as a member of the family state which has contracted valid international obligations is bound to make in its legislations such modifications as may be necessary to ensure the fulfillment of the obligations.. The sovereignty of a state therefore cannot in fact and in reality be considered absolute. Certain restrictions enter into the picture: (1) limitations imposed by the very nature of membership in the family of nations and (2) limitations imposed by treaty stipulations. (Tanada v. Angara, 272 SCRA 18, May 2, 1997 [Panganiban]) Doctrine of Transformation – Legislative action is required to make the treaty enforceable in the municipal sphere. Generally accepted rules of international law are not per se binding upon the state but must first be embodied in legislation enacted by the lawmaking body and so transformed into municipal law. This Notes: and are concluded by a substantial number of States EX. Treaties or International Conventions – 2 KINDS: 1. Treaties or International Conventions II. Law-Making Treaty [Traite-Loi] – ★ Concluded by a large number of States for purposes of: 1. International Custom III. (Abbas vs. The constitutional policy of a "self-reliant and independent national economy" does not necessarily rule out the entry of foreign investments. 2. 3.: Extradition Treaties 2. Rule. expressly or impliedly as a member of the family of nations. of the 1987 Constitution. confirming. Angara GRN 118295 May 2. Stipulating or laying down new general rules for future international conduct. 2. 1997 While sovereignty has traditionally been deemed absolute and all encompassing on the domestic level. 1949]. Judicial Decisions V. a law was passed which has conflicting provisions with the treaty. goods and services. rather it would be in the same class . for our Constitution has been deliberately general and extensive in its scope and is not cofined to the recognition of rules and principles of international law as contained in treaties to which our government may have been or shall be a signatory. [GRN L-2662 March 26. it consented to restrict its sovereign rights under the "concept of sovereignty as autolimitation. or defining their understanding of what the law is on a particular subject. Pacta Sunt Servanda International agreements must be performed in Good Faith. containing practically uniform provisions. the country is bound by generally accepted principles of international law. Primary I. Tañada vs. it would not be superior to a legislative act. Teachings of authoritative publicists ¯°º°¯ A. By the doctrine of incorporation. Creating new international institutions ★ Source of “General International Law” Concept of Sovereignty as Autolimitation When the Philippines joined the United Nations as one of its 51 charter members. General Principles of Law Recognized by Civilized Nations B. one may say that Supreme Court expressly ruled out the Doctrine of Transformation when they declared that generally accepted principles of international law form a part of the law of our nation even if the Philippines was not a signatory to the convention embodying them. it is however subject to restrictions and limitations voluntarily agreed to by the Philippines. Declaring. A treaty engagement is not a mere moral obligation but creates a legally binding obligation on the [arties. It contemplates neither “economic seclusion" nor "mendicancy in the international community. A reading of the case of Kuroda v Jalandoni. Contract Treaties [Traite-Contrat] – ★ Bilateral arrangements concerning matters of particular or special interest to the contracting parties ★ Source of “Particular International Law” ★ BUT: May become primary sources of international law when different contract treaties are of the same nature. Thus. Primary I. Later. COMELEC) Notes: SOURCES Article 38 of the Statute of International Court of Justice (SICJ) directs that the following be considered before deciding a case: A. But as internal law. A state which has contracted a valid international obligation is bound to make in its legislation such modifications as may be necessary to ensure the fulfillment of the obligations undertaken. The Constitution does not envision a hermit type isolation of the country from the rest of the world. the latter law would be considered as amendatory of the treaty.5 doctrine runs counter Art." PUBLIC INTERNATIONAL LAW 2008 as the latter. A: A treaty is part of the law of the land. Secondary IV. Sec. Q: A treaty was concurred between RP and China. II. which are considered to be automatically part of our own laws. being a subsequent law under the principle lex posterior derogat priori. ] Q: State your general understanding of the primary sources and subsidiary sources of international law. the cumulative effect of uniform decisions of the courts of the most PUBLIC INTERNATIONAL LAW 2008 important States is international custom. res judicata and prescription.S. and teachings of the most highly qualified publicists of various nations. Teachings of authoritative publicists – including learned writers Such works are resorted to by judicial tribunals not for the speculation of their authors concerning what the law ought to be. US. Justice Gray in Paquete Habana case. prescription. Secondary IV. cabotage. III. 175 U. subject to the provisions of Article 59. res judicata. e. The idea of “civilized nations” was intended to restrict the scope of the provision to European States.g. Article 38(1) of the Statute of International Court of Justice is understood as providing for international convention. e. but for trustworthy evidence of what the law really is. and due process. a longestablished way of doing things by States. This includes decisions of national courts. the decision in the AngloNorwegian Fisheries Case and Nicaragua v. international custom. although they are not a source of law. Vienna Convention on the Law of Treaties. and the prohibition against torture. B. international custom remains a significant source of international law.” This means that these decisions are not a direct source. By way of illustrating international Convention as a source of law.” It tells us what the law is and the process or method by which it cam into being. International Custom may be concretely illustrated by pacta sunt servanda. and thus. Human Rights in International Law by Lauterpacht and International Law by Oppenheim-Lauterpacht.” The primary sources may be considered as formal sources in that they are considered methods by which norms of international law are created and recognized. accorded with great respect. thus the term should include all nations. Judicial decisions The doctrine of stare decisis is not applicable in international law per Art. e. pacta sunt servanda. and general principles of law as primary sources of international law. International conventions. the prohibition against slavery. e. e. at present the term no longer have such connotation.6 II. To elevate a mere usage into one of a customary rule of international law. The subsidiary sources of international law are judicial decisions. supplementing treaty rules. 677.g. General principles of law recognized by civilized nations. a . [Mr. Examples of general principles are: estoppel. Alternative A: Reflecting general international law. equity and peace. including the principles of justice. 3.g. A conventional or treaty norm and a customary norm is the product of the formation of general practice accepted as law. while indicating that judicial decisions and teachings of the most highly qualified publicists as “subsidiary means for the determination of the rules of law. however.g. (2003 Bar) A: Under Article 38 of the Statute of International Court of Justice. consent. we may refer to the principle embodied in Article 6 of the Vienna Convention on the Law on Treaties which reads: “Every State possesses capacity to conclude treaties. International customs. 2. Usage is also a usual course of conduct. International Custom – Matters of international concern are not usually covered by international agreements and many States are not parties to most treaties.. This conviction is called “Opinio Juris” When there’s no conviction that it is obligatory and right. there must be a degree of constant and uniform repetition over a period of time coupled with opinio juris.. to afford evidence of Notes: V. giving an illustration of each. there’s only a Usage. but they do exercise considerable influence as an impartial and well-considered statement of the law by jurists made in the light of actual problems which arise before them. Custom is the practice that has grown up between States and has come to be accepted as binding by the mere fact of persistent usage over a long period of time It exists when a clear and continuous habit of doing certain things develops under the CONVICTION that it is obligatory and right.59 of the ICJ which states that “The decision of the Court has no binding force except between the parties and in respect to that particular case. General Principles of Law Recognized by Civilized Nations Salonga opines that resort is taken from general principles of law whenever no custom or treaty provision is applicable. the primary sources of international law are the following: 1.g. Right to Diplomatic Intercourse considered Recognition Level of Recognition Recognition of State . Consequences of Recognition of Belligerents e. and may be held directly accountable for its obligations. Where there is no direct enforcement of accountability and an intermediate agency is needed. Traditional concept ★ Only States are subjects of international law. as the decision of the Court has demonstrated in the Nicaragua Case. Right to Existence and SelfDefense 4. There is no direct enforcement and accountability. Forms of Recognition ¯°º°¯ Subject Defined A Subject is an entity that has an international personality. A. Objective Test – 2. An entity has an international personality if it can directly enforce its rights and duties under international law. The subsidiary means serves as evidence of law. SUBJECTS OF INTERNATIONAL LAW 2 Concepts: 1. Kelsen or Oppenheim. Declaratory School 2. 2. Territory 6. De Jure 2.2 Schools of Thought a. Right to Sovereignty and Independence. Contemporary concept ★ Individuals and international organizations are also subjects because they have rights and duties under international law. Kinds of Recognition 1. Criteria for Recognition 1. PUBLIC INTERNATIONAL LAW 2008 SUBJECTS Subject Defined Object Defined 2 Concepts of Subjects of International Law State as Subjects of International Law Elements of a State 4. Q: When does an entity acquire international personality? A: When it has right and duties under international law. Objects Defined An Object is a person or thing in respect of which rights are held and obligations assumed by the Subject.7 customary or general norm which came about through extensive and consistent practice by a great number of states recognizing it as obligatory. Government a) 2 kinds (1) De Jure (2) De Facto – 3 kinds b) 2 functions (1) Consti tuent (2) Minist rant c) Effects of change in government 7. Thus. 2 Senses of Belligerency c. the entity is merely an object not a subject of international law. Sovereignty a) Kinds b) Characteristics c) Effects of change in sovereignty Principle of State Continuity Fundamental Rights of States 1. A decision of the International Court of Justice. Right to Property and Jurisdiction. An intermediate agency—the Subject—is required for the enjoyment of its rights and for the discharge of its obligations. Belligerency b. GRN 125865 [26 March 2001]) . Requisites of Belligerency d. can directly enforce its rights. Subjective Test (a) Tobar/Wilson Doctrine (b) Estrada Doctrine b. such as McNair. De Facto c. Consequences of Recognition of Government C. 3. may serve as material evidence confirming or showing that the prohibition against the use of force is a customary norm. (Liang vs. B. Constitutive School b. The status of a principle as a norm of international law may find evidence in the works of highly qualified publicists in international law. People 5. for example. Notes: 5. People. Recognition of Belligerency a. Right to Equality Recognition of Government a. it is not directly governed by the rules of international law. 01 Dec. 1 Hudson. Since the continued amity between the State and other countries may require a satisfactory compromise of mutual claims. Q: The Japanese government confirmed that during the Second World War. the necessary power to make such compromise has been recognized. Rosario [GR 101949. The v. 302 [1924]) (Holy See. Reagan. Filipinas were among those conscripted as “comfort women” (prostitutes) for Japanese troops in various parts of Asia. The Japanese government has accordingly launched a goodwill campaign and offered the Philippine government substantial assistance for a program that will promote through government and non-governmental organization women’s rights. Julian Iglesias. An executive agreement is about to be signed for that purpose. a person who feels aggrieved by the acts of a foreign sovereign can ask his own government to espouse his cause through diplomatic channels. it is difficult to determine whether the statehood is vested in the Holy See or in the Vatican City. respect for the rules of international law. and possessing an organized government to which the great body of inhabitants render habitual obedience. World Court Reports 293. the sovereign authority of the state to settle claims of its nationals against foreign countries has repeatedly been recognized. Jr. Once the Philippine government decides to espouse the claim. Its first task is to persuade the Philippine government to take up with the Holy See the validity of its claims. Private respondent can ask the Philippine government. permanently occupying a definite portion of territory. 1994. (1992 Bar) A: The agreement is valid. As stated in Paris Moore v. seeks you advise on the validity of the agreement. Of course. descendant of now deceased comfort woman. the latter ceases to be a private cause. The settlement of such claims may be made by executive agreement. through the Foreign Office. “while as a general rule. a State is in reality asserting its own rights – its right to ensure.” Q: Is the Vatican City a state? A: YES! Notes: Holy See v. 1. international law has as its subjects states and obliges only immediately. the forerunner of the International Court of Justice: “By taking up the case of one of its subjects and by resorting to diplomatic action or international judicial proceedings on his behalf.8 PUBLIC INTERNATIONAL LAW 2008 The STATE as subject of International Law State is a community of persons more or less numerous. The comfort woman and their descendant cannot assert individual claims against Japan. child welfare. as the Holy See or Head of State. and the demands . to espouse its claims against the Holy See. it is to man who. 238 SCRA 524. it exceptionally applies to individuals because it is to man that the norms of international law apply. The Vatican City fits into none of the established categories of states. it is to man whom they restrain. 533-534.. The agreement includes a clause whereby the Philippine government acknowledges that any liability to the comfort women or their descendants are deemed covered by the reparations agreements signed and implemented immediately after the Second World War. who is also head of the Roman Catholic Church. nutrition and family health care. The Vatican City represents an entity organized not for political but for ecclesiastical purposes and international objects. Advise him. Rosario. in the person of its subjects. independent of external control. Dec. From the wordings of the Lateran Treaty. with the Pope. This may be made without the consent of the nationals or even without consultation with them. and the attribution to it of “sovereignty” must be made in a sense different from that in which it is applied to other states.” (The Mavrommatis Palestine Concessions. the Foreign Office shall first make a determination of the impact of its espousal on the relations between the Philippine government and the Holy See. Despite its size and object. Q: What must a person who feels aggrieved by the acts of a foreign sovereign do to espouse his cause? Held: Under both Public International Law and Transnational Law. international law thrusts the responsibilities of law and order. En Banc [Quiason]) Q: What is the status of an individual under public international law? (1981 Bar) A: According to Hanks Kelson. in conformity with its traditions. it has an independent government of its own. According to the Permanent Court of International Justice. 1994] The Lateran Treaty established the STATEHOOD of the Vatican City “for the purpose of assuring to the Holy See absolute and visible independence and of guaranteeing to it indisputable sovereignty also in the field of international relations”. 453 US 654. cannot perpetuate themselves 2.9 of its mission. Some writers even suggested that the treaty created two international persons . Dec. one can conclude that in the Pope's own view. The v. the Papal Nuncio. one can conclude that in the Pope's own view.” In view of the wordings of the Lateran Treaty. Jr. in conformity with its traditions. (Holy See. 1994. ★ the aggregate of individuals of both sexes who live together as a community despite racial or cultural differences ★ groups of people which cannot comprise a State: 1. Indeed. 533-534. Indeed. the Papal Nuncio.the Holy See and Vatican City. In 1929. through its Ambassador. treated as an enemy of all mankind. Inasmuch as the Pope prefers to conduct foreign relations and enter into transactions as the Holy See and not in the name of the Vatican City.7 acres. the world-wide interests and activities of the Vatican City are such as to make it in a sense an “international state. through its Ambassador. It also recognized the right of the Holy See to receive foreign diplomats. as the Holy See or Head of State. This appears to be the universal practice in international relations. was considered a subject of International Law. It was noted that the recognition of the Vatican City as a state has significant implication – that it is possible for any entity pursuing objects essentially different from those pursued by states to be invested with international personality. and to enter into treaties according to International Law. En Banc [Quiason]) Notes: ELEMENTS OF A STATE: A. it is the Holy See that is the international person. The Lateran Treaty established the statehood of the Vatican City “for the purpose of assuring to the Holy See absolute and visible independence and of guaranteeing to it indisputable sovereignty also in the field of international relations. With the loss of the Papal States and the limitation of the territory under the Holy See to an area of 108. Held: Before the annexation of the Papal States by Italy in 1870. Q: Discuss the Status of the Vatican and the Holy See in International Law. and the demands of its mission in the world. the Vatican City B. it is the Holy See that is the international person. 1.” One authority wrote that the recognition of the Vatican City as a state has significant implication that it is possible for any entity pursuing objects essentially different from those pursued by states to be invested with international personality. In a community of national states. the position of the Holy See in International Law became controversial. Amazons – not of both sexes. the Pope was the monarch and he. as the Holy See. where Italy recognized the exclusive dominion and sovereign jurisdiction of the Holy See over the Vatican City. PUBLIC INTERNATIONAL LAW 2008 represents an entity organized not for political but for ecclesiastical purposes and international objects. to send its own diplomats to foreign countries. Despite its size and object. it is difficult to determine whether the statehood is vested in the Holy See or in the Vatican City. Rosario. has had diplomatic representations with the Philippine government since 1957. The Vatican City fits into none of the established categories of states. with the Pope. “hostis humani generis” Territory – ★ the fixed portion of the surface of the earth inhabited by the people of the State . 238 SCRA 524. the Vatican City has an independent government of its own. The Holy See. The Holy See. People – ★ the inhabitants of the State ★ must be numerous enough to be self-sufficing and to defend themselves and small enough to be easily administered and sustained. who is also head of the Roman Catholic Church. This appears to be the universal practice in international relations. and the attribution to it of “sovereignty” must be made in a sense different from that in which it is applied to other states. The Philippines has accorded the Holy See the status of a foreign sovereign. has had diplomatic representations with the Philippine government since 1957. its world-wide interests and activities are such as to make it in a sense an “international state”.. The Republic of the Philippines has accorded the Holy See the status of a foreign sovereign. Pirates – considered as outside the pale of law. Italy and the Holy See entered into the Lateran Treaty. Since the Pope prefers to conduct foreign relations and enter into transactions as the Holy See and not in the name of the Vatican City. and aerial domains. consisting of its terrestrial. 1987 Philippine Constitution. 1596. C. fluvial. Philippine sovereignty was displayed by open and public occupation of a number of islands by stationing military forces. However. on the following islands. EX. and by awarding petroleum drilling rights. among other political and administrative acts. 4. the subsoil. Article 1. with all the islands and waters embraced therein. regardless of their breadth and dimensions. it confirmed its sovereign title by the promulgation of Presidential Decree No. but must not be too small as to unable to provide for people’s needs ★ Q: Why important to determine? A: Determines the area over which the State exercises jurisdiction ★ Nomadic tribe not a State Q: What comprises the Philippine Archipelago? A: §1. the Japanese occupation government in the Philippines which replaced the Commonwealth government during WWII c) By secession – that which is established by the inhabitants of a state who cedes . the insular shelves. China ★ BUT.” Q: The provision deleted the reference to territories claimed “by historic right or legal title. Defined in the 02 Jan. which declared the Kalayaan Island Group part of Philippine territory. The waters around.10 ★ the size is irrelevant – San Marino v. 1930 Treaty between the US and the UK over the Turtle and Mangsee Islands 7. but has NO legal title 3 Kinds: a) By revolution – that which is established by the inhabitants who rise in revolt against and depose the legitimate regime.” Does this mean that we have abandoned claims to Sabah? A: NO! This is not an outright or formal abandonment of the claim. the government of which is also displaced EX. including its territorial sea. Island of Batanes 8. Contemplated in the phrase “belonging to the Philippines by historic right or legal title” Q: What is the basis of the Philippine’s claim to a part of the Spratlys Islands? (2000 Bar) A: The basis of the Philippine claim is effective occupation of a territory not subject to the sovereignty of another state. Japan formally renounced all right and claim to the Spratlys. Instead. because: ☀ Power was withdrawn. and all other territories over which the Philippines has sovereignty or jurisdiction. Ceded to the US under the Treaty of Paris of 10 Dec. Notes: Government – ★ the agency or instrumentality through which the will of the State is formulated. between. Subsequently. De Facto A government of fact Actually exercises power or control. the seabed. 1898 2. form part of the internal waters of the Philippines. The Japanese forces occupied the Spratly Islands Group during the Second World War. De Jure One with rightful title but not power or control. Sulu. ☀ Has not yet entered into the exercise of power 2. however. under the San Francisco Peace Treaty of 1951. the Spratlys became terra nullius and was occupied by the Philippines in the title of sovereignty. by organizing a local government unit. 5. 3. and other submarine areas. In 1978. 1900 Treaty between US and Spain. must not be too big as to be difficult to administer and defend. did not designate any beneficiary state following the Japanese renunciation of right. the Commonwealth established by Oliver Cromwell which supplanted the monarchy under Charles I of England b) By government of paramount force – that which is established in the course of war by the invading forces of one belligerent in the territory of the other belligerent. Sibuto 6. the claim was left to a judicial body capable of passing judgment over the issue ★ The definition covers the following territories: 1. Cagayan. “The national territory comprises the Philippine archipelago. Defined in the 07 Nov. expressed and realized ★ 2 KINDS: 1. and connecting the islands of the archipelago. practically. The San Francisco Treaty or any other international PUBLIC INTERNATIONAL LAW 2008 agreement. Sec. the confederate government during the American Civil War which. (g) Administration of political duties. 4 – “The prime duty of the Government is to serve and protect the people…” Thus. privileges. (d) Determination of contractual relations between individuals. Examples: Promote social justice. transmission. not the State Harm justifies the replacement of the government by revolution – “Direct State Action” EFFECTS OF A CHANGE IN GOVERNMENT: It is well settled that as far as the rights of the predecessor government are concerned. PUBLIC INTERNATIONAL LAW 2008 ACCFA v. Summary: A. did not seek to depose the union government Q: Is the Cory Aquino Government a de facto or de jure government? A: De Jure! While initially the Aquino Government was a de facto government because it was established thru extra-constitutional measures. (c) Regulation of trade and industry Q: Is the distinction still relevant? A: No longer relevant! . (c) Regulation of the holding. and the determination of liabilities for debt and crime. and relations of citizens. (h) Dealings of the States with foreign powers 2. Moreover. it nevertheless assumed a de jure status when it subsequently recognized by the international community as the legitimate government of the Republic of the Philippines. Change of Government by Constitutional Reform ★ The new government inherits all the rights and obligations of the former government B.11 therefrom without overthrowing its government EX. II. The rule is that where the new government was organized by virtue of a constitutional reform duly ratified in a plebiscite.: Payment of postal money orders bought by an individual Ministrant – undertaken to advance the general interests of society – merely OPTIONAL. whatever harm is done by the government – attributed to the government alone. Notes: 1. (e) Definition and punishment of crimes (f) Administration of justice in civil cases. where the new government was established through violence. EX. Examples: (a) Public works. (b) Fixing of legal relations between spouses and between parents and children. Land reform Provide adequate social services Q: What is the mandate of the Philippine Government? A: Art. however. Conversely.R. CUGCO [30 SCRA 649] Constitution has repudiated the laissez faire policy Constitution has made compulsory the performance of ministrant functions. whatever good is done by government – attributed to the State. ★ Obligations – distinguish: ★ Contracted in the regular course of business – Inherited. No. the obligations of the replaced government are also completely assumed by the former. they are inherited in toto by the successor government. Examples: (a) Keeping of order and providing for the protection of persons and property from violence and robber. as by a revolution. distinction is made according to the manner of the establishment of the new government. and interchange of property. a new Constitution was drafted and overwhelmingly ratified by the Filipino people and national elections were held for that purpose. Change by Extra-Constitutional Means ★ Rights – all are inherited. Aquino. G. (b) Public charity. Regarding obligations.[Lawyers League for a Better Philippines v. it may lawfully reject the purely personal or political obligations of the predecessor government but not those contracted by it in the ordinary course of official business. 73748 (1986)] ★ The Cory government won! All de facto governments lost in the end! ★ 2 Functions: Constituent – constitutes the very bonds of society – COMPULSORY. comprehensiveness 4. Upon learning of the incident. EX. The facilitation of entry by Balerian contract workers to Islamabad is non political. absoluteness 5. If a Roman Citizen is captured. exclusivity 3. D. however that the new government is not internationally bound by the agreement that was concluded by the former government of Islamabad and Baleria. Sovereignty Internal and External Notes: Internal – ☀ the power of a State to control its internal affairs External ☀ the power of the State to direct its relations with other States ☀ also called “Independenc”e Characteristics of Sovereignty 1. but once he returns to Rome. Legal and Political Sovereignty Legal ☀ the authority which has the power to issue final commands ☀ Congress is legal sovereign Political - PUBLIC INTERNATIONAL LAW 2008 ☀ the power behind the legal sovereign. Sovereignty – ★ the supreme and uncontrollable power inherent in a State by which that State is governed. Hence. imprescriptibility Q: What happens to sovereignty if the acts of authority cannot be exercised by the legitimate authority? A: Sovereignty not suspended. permanent 2. Thereafter. he recovers all those rights again XPN: (a) Laws of Treason – Not suspended! ★ Preservation of allegiance to sovereign does not demand positive action. Moreover. but only a passive attitude or forbearance from adhering to the enemy by giving the latter aid and comfort (Laurel v. The agreement concerns the facilitation of entry of Balerian contract workers in Islamabad. A new government is exempt from obligation of treaties entered into by the previous government only with respect to those whose subject matter is political in nature. It is presumed that the treaty is in conformity with its internal law. or the sum of the influences that operate upon it ☀ the different sectors molding public opinion 2. Islamabad further contended that the agreement was contrary to its plasmatic law. the government of Baleria lodged a formal protest with the Islamabad revolutionary government invoking certain provisions of the aforementioned agreement.. Misa) ★ . The latter replied. Nor may the new government evade its international obligation on the ground that the agreement is contrary to its Plasmatic law. Most of Balerian contract workers were arrested by Islamabad Immigration officers for not having with them the necessary papers and proper documents. to comply with what was agreed upon and set forth in the agreement concluded between Baleria and its former government? Reasons. the political laws are revived Jus Postliminium – roman law concept. May be legal or political ★ KINDS: 1. individuality 6. a revolution broke out in Islamabad which is now governed by a revolutionary junta. what are the effects on the laws? A: Political Laws GR: Suspended! ★ Subject to revival under jus postliminium – i. inalienability 7.: Payment for arms bought by old government to fight the rebels Q: The Federation of Islamabad concluded an agreement with the republic of Baleria when the leaders of Islamabad made a state visit to the latter. the treaty embodying such agreement is binding on the new government of Islamabad. (1985 Bar) A: Yes.e. The rule is settled that a state cannot evade its international obligation by invoking its internal law.12 ★ Purely Personal/Political Obligations – Not bound! May reject! EX. he loses his rights as a Roman citizen. Is the Islamabad revolutionary government under obligation pursuant to international law. once the legitimate authority returns.: Japanese Occupation during WWII ★ Sovereignty remained with the US ★ Japanese merely took over the exercise of acts of sovereignty Q: In this case. Q: Why? A: They govern relations between the State and the people. because the inhabitants of the occupied territory were still bound by their allegiance to the latter during the enemy occupation. it is applicable to treason committed against the national security of the legitimate government.? A: The effect is that the political laws of the former sovereign are not merely suspended but abrogated. Although the penal code is non-political law. remains effective. but only passive attitude or forbearance from adhering to the enemy by giving the latter aid and comfort. 2. and Japanese occupation during WWII regarding the political laws of the Philippines. Q: May an inhabitant of a conquered State be convicted of treason against the legitimate sovereign committed during the existence of belligerency? A: YES. subject to revival under jus postliminium upon the end of the occupation. et al. the occupant has no power. non-political laws. Q: Was there a case of suspended allegiance during the Japanese occupation? A: None. A: There being no change of sovereignty during the belligerent occupation of Japan. over the Philippines? A: Sovereignty is not deemed suspended although acts of sovereignty cannot be exercised by the legitimate authority. to repeal or suspend the operation of the law of treason. NOTES: Members of the armed forces are still covered by the National Defense Act. Non-Political Laws generally continue in operation. Q: Distinguish between Spanish secession to the U. To allow suspension is to commit political suicide. Angara. Political Laws are deemed ABROGATED. however.S. Thus.S. etc. In both cases. although the Americans could not exercise any control over the occupied territory at the time. A person convicted of treason against the Japanese Imperial Forces was. Q: What is the effect of Japanese occupation to the sovereignty of the U. Q: Is sovereignty really absolute? A: In the domestic sphere – YES! In international sphere – NO! Tañada. Articles of War. these laws fall to the ground ipso facto unless they are retained or re-enacted by positive act of the new sovereign.13 (b) Combatants – not covered by said rule ★ Thus. after the occupation.S. (Ruffy v. for it would allow invaders to legally recruit or enlist the quisling inhabitants of the occupied territory to fight against their own government without the latter incurring the risk of being prosecuted for treason. for the reason also that they regulate private relations only. Adoption of the petitioner's theory of suspended allegiance would lead to disastrous consequences for small and weak nations or states. as a corollary of the preceding consideration. the Articles of War and other laws relating to the armed forces even during the Japanese occupation. entitled to be released on the ground that the sentence imposed on him for his political offense had ceased to be valid but not on non-political offenses. Notes: for EFFECTS OF A CHANGE IN SOVEREIGNTY 1. the political laws of the occupied territory are merely suspended. As they regulate the relations between the ruler and the rules. and would be repugnant to the laws of humanity and requirements of public conscience.S. sovereignty over the Philippines remained with the U. Non-political laws. Since the preservation of the allegiance or the obligation of fidelity and obedience of a citizen or subject to his government or sovereign does not demand from him a positive action. unless they are changed by the new sovereign or are contrary to its institutions. vs. et al. Chief of Staff) ★ Rule applies only to civilians Civil Laws: GR: Remains in force XPN: Amended or superseded by affirmative act of belligerent occupant Q: What happens to judicial decisions made during the occupation? A: Those of a Political Complexion – ★ automatically annulled upon restoration of legitimate authority ★ conviction for treason against the belligerent Non-political ★ remains valid ★ EX. Q: Why? A: Regulates only private relations XPN: (a) Changed by the new sovereign (b) Contrary to institutions of the new sovereign Q: What is the effect of change of sovereignty when the Spain ceded the Philippines to the U. continue in operation. What the . by contrast. AFP members still covered by National Defense Act.: Conviction defamation PUBLIC INTERNATIONAL LAW 2008 belligerent occupant took over was merely the exercise of acts of sovereignty. people. as a member of the family of nations. which are considered to be automatically part of our own laws. 3. By their inherent nature. States. A treaty engagement is not a mere moral obligation but creates a legally binding obligation on the parties. Emperor Louis Napoleon filed damage suit on behalf of France in an American Court. RIGHTS OF THE STATE Fundamental Rights of States [ S P E E D ] 1. based on the rationale that the Philippines “adopts the generally accepted principles of international law as part of the law of the land and adheres to the policy of . 02 May 1997] While sovereignty has traditionally been deemed absolute and all-encompassing on the domestic level. because it had in legal effect been filed by France. the litigation could continue. but he was deposed and replaced as head of State pendent elite. Hence. . the country is bound by generally accepted principles of international law. whose legal existence had not been affected by change in head of its government. Thus. a state’s sovereignty cannot in fact and in reality be considered absolute. the disappearance of any of the elements causes the extinction of the state. upon recognition of the duly authorized representative of the new government. its officials and its citizens. Clearly.: (1) Reduction of population due to natural calamity (2) Changes in territory However. the State continues as a juristic being. expressly or impliedly. territory. Right to Property and Jurisdiction. Intercourse Right to Diplomatic RIGHT OF EXISTENCE AND SELF-DEFENSE ★ The most elementary and important right of a State ★ All other rights flow from this right ★ Recognized in the UN Charter. Measures taken by Members in the exercise of this right of selfdefense shall be immediately reported to the SC and shall not in any way affect the . Rosario (238 SCRA 524) From the moment of its creation. Right to Equality Notes: 5. Was the action abated? (Bar) A: No. or sovereignty. and in pursuit of mutually covenanted objectives and benefits. it is lost only when at least one of its elements is destroyed. Right to Sovereignty and Independence. See Holy See vs. EX. Napoleon had sued not in his personal capacity but officially as sovereign of France. nations may surrender some aspects of their state power in exchange for greater benefits granted by or derived from a convention or pact. Right to Existence and Self-Defense 4. One of the oldest and most fundamental rules in international law is pacta sunt servanda – international agreements must be performed in good faith.” The underlying consideration in this partial surrender of sovereignty is the reciprocal commitment of the other contracting states in granting the same privilege and immunities to the Philippines. they also commonly agree to limit the exercise of their otherwise absolute rights. Article 51: “Nothing in the present charter shall impair the inherent right of individual or collective self-defense if an armed attack occurs against a Member of the UN. Certain restrictions enter into the picture: Limitations imposed by the very nature of membership in the family of nations. and Limitations imposed by treaty stipulations. a portion of sovereignty may be waived without violating the Constitution.” Principle of State Continuity PUBLIC INTERNATIONAL LAW 2008 State is not lost when one of its elements is changed. Q: In the famous Sapphire Case. when the Philippines joined the UN as one of its 51 charter members. like individuals. 2. despite changes in its elements. .14 [GR 118295. Thus. until the SC has taken measures necessary to maintain international peace and security. cooperation and amity with all nations. By their voluntary act. State does not lose its identity but remains one and the same international person notwithstanding changes in the form of its government. it consented to restrict its sovereign rights under the “concept of sovereignty as AUTO-LIMITATION. By the doctrine of incorporation. live with coequals. treaties limit or restrict the absoluteness of sovereignty. it is however subject to restrictions and limitations voluntarily agreed to by the Philippines. under the Incorporation Clause (Art.” This mandate does not only outlaw war. is binding on all members of the international community. The allied forces did not launch military operations and did not occupy Iraq on the claim that their action was in response to an armed attacked by Iraq.” The Security Council of the United Nations failed to reach a consensus on whether to support or oppose the “war of liberation. (2) enforcement measure involving the use of armed forces by the UN Security Council under Article 42. 1987 Constitution) Q: State the occasions when the use of force may be allowed under the UN Charter. 51. as authorized by the UN Security Council. (Justice Isagani A. II. Immediately after the incident. The second is when it is employed in the exercise of the inherent right of self-defense under conditions prescribed in Art. speaking through its leader Bin Derdandat. or in any other manner inconsistent with the purposes of the United Nations.15 authority and responsibility of the SC under the present Charter to take at any time such action as it deems necessary in order to maintain or restore international peace and security. However. members of Ali Baba. did not authorize the use of armed force. a political extremist organization based in and under the protection of Country X and espousing violence worldwide as a means of achieving its objective. 2. Alternative A: In International Law. it encompasses all threats of and acts of force or violence short of war. which gave Iraq a final opportunity to disarm or face serious consequences. These are: (1) inherent right of individual or collective self-defense under Article 51. the Philippines can exercise its inherent right of existence and self-defense ★ This right is a generally accepted principle of international law – thus. the prohibition is addressed to all UN members. PUBLIC INTERNATIONAL LAW 2008 The UN Charter in Article 2(4) prohibits the use of force in the relations of states by providing that all members of the UN “shall refrain in their international relations from the threat or use of force against the territorial integrity or political independence of any state. The action taken by the allied forces cannot be justified under any of the three exceptions to the prohibition against the use of force which the UN Charter allows.” ★ Art. it allows DEFENSIVE WAR! ★ Thus. It is covered by the prohibition against the use of force prescribed by the United Nations Charter and it does not fall under any of the exceptions to that prohibition. A: There are only two occasions when the use of force is allowed under the UN Charter. when attacked.” giving Iraq “a final opportunity to comply with its disarmament obligations. admitted and owned responsibility for the bombing of ITT. 2003 issue of the Philippines Daily Inquirer) Q: Not too long ago. Ali Baba. the action taken by the allied forces cannot find justification. of which there was none. (2003 Bar) A: The United States and its allied forces cannot justify their invasion of Iraq on the basis of selfdefense under Article 51. Moreover. 42. invaded Iraq to “liberate Iraqis and destroy suspected weapons of mass destruction. planted high-powered explosives and bombs at the International Trade Tower (ITT) in Jewel City in Country Y. “allied forces”. and there was no necessity for anticipatory self-defense which may be justified under customary international law. as such. Q: On 31 October 2001. saying that it was done to pressure Country Y to release captured members of the terrorist group.” This resolution was in the process of implementation. in an article entitled “A New World Order” written in his column “Separate Opinion” published in the March 30. Sec. II. Cruz. and (3) enforcement measure by regional arrangement under Article 53. including women and children were killed or injured and billions of dollars in property were lost. it is now recognized as a fundamental principle in customary international law and. led by Amercian and British armed forces. As a result of the bombing and the collapse of the 100-story twin towers. 1441 which set up “an enhanced inspection regime with the aim of bringing to full and verified completion the disarmament process. The first is when it is authorized in pursuance of the enforcement action that may be decreed by the Security Council under Art. the action of the alleged allied forces was taken in defiance or disregard of the Security Council Resolution No. so was Iraq’s compliance with such disarmament obligations. Ali Baba threatened to repeat its terrorist acts against Country Y if the latter and its allies failed to accede to Ali Baba’s Notes: . Resolution 1441. it is part of our law of the land. Neither can they justify their invasion on the ground that Article 42 of the Charter of the United Nations permits the use of force against a State if it is sanctioned by the Security Council. As thus provided. about 2000 people. Sec.” Can the action taken by the allied forces find justification in International Law? Explain. a member of the United Nations. attack by Iraq. 2 – “The Philippines renounces war as an instrument of national policy…” ★ This prohibits an offensive/aggressive war ★ But. however. The American invasion was made without permission from the Security Council as required by the UN Charter. It is like searching a person without warrant and curing the irregularity with the discovery of prohibited drugs in his possession. in an article entitled “A New World Order” written in his column “Separate Opinion” published in the March 30. Country Y demanded that Country X surrender and deliver Bin Derdandat to the government authorities of Country Y for the purpose of trial and “in the name of justice. 2003 issue of the Philippines Daily Inquirer) Q: Will the subsequent discovery of weapons of mass destruction in Iraq after its invasion by the US justify the attack initiated by the latter? A: Even if Iraq’s hidden arsenal is discovered – or actually used – and the United States is justified in its suspicions. Art. Cruz. the use of military force must be proportionate and intended for the purpose of detaining the persons allegedly responsible for the crime and to destroy military objectives used by the terrorists. Any subsequent discovery of the prohibited biological and chemical weapons will not retroactively legalize that invasion. What action or actions can Country Y legally take against Ali Baba and Country X to stop the terrorist activities of Ali Baba and dissuade Country X from harboring and giving protection to the terrorist organization? Support your answer with reasons. 51 of the UN Notes: . (2002 Bar) A: (1) Country Y may exercise the right of selfdefense. 2003 issue of the Philippines Daily Inquirer) Q: State B. The process cannot be reversed. which was. as provided under Article 51 of the UN Charter “until the Security Council has taken measure necessary to maintain international peace and security. in an article entitled “A New World Order” written in his column “Separate Opinion” published in the March 30. null and void ab initio. Country Y cannot be granted sweeping discretionary powers that include the power to decide what states are behind the terrorist organizations. Under Article 4 of the UN Charter. Cruz. It is for the Security Council to decide whether force may be used against specific states and under what conditions the force may be used. Country Y may use force against Country X as well as against the Ali Baba organization by authority of the UN Security Council. that there must first be an “armed attack” before a state can exercise its inherent right of self-defense. Alternative A: Under the Security Council Resolution No. undertook a “preventive” attack in certain bases on State C located near the border of the two states. The cowboy from Texas says PUBLIC INTERNATIONAL LAW 2008 that outdrawing the foe who is about to shoot is an act of self-defense. is planning an attack on its nuclear plan and research institute. to which the aggression should be reported. (Justice Isagani A. which disturbs or threatens “international peace and security”. However. State B argued that it was acting within the legal bounds of Article 51 of the UN Charter and that it was a permitted use of force in self-defense and against armed attack.16 demands. including measure invoking the use of force. and only until the Security Council. the attack of State B on State C cannot be justified as an act of self-defense under Art. As a result. (Justice Isagani A. shall have taken the necessary measures to maintain international peace and security. thus becoming the aggressor. There is no evidence of such a threat. Q: Is the United States justified in invading Iraq invoking its right to defend itself against an expected attack by Iraq with the use of its biological and chemical weapons of mass destruction? A: The United States is invoking its right to defend itself against an expected attack by Iraq with the use of its biological and chemical weapons of mass destruction. relying on information gathered by its intelligence community to the effect that its neighbor. not Iraq. State C presented the incident to the UN General Assembly but the latter referred it to the UN Security Council as a matter.” Self-defense enables Country Y to use force against Country X as well as against the Ali Baba organization. that circumstance will not validate the procedure taken against Iraq. The fundamental principles of international humanitarian law should be respected. 1368. legally speaking. The warrant must first be issued before the search and seizure can be made. (2) It may bring the matter to the Security Council which may authorize sanctions against Country X. but Bush is probably invoking the modern view that a state does not have to wait until the potential enemy fires first. Iraq is now not only exercising its inherent right of self-defense as recognized by the UN Charter. However. 51 says. State C. the terrorist attack of Ali Baba may be defined as a threat to peace.” Country X refused to accede to the demand of Country Y. It was the United States that made the “armed attack” first. as it did in defining the 11 September 2001 attacks against the United States. In response. Is State B responsible under International Law? Did State B act within the bounds set forth in the UN Charter on the use of force in self-defense? (1985 Bar) A: An armed attack is not a requirement for the exercise of the right of self-defense. The resolution authorizes military and other actions to respond to terrorist attacks. By UN Authorization and Resolution ★ EX. fail to submit to the award. 18 – “The President shall be the Commander-in-Chief of all armed forces…and whenever it becomes necessary. This means that we are already under attack Q: What are the effects when Congress declares a state of war? A: 1. and asked the Soviet forces to intervene While the intervention was upon invitation. VI.: Diplomatic Protest. 1990 Iraqi Annexation of Kuwait There was an SC Resolution. it is UN itself that intervened 2. suspend the privilege of the writ of habeas corpus or place the Philippines or any part thereof under martial law…” ☀ line with the UN Charter. Unless sooner withdrawn by resolution of the Congress. What the Constitution allows is a declaration of a “State of War”. VI. Under Art. On Humanitarian Grounds ★ This has recently evolved by international custom ★ Thus. Art. Art. Intervention by Treaty Stipulation or by Invitation “Intervention by Invitation” ★ Presupposes that the inviting State is not a mere puppet of the intervening State ★ EX. shall have the sole power to declare the existence of a state of war. which is either forcible or backed by the threat of force. voting separately. but subject to the qualification that the debtor state should not refuse or neglect to reply to an offer of arbitration or after accepting the offer. the neutral vessel is seized WHEN INTERVENTION ALLOWED.” 2. 23 – “In times of war…the Congress may. 23(1) – “Congress. in joint session assembled. VII. to exercise powers necessary and proper to carry out a declared national policy. or in the relations between other States. a blockade must not be violated by a neutral State ★ if breached. for a period not exceeding 60 days. such powers shall cease upon the next adjournment thereof. UK. Sec. State B ought to have exhausted peaceful and pacific methods of settlements instead of resorting to the use of force.: 1. or after the arbitration. in reaction to the Venezuelan Incident 4. Sec. authorize the President. he may call out such armed forces to prevent or suppress… invasion…In case. prevent any compromis from being agreed upon. invasion…when the public safety requires it. Germany and Italy blockaded Venezuelan ports to compel it to pay its contractual debts leading Foreign Minister Drago to formulate a doctrine that “ a public debt cannot give rise to the right of intervention. This principle was later adopted in the Second Hague Conference. Tender of Advice Generally Intervention is Prohibited (S Doctrine) ★ Prohibits intervention for the collection of contractual debts. Exceptions 1. Hungary was in internal turmoil. it was still condemned because the Hungarian government was a mere Soviet puppet 3. public or private ★ Formulated by Foreign Minister Luis Drago (Argentina).: 1. Intervention as an Act of Individual and Collective Self-Defense 2. has become a primary source of international law ★ EX.: Hungary In 1956. for a limited period and subject to such restrictions as it may prescribe. he may. Sec. Pacific Blockade ★ one imposed during times of peace ★ were the countries at war. by law. renounces war ☀ charter-member of the Constitution also renounces instrument of national policy This is in which also As UN. authorizing the US-led multilateral force to intervene Notes: RIGHTS OF SOVEREIGNTY AND INDEPENDENCE Intervention It is “the dictatorial interference by a State in the internal affairs of another State. the qualification is known as the Porter resolution. Intervention in Somalia . then a blockade is a legitimate measure ★ in fact. Korean War In fact.” Intervention is Different from “Intercession” ☀ Intercession is allowed! ☀ EX.17 Charter considering that the danger perceived by State B was not imminent. by a vote of 2/3 of both Houses. our war as an PUBLIC INTERNATIONAL LAW 2008 Venezuelan Incident In 1902. Q: Who can declare war? A: No one! The Constitution has withheld this power from the government. 41 – “The SC may decide what measures not involving the use of armed force are to be employed to give effect to its decisions. sea. United States Nicaragua v. Intervention in Bosnia and Kosovo No UN Resolution. a member of the United Nations may bring to the attention of the Security Council or the General Assembly. sea. In particular. blockade. the Arab League.” You are asked by the Philippine Government to draft a position paper opposing the move. specifically discussing the tenability of Arab League’s action from the standpoint of International Law. would have been classified as an armed attack rather than as a mere frontier incident had it been carried out by regular armed forces. sponsors a move to include in the agenda of the General Assembly the discussion of this matter: “The Muslim population of Mindanao. or amount to intervention in the internal or external affairs of other States. may be taken to reflect customary international law. When Use of Force is Allowed under the UN Charter By UNSC Resolution – Arts. (1984 Bar) A: The Muslim secessionist movement is not an international dispute. 51: “Nothing in the present charter shall impair the inherent right of individual or collective self-defense if an armed attack occurs against PUBLIC INTERNATIONAL LAW 2008 a Member of the UN. Philippines has expressed the desire to secede from the Republic of the Philippines in order to constitute a separate and independent state and has drawn attention to the probability that the continuation of the armed conflict in Mindanao constitutes a threat to peace. The attempt of the Arab League to place on the agenda of the General Assembly the Muslim problem in Mindanao can only be views as an interference with a purely domestic affair. which under Article 35(1) of the UN Charter. irregulars or mercenaries. contained in Article 3. the prohibition of armed attacks may apply to the sending by a State of armed bands to the territory of another State. until the SC has taken measures necessary to maintain international peace and security. and other means of communication.” In the exercise of right of self-defense. the exercise of this right is subject to the State concerned having been the victim of an armed attack. paragraph (g). it may be considered to be agreed that an armed attack must be understood as including not merely action by regular armed forces across an international border.” NOTE: There is a limited definition of armed attacks – Nicargua v. and other operations by air. United States “195. and the severance of diplomatic relations. 42 – “Should the SC consider that measures provided for in Article 41 would be inadequate or have proved to be inadequate. postal. but NATO intervened militarily Ground: There was ethnic cleansing by Serbs of ethnic minorities 3. Recognition of Government C. if such an operation. In the case of individual self-defense. 'or its substantial involvement therein'. There appears now to be general agreement on the nature of the acts which can be treated as constituting armed attacks. Such assistance may be regarded as a threat or use of force. These may include complete or partial interruption of economic relations and of rail.” RECOGNITION 3 LEVELS A. of the Definition of Aggression annexed to General Assembly resolution 3314 (XXIX). against armed attacks – Art. But the Court does not believe that the concept of 'armed attack' includes not only acts by armed bands where such acts occur on a significant scale but also assistance to rebels in the form of the provision of weapons or logistical or other support. which carry out acts of armed force against another State of such gravity as to amount to' (inter alia) an actual armed attack conducted by regular forces.18 2. Such dispute can arise only between two or more States. air. 41 and 42 Art. in customary law. Recognition of Belligerency RECOGNITION OF STATE Notes: . telegraphic. sea. Such action may include demonstrations. Intervention in East Timor Purpose: To protect the East Timorese Q: At the United Nations. Measures taken by Members in the exercise of this right of selfdefense shall be immediately reported to the SC and shall not in any way affect the authority and responsibility of the SC under the present Charter to take at any time such action as it deems necessary in order to maintain or restore international peace and security. but also 'the sending by or on behalf of a State of armed bands. This description. through Syria. or land forces of Members of the UN. Reliance on collective self-defense of course does not remove the need for this. Recognition of State B. and it may call upon the Members of the UN to apply such measures. radio. The Court sees no reason to deny that. because of its scale and effects. it may take such action by air.” Art. or land forces as may be necessary to maintain or restore international peace and security. Briefly outline your arguments supporting the Philippine position. groups. using example. it is generally irrevocable. In other words. For example. as a matter of legal right. the Declaratory Theory of Recognition Principle. recognition is a legal matter—not a matter of arbitrary will on the part of one State whether to recognize or refuse to recognize another entity but that where certain conditions of fact exist. while the declaratory theory is the majority view that recognition affirms the pre-existing fact that the entity being recognized already possesses the 1. irrevocable As to Revocability ★ Q: Distinguish recognition of State from recognition of Government. Recognition of government. In the former recognition is regarded as mandatory and legal and may be demanded as a matter of right by any entity that can establish its possession of the four essential elements of a state. Q: Distinguish briefly but clearly between the constitutive theory and the declaratory theory concerning recognition of states. (2004 Bar) A: The constitutive theory is the minority view which holds that recognition is the last element that converts or constitutes the entity being recognized into an international person.thus. may be withheld from a succeeding government brought about by violent or unconstitutional means.e. and the State is under legal duty to accord recognition Declaratory School recognition merely an act that declares as a fact something that has hitherto been uncertain it simply manifests the recognizing State’s readiness to accept the normal consequences of the fact of Statehood . an entity may demand. while the latter recognition is highly political and discretionary. the recognized state already exists and can exist even without such recognition..19 2 Schools of Thought Constitutive School recognition is the act which gives to a political entity international status as a State. on the other hand. it is only through recognition that a State becomes an International Person and a subject of international law . Bangladesh already existed as a state even without such recognition. and that no entity possesses the power. it is entirely a matter of policy and discretion to give or refuse recognition.there is no legal right to demand recognition followed by most nations ★ recognition of a State has now been substituted to a large extent by the act of admission to the United Nations it is the “assurance given to a new State that it will be permitted to hold its place and rank in the character of an independent political organism in the society of nations” PUBLIC INTERNATIONAL LAW 2008 status of an international person. – Objective Test ★ government should be EFFECTIVE and STABLE ★ government is in possession of State machinery ★ there is little resistance to its authority 2. (1975 Bar) A: (1) Recognition of state carries with it the recognition of government since the former implies that a state recognized has all the essential requisites of a state at he time recognition is extended. i.recognition is a political act. Criteria for Recognition Q: Explain. when other countries recognize Bangladesh. (2) Once recognition of state is accorded. to demand recognition . (1991 Bar) A: The declaratory theory of recognition is a theory according to which recognition of a state is merely an acknowledgment of the fact of its existence. Subjective Test – ★ WILLINGNESS and ABILITY ★ the government is willing and able to discharge its international obligations ★ 2 Doctrines Tobar or Wilson Doctrine . Notes: RECOGNITION OF GOVERNMENT Recognition of Government As to Scope Does not necessarily signify that recognition of a State – to government may not be independent Revocable Recognition of State Includes recognition or government – government an essential element of a State Generally. But since under the Constitution. The recognized government or State acquires the right of suing in the courts of law of the recognizing State 3.20 ☀ suggested by Foreign Minister Tobar (Ecuador). Manglapus title [GR 88211 15 Sept. it is the Executive Department that is primarily Recognition endowed with the power to recognize foreign De Facto governments and States. In the Philippines. The certain courts are bound by the acts of political department of the government. The legality and wisdom of recognition accorded any to Limited foreign entity is not subject to judicial review. civil war. Its effect is to preclude the courts of recognizing State from assign judgment on the legality of its acts. The recognized government or State acquires the capacity to enter into diplomatic relations with recognizing States and to make treaties with them 2. civil war. coup d’ etat or other forms of internal violence will not be recognized until the freely elected representatives of the people have organized a constitutional government. past and future. it simply accepts whatever government is in effective control without raising the issue of recognition Q: Distinguish briefly but clearly between the Wilson doctrine and the Estrada doctrine regarding recognition of governments. Thus. The action of the juridical Executive in recognizing or refusing to recognize a relations. Recognition being retroactive. freely elected representatives of the people have organized a constitutional government Estrada Doctrine PUBLIC INTERNATIONAL LAW 2008 ★ Given to a government that satisfies both the objective and subjective criteria Recognition De Facto ★ Given to governments that have not fully satisfied objective and subjective criteria ★ EX. for foreign State or government is properly within the scope of instance. It becomes entitled to demand and receive possession of property situated within the jurisdiction of a recognizing State. other forms of internal violence. 1989] The Constitution limits resort to the political question doctrine and broadens the scope of As to Effect on Properties Abroad Recognition De Jure Vests title to recognized government in properties abroad . it might have not yet acquired sufficient stability Consequences of Recognition of Government 1. VII. a government established by means revolution. [Art. Kinds of Recognition Recognition De Jure As to Duration As to Effect on Diplomatic Relations Relatively permanent Brings about full diplomatic relations/intercourse Q: Who has the authority to recognize? A: It is a matter to be determined according to the municipal law of each State. it judicial notice. reiterated by President Woodrow Wilson (US) ☀ recognition is withheld from governments established by revolutionary means – revolution. 1987 Constitution] Provisional. there is no explicit provision in the Constitution which vests this power in any department. It is immune from the jurisdiction of the courts of law of recognizing State 4.: While wielding effective power. formulated by Mexican Foreign Minister Genaro Estrada ☀ disclaims right of foreign states to rule upon legitimacy of a government of a foreign State ☀ a policy of never issuing any declaration giving recognition to governments – instead. (2004 Bar) A: In the Wilson or Tobar doctrine. which formerly belonged to the preceding government at the time of its supercession 5. while in the Estrada doctrine any diplomatic representatives in a country where an upheaval has taken place will deal or not deal with whatever government is in control therein at the time and either action shall not be taken as a judgment on the legitimacy of the said government. does not Q: Is the bring about recognition extended by the President to a foreign government subject to judicial diplomatic review? immunities A: NO! It is purely a political question. Act of State Doctrine now applies Notes: ☀ a reaction to the Tobar/Wilson Doctrine. Does not vest such Marcos v. the President is empowered to appoint and receive ambassadors and public ministers. coup d’etat. it is conceded that by implication. UNTIL. and is usually not recognized more serious and widespread and presupposes the existence of war between 2 or more states (1st sense) or actual civil war within a single state (2nd sense) governed by the rules on international law as the belligerents may be given international personality Notes: sanctions governed municipal Revised Code. Actual Hostilities amounting to Civil War within a State ☀ Insurgency ☀ there is just 1 State ☀ presuppos es the existence of a rebel movement Developments in a Rebel Movement Stage of Insurgency ★ Earlier/nascent/less-developed stage of rebellion ★ There is not much international complication ★ Matter of municipal law ★ EX. Requisites of Belligerency [COWS] 1. ★ more or less permanent occupation ★ legitimate government must use superior military force to dislodge the rebels 3. and ★ must be so widespread.: Captured rebels are prosecuted for rebellion Stage of Belligerency ★ A higher stage. had Red Cross representatives . 28 Sept. there are some indications they are striving to meet the conditions. They executed common criminals. and administration of justice. as the stage of insurgency becomes widespread ★ Already a matter of international law. BELLIGERENCY 2 Senses of Belligerency 1. cannot be executed Insurgency Belligerency PUBLIC INTERNATIONAL LAW 2008 a mere initial stage of war.: Captures rebels – must be treated like prisoners of war. considered as combatants. hence. leaving no doubt as to the outcome ★ Q: Has the CPP/NPA and MILF complied with these conditions? A: NO! BUT. no matter how premature or improvident such action may appear. seriousness of the struggle. rebellion are by law – Penal i.e. after a trial.. It is like saying they have a government Note: The maintenance of peace and order.21 judicial inquiry…But nonetheless there remain issues beyond the Court’s jurisdiction the determination of which is exclusively for the President…We cannot. Calleja [GR 85750. Note: Abu Sayaff is not a rebel group it is a mere bandit group. which must be so widespread thereby leaving no doubt as to the outcome. an organized civil government that has control and direction over the armed struggle launched by the rebels. question the President’s recognition of a foreign government. for example..” ICMC vs. 1990] A categorical recognition by the Executive Branch that ICMC enjoy immunities…is a political question conclusive upon the Courts in order not to embarrass a political department of Government. State of War between 2 or more States ☀ Belligeren cy ☀ the States at war are called “Belligerent States” 2. are constituent functions of the government ★ Camp Abu-Bakr—MILF almost had control of a substantial portion of territory ★ government had to use all its military might and divert its budget ★ CPP/NPA sends message that they are observing the Laws of War ★ Captured soliders are announced as POWs. It involves a rebel movement. not of municipal law ★ EX. occupation of a substantial portion of the state’s territory. ★ a “provisional government” 2. . Not so extensive as to be difficult to: (1) Administer. Consequences of Recognition of Belligerents 1. Q: Explain. Proclamation by the legitimate government of a blockade of ports held by the rebels ★ Done by Lincoln during the American Civil War ★ Q: What about peace talks? A: NOT implied recognition. Rebels are enemy combatants and accorded the rights of prisoners of war. FORMS OF RECOGNITION 1. circumstances may be such as to become an implied recognition EX. Big enough to sustain the population 4. If a mere insurgency. the recognition of belligerency puts them under responsibility to 3rd States and to the legitimate government for all their acts which do not conform to the laws and customs of war. have a political organization. On the side of the rebels. High Seas (3) Aerial Domain a. Outer Space b. recognition of belligerency. ★ must observe Laws of Neutrality ★ EX. using example.: Holding peach talks in a foreign country. Permanent 2. Implied PUBLIC INTERNATIONAL LAW 2008 EX. Contiguous Zone c. 2. Great Britain recognized a state of belligerency in the United States during the Civil War. Exclusive Economic Zone (EEZ) d. it is the legitimate government that is responsible for the acts of the rebels affecting foreign nationals and their properties. Definite/Indicated with Precision ★ Generally. this means that there are 2 competing governments in 1 country 5. covering not only land.: 1. must abstain from taking part in the hostilities. Air Space b. and are able to maintain such control and conduct themselves according to the laws of war. willingness on the part of the rebels to observe the rules and customs of war. Territory . but also the atmosphere as well CHARACTERISTICS OF TERRITORY 1. the effect of recognition of belligerency is to put them under obligation to observe strict neutrality and abide by the consequences arising from that position. and ★ essentially. it is a purely internal matter – no need for talks abroad TERRITORY OF STATES Territory Defined Characteristics of Territory Modes of Acquisition of Territory (1) Dereliction/Abandonment (2) Cession (3) Conquest/Subjugation (4) Prescription (5) Erosion (6) Revolution (7) Natural Causes COMPONENTS OF TERRITORY (1) Territorial Domain (2) Maritime and Fluvial Domain a. But. and (2) Defend from external aggression Modes of Acquisition of Territory Notes: . For example. ★ EX. Express 2.: cannot execute captured rebels. Territorial Sea b. Laws and customs of war in conducting the hostilities must be observed. Rebel government is responsible for the acts of the rebels affecting foreign nationals and properties. considered as POWs 3. Belligerency exists when a sizable portion of the territory of a state is under the effective control of an insurgent community which is seeking to establish a separate government and the insurgents are in de facto control of a portion of the territory and population. From the point of view of 3rd States.the fixed and permanent portion on the earth’s surface inhabited by the people of the state and over which it has supreme authority consists of the portion of the surface of the globe on which that State settles and over which it has supreme authority an exercise of sovereignty. (1991 Bar) A: Recognition of belligerency is the formal acknowledgment by a third party of the existence of a state of war between the central government and a portion of that state. most acquiesce to restrictions imposed by the rebels. Before recognition as such. Rebels call the foreign country a “neutral state”.22 4. the territory’s limits define the State’s jurisdiction 3. such as visit and search of its merchant ships 4. 2. Continental Shelf e. it must be followed within a reasonable time by effective occupation ☀ effective occupation does not necessarily require continuous display of authority in every part of the territory claimed ☀ an occupation made is valid only with respect to and extends only to the area effectively occupied. Why is this mode then important? A: Past occupations are source of modern boundary disputes ★ Q: When is a territory “terra nullius?” A: Under the Old Concept a territory is not necessarily uninhabited! A territory is terra nullius. Discovery and Occupation b. the people occupying it has a civilization that falls below the European standard. Accretion c. if any places are terra nullius. This was the justification for the Spanish colonization of the Philippines. this old concept is no longer valid under contemporary international law! ★ 2 REQUISITES (1) Discovery/ Possession ☀ Mere discovery gives only an Inchoate Right of Discovery ☀ Q: What is the effect of this right? A: It bars other states. from entering the territory. if. 2. security and defense of the land actually occupied Prescription ★ acquisition of territory by an averse holding continued through a long term of years ★ derivative mode of acquisition by which territory belonging to 1 State is transferred to the sovereignty of another State by reason of the adverse and uninterrupted possession thereof by the latter for a sufficiently long period of time Notes: Discovery and Occupation ★ An original mode of acquisition of territory belonging to no one – “terra nullius” ★ land to be acquired must be terra nullius ★ Q: Today. so that the discovering state may establish a settlement therein an commence administration and occupation. few. Prescription b. when the territory is thinly populated and uninhabited. ☀ under the “Principle of Effective Occupation. Cession c. It may then be effected through a formal proclamation and the symbolic act of raising the state’s national flag. very little actual exercise of sovereign rights is needed in the absence of competition Doctrine of Effective Occupation ☀ discovery alone gives only an inchoate title. within a reasonable time. .23 (1) By Original Title a. and the European colonization of Africa. Conquest/Subjugation Other Modes (a) nment (b) (c) (d) Dereliction/Abando Erosion Revolution Natural Causes PUBLIC INTERNATIONAL LAW 2008 ☀ Q: How is this done and effected? A: Possession must be claimed on behalf of the State represented by the discoverer. However. Effective Occupation ☀ Does not necessarily require continuous display of authority in every part of the territory claimed ☀ Authority must be exercised as and when occasion demands ☀ Thus. Once the discovering state begins exercising sovereign rights over the territory. the inchoate right ripens and is perfected into a full title ☀ Q: What if the discovering state fails to exercise sovereign rights? A: The inchoate title is extinguished.” the following doctrines/principles are no longer applicable today: a) Hinterland Doctrine Occupation of coasts results to claim on the unexplored interior b) Right of Contiguity Effective occupation of a territory makes the possessor’s sovereignty extend over neighboring territories as far as is necessary for the integrity. even if occupied. and the territory becomes terra nullius again. “Sector Principle” (2) By Derivative Title a. 24 ★ 2 REQUISITES a) continuous and undisturbed possession ☀ Q: What if there are claims or protests to the State’s possession? A: NOT undisturbed! b) lapse of a period of time ☀ No rule as to length of time required ☀ Question of fact ★ Q: What is the source of this right? A: Roman principle of “usucapio” (long continued use of real property ripened into ownership) Cession ★ a derivative mode of acquisition by which territory belonging to 1 State is transferred to the sovereignty of another State in accordance with an agreement between them ★ a bilateral agreement whereby one State transfers sovereignty over a definite portion of territory to another State E.g. Treaty of cession (maybe an outcome of peaceful negotiations [voluntary] or the result of war[forced]) ★ 2 KINDS: 1. Total Cession - comprises the entirety of 1 State’s domain - the ceding State is absorbed by the acquiring State and ceases to exist - EX.: Cession of Korea to Japan under the 22 Aug. 1910 Treaty 2. Partial Cession - comprises only a fractional portion of the ceding State’s territory - cession of the Philippine Islands by Spain to the US in the Treaty of Paris of 10 Dec. 1988 - Forms: a) Treaty of Sale EX.: (1) Sale by Russia of Alaska to US (2) Sale by Spain of Caroline Islands to Germany b) Free Gifts EX: (1) Cession of a portion of the Horse-Shoe Reef in Lake Erie by UK to US Conquest ★ derivative mode of acquisition whereby the territory of 1 State is conquered in the course of war and thereafter annexed to and placed under the sovereignty of the conquering State ★ the taking possession of hostile territory through military force in time of war and by which the victorious belligerent compels the PUBLIC INTERNATIONAL LAW 2008 ★ ★ ★ ★ enemy to surrender sovereignty of that territory thus occupied acquisition of territory by force of arms however, conquest alone merely gives an inchoate right; acquisition must be completed by formal act of annexation no longer regarded as lawful UN Charter prohibits resort to threat or use of force against a State’s territorial integrity or political independence Conquest is Different from “Military or Belligerent Occupation” ☀ Act whereby a military commander in the course of war gains effective possession of an enemy territory ☀ By itself, does not effect an acquisition of territory Notes: Accretion ★ the increase in the land area of a State caused by the operation of the forces of nature, or artificially, through human labor ★ Accessio cedat principali (accessory follows the principal) is the rule which, in general, governs all the forms of accretion. ★ EX.: (1) Reclamation projects in Manila Bay (2) Polders of the Netherlands COMPONENTS OF TERRITORY TERRITORIAL DOMAIN ★ The landmass people live where the Internal Waters ★ These are bodies of water within the land boundaries of a State, or are closely linked to its land domain, such that they are considered as legally equivalent to national land ★ includes: rivers, lakes and land-locked seas, canals, and polar regions. Rivers ☀ Kinds of Rivers (1) National Rivers Lie wholly within 1 State’s territorial domain – from source to mouth Belongs exclusively to that State EX.: Pasig River (2) Boundary Rivers Separates 2 Different States Belongs to both States: If river is navigable – the boundary line is the middle of the navigable channel “thalweg” If the river is not navigable – the boundary line is the midchannel 25 EX.: St. Lawrence River between US and Canada 1. PUBLIC INTERNATIONAL LAW 2008 Waters adjacent to the coasts of a State to a specified limit Territorial Sea ★ comprises in the marginal belt adjacent to the land area or the coast and includes generally the bays, gulfs and straights which do not have the character of historic waters (waters that are legally part of the internal waters of the State) ★ portion of the open sea adjacent to the State’s shores, over which that State exercises jurisdictional control ★ Basis – necessity of self-defense ★ Effect – territorial supremacy over the territorial sea, exclusive enjoyment of fishing rights and other coastal rights ★ BUT: Subject to the RIGHT OF INNOCENT PASSAGE (a foreign State may exercise its right of innocent passage) ★ Q: When is passage innocent? A: When it is not prejudicial to the peace, good order, or security of the coastal State Notes: (3) Multinational Rivers Runs through several States Forms part of the territory of the States through which it passes EX.: Congo River, Mekong River (4) International Rivers navigable from the open sea, and which separate or pass through several States between their sources and mouths In peacetime, freedom of navigation is allowed or recognized by conventional international law Lakes and Land-locked Seas ☀ If entirely enclosed by territory of 1 state: Part of that State’s territory ☀ If surrounded by territories of several States: Part of the surrounding States Canals ☀ Artificially constructed waterways ☀ GR: Belongs to the State’s territory ☀ XPN: Important Inter-Oceanic Canals governed by Special Regime (1) Suez Canal (2) Panama Canal Historic Waters ☀ Waters considered internal only because of existence of a historic title, otherwise, should not have that charater ☀ EX.: Bay of Cancale in France MARITIME AND FLUVIAL DOMAIN Zones of the Sea Right of Innocent Passage The right of continuous and expeditious navigation of a foreign shop through a State’s territorial sea for the purpose of traversing that sea without entering the internal waters or calling at a roadstead or port facility outside the internal waters, or proceeding to or from internal waters or a call at such roadstead or port facility Q: Explain Innocent Passage. (1991 Bar) A: Innocent passage means the right of continuous and expeditious navigation of a foreign ship through the territorial sea of a State for the purpose of traversing that sea without entering the internal waters or calling at a roadstead or port facility outside internal water or proceeding to or from internal waters or a call at such roadstead or port facility. The passage is innocent so long as it is not prejudicial to the peace, good order or security of the coastal State. Extent and Limitations of Right of Innocent Passage ☀ Extends to ALL ships – merchant and warships ☀ Submarines must navigate on the surface and show their flag ☀ Nuclear-powered ships, ships carrying nuclear and dangerous substances must carry documents and observe special safety measures Q: En route to the tuna fishing grounds in the Pacific Ocean, a vessel registered in Country TW entered the Balintang Channel north of Babuyan Island and with special hooks and nets dragged up red corrals found near Batanes. By International Convention certain corals are protected species. Just before the vessel 26 reached the high seas, the Coast Guard patrol intercepted the vessel and seized its cargo including tuna. The master of the vessel and the owner of the cargo protested, claiming the rights of transit passage and innocent passage, and sought recovery of the cargo and the release of the ship. Is the claim meritorious or not? Reason briefly. (2004 Bar) A: The claim of the master of the vessel and the owner of the cargo is not meritorious. Although their claim of transit passage and innocent passage through the Balintang Channel is tenable under the 1982 Convention on the Law of the Sea, the fact that they attached special hooks and nets to their vessel which dragged up red corrals is reprehensible. The Balintang Channel is considered part of our internal waters and thus is within the absolute jurisdiction of the Philippine government. Being so, no foreign vessel, merchant or otherwise, could exploit or explore any of our natural resources in any manner of doing so without the consent of our government. Q: What is the extent of the territorial sea? A: 1. Formerly, 3 nautical miles from the low water mark based on the theory that this is all that a State could defend. This has been practically abandoned. 2. 1982 Convention of the Law of the Sea provides the maximum limit of 12 nautical miles from the baseline. Q: What is the baseline? A: Depends on the method: 1. Normal Baseline Method ☀ Territorial sea is drawn from the lowwater mark. ☀ Q: What is the low-water mark? A: The line on the shore reached by the sea at low tide. Otherwise known as the “baseline.” 2. Straight Baseline Method ☀ A straight line is drawn across the sea, from headland to headland, or from island to island. That straight line then becomes the baseline from which the territorial sea is measured. ☀ Q: What happens to the waters inside the line? A: Considered internal waters. However, the baseline must not depart to any appreciable extent from the general direction of the coast ☀ Q: When is this used? A: When the coastline is deeply indented, or when there is a fringe of islands along the coast in its immediate vicinity. Distinguish briefly but clearly between the territorial sea and the internal waters of the Philippines. (2004 Bar) PUBLIC INTERNATIONAL LAW 2008 Territorial water is defined by historic right or treaty limits while internal water is defined by the archipelago doctrine. The territorial waters, as defined in the Convention on the Law of the Sea, has a uniform breadth of 12 miles measured from the lower water mark of the coast; while the outermost points of our archipelago which are connected with baselines and all waters comprised therein are regarded as internal waters. 2. ★ Contiguous Zone zone adjacent to the territorial sea, over which the coastal State may exercise such control as is necessary to: Prevent infringement of its customs, fiscal, immigration or sanitary laws within its territory or territorial sea; Punish such infringement ☀ extends to a maximum of 24 nautical miles from the baseline from which the territorial sea is measured. 3. Exclusive Economic Zone ☀ a maximum zone of 200 nautical miles from the baseline from which the territorial sea is measured, over which, the coastal State exercises sovereign rights over all the economic resources of the sea, sea-bed and subsoil Notes: Rights of other States in the EEZ (a) Freedom of navigation and overflight (b) Freedom to lay submarine cables and pipelines (c) Freedom to engage in other internationally lawful uses of the sea related to said functions Rights of Land-locked States Right to participate, on an equitable basis, in the exploitation of an appropriate part of the surplus of the living resources of the EEZ of the coastal States of the same sub-region or region Distinguish briefly but clearly between the contiguous zone and exclusive economic zone. (2004 Bar) The contiguous zone is the area which is known as the protective jurisdiction and starts from 12th nautical mile from low water mark (baseline), while the EEZ is the area which ends at the 200th nautical mile from the baseline. In the latter, no state really has exclusive ownership of it but the state which has a valid claim on it according to the UN Convention on the Law of the Seas agreement has the right to explore and exploit its natural resources; while in the former the coastal state may exercise the control necessary to a) prevent infringement of its customs, fiscal immigration or sanitary regulations within its territory b) punish infringement of the above regulations within its territory or territorial sea. Q: Enumerate the rights of the coastal state in the exclusive economic zone. (2005, 2000 Bar) 27 A: The following are the rights of the coastal state in the exclusive economic zone: 1. sovereign rights for the purpose of exploring and exploiting, conserving and managing the living and nonliving resources in the superjacent waters of the sea-bed and the resources of the sea-bed and subsoil; 2. sovereign rights with respect to the other activities for the economic exploitation and exploration of the zone or EEZ, such as production of energy from water, currents and winds; 3. jurisdictional right with respect to establishment and use of artificial islands; 4. jurisdictional right as to protection and preservation of the marine environment; and 5. jurisdictional right over marine scientific research 6. other rights and duties provided for in the Law of the Sea Convention. (Article 56, Law of the Sea Convention) These treaty provisions form part of the Philippine Law, the Philippines being a signatory to the UNCLOS. 4. Continental Shelf Q: Explain the meaning of continental shelf. (1991 Bar) A: The continental shelf comprises the seabed and subsoil of the submarine areas that extend beyond the territorial sea throughout the natural prolongation of its land territory to the outer edge of the continental margin; or to a distance of more than 200 nautical miles from the baselines form which the breadth of the territorial sea is measured where the outer edge of the continental shelf does not extend up to that distance. Rights of the Coastal State ☀ sovereign rights for the purpose of exploring and exploiting its natural resources ☀ rights are exclusive – if the State does not explore or exploit the continental shelf, no one may do so without its express consent Archipelagic Doctrine 2 Kinds of Archipelagos: 1. Coastal Archipelago ☀ situated close to a mainland, and may be considered part of such mainland 2. Mid-Ocean Archipelago ☀ groups of islands situated in the ocean at such distance from the coasts of firm land (mainland) ☀ EX.: Philippines PUBLIC INTERNATIONAL LAW 2008 emphasizes the unity of land and waters by defining an archipelago either as: A group of island surrounded by waters; or A body of water studded with islands thus, baselines are drawn by connecting the appropriate points of the outermost islands to encircle the islands within the archipelago. Rules Governing the Baselines (a) Such baselines should not depart radically from the general direction of the coast, or from the general configuration of the archipelago (b) Within the baselines are included the main islands an area with a maximum water area to land area ratio of 9:1 (c) Length of baselines shall not exceed 1— nautical miles XPN: Up to 3% of the total number of baselines may have a maximum length of 125 nautical miles Effect of the Baselines (a) The waters inside the baselines are considered internal waters; (b) The territorial sea, etc. are measured from such baselines; (c) Archipelagic State exercises sovereign rights over all the waters enclosed by the baselines Limitation – Archipelagic Sealanes ☀ Archipelagic State must designate sea lands an air route for the continuous and expeditious passage of foreign ships and aircraft through or over its archipelagic waters and adjacent territorial sea Passage only for continuous, expeditious, and unobstructed transit between 1 part of the high seas or an EEX to another part of the high seas or an EEZ Q: What if none are designated? A: Right of archipelagic sealane passage may still be exercised through the routes normally used for international navigation The Philippines adheres to the Archipelagic Doctrine – Art. I, 1987 Constitution: “The waters around, between, and connecting the islands of the archipelago, regardless of their breadth and dimensions, form part of the internal waters of the Philippines.” Also embodied in the 1982 Convention of the Law of the Sea, Art. 47 Notes: (1986 Bar) A: The motion to quash should be sustained. The dispute was referred by agreement to the Permanent Court of International Justice which held in a split decision that Turkey had “not acted in conflict with the principles of International Law. collided with a Turkish collier. or c. with all the islands and waters embraced therein. Deep Sea Bed ☀ The sea-bed beyond the continental shelf ☀ Under the UNCLOS – resources of the deep seabed are reserved as the “common heritage of mankind” Q: In the Pacific Ocean. the Norweigian Embassy. The principle that vessels on the high seas are subject to no authority except that the flag State whose flag they fly was thus affirmed. Lotus. involving the penal or disciplinary responsibility of Notes: ★ ★ The regime of the High Seas belongs to everyone and to no one – both res commones and res nullius everyone may enjoy the following rights over the high seas: (a) Navigation (b) Fishing (c) Scientific research (d) Mining (e) Laying of submarine cables or pipelines. Be commenced when the ship is within the pursuing State’s: a. or dimensions are merely internal waters. Contiguous Zone 2.” ☀ The pursuit must: 1. In the Lotus case [PCIJ Pub 198i2 Series A No 10 p. b. 1994. 1979. in his book however. outside of Turkish territorial waters. NOTE: Justice Jorge Coquia. Northern Samar. after its ratification by more than the required 60 of the signatory States Q: What do you understand by the archipelagic doctrine? Is this reflected in the 1987 Constitution? (1989. As a result. and thus on Turkish territory. opined that the ruling in the Lotus case is no longer controlling in view of Art. Warships. That of a 3rd State 5. it requires that baselines be drawn by connecting the appropriate points of the outermost islands to encircle the islands within the archipelago. Article I. Boz Kourt. a Norweigian freighter collides with Philippine Luxury Liner resulting in the death of ten (10) Filipino passengers. or b. the accused were on board a Norweigian vessel and only a Norweigian court can try the case even if the death occurred on a Philippine ship. regardless of their breadth and dimensions form part of the internal waters of the Philippines. Territorial Sea. PUBLIC INTERNATIONAL LAW 2008 a. the Norweigian captain and the helmsman assisting were arrested and charged with multiple homicide through reckless imprudence. between. and (f) other human activities in the open sea and the ocean floor ★ the freedoms extend to the air space above the high seas Doctrine of Hot Pursuit ☀ The pursuit of a foreign vessel undertaken by the coastal State which has “good reason to believe that the ship has violated the laws and regulations of that State. Resolve the motion stating the reason for your decision. or b. Ceases as soon as the foreign ship enters the territorial sea of: a. Continuous and unabated 4. Internal Waters. Apart from filing a protest with the Ministry of Foreign Affairs. or c. and the waters around. For this purpose. It is pointed out that the incident happened on the high seas. a French mail steamer. 1 of the Constitution provides that the national territory of the Philippines includes the Philippine archipelago. The waters on the landward side of the baselines regardless of breadth. The Lotus proceeded to Constantinople where its officers were tried and convicted for manslaughter. Be undertaken by: .” because the act committed produced affects on board the Boz Kourt under Turkish flag. Military aircraft. eight (8) Turkish subjects died.28 UNCLOS became effective on 16 Nov. while on its way to Northern Samar to load copra. The French government protested on the ground that Turkey had no jurisdiction over an act committed on the high seas by foreigners on board foreign vessels whose flag state has exclusive jurisdiction as regards such acts. Other ships/aircraft cleared and identifiable as being in the government service and authorized to that effect ☀ Also applies to violations of laws and regulations of the coastal State applicable to the EEZ and to the continental shelf. The collision took place in the Aegean Sea. 97 of the UN Convention on the Law of the Sea which provides that in the event of collision or any other incident of navigation concerning a ship on the high seas. Its own State. 5. 1975 Bar) A: The archipelagic doctrine emphasizes the unity of land and waters by defining an archipelago either as a group of islands surrounded by waters or a body of water with studded with islands.25]. through a local counsel helps the accused in filing a motion to quash. and connecting the islands of the archipelago. May be continued outside such waters if the pursuit has not been interrupted 3. Upon the Norweigian vessel’s arrival in Catarman. Sec. That it should be near the lowest altitude (perigee) at which artificial earth satellites can remain in orbit without being destroyed by friction with the air around 190 km from earth’s surface . just as the high seas is accessible to ships of all States the State whose aerial space is violated can take measures to protect itself. (c) put down traffic from state to airline. to the limits of the atmosphere ★ does not include the outer space 1. but there must be a genuine link between the state and the ship. the penal or disciplinary proceedings may be instituted only before State of which such person is a national. (b) landing for non-traffic purposes. includes air space above territorial sea ★ NOTE: NO right of innocent passage! PUBLIC INTERNATIONAL LAW 2008 ★ the air space above the high seas is open to all aircraft.) Flag of convenience refers to a state with which a vessel is registered for various reasons such as low or nonexistent taxation or low operating costs although the ship has no genuine link with that state. no arrest or detention of the ship. and (e) embark traffic or put down traffic to or from a third state Notes: 2. d) any ship engaged in unauthorized broadcasting. (2004 Bar) A: Flag state means a ship has the nationality of the flag state it flies. c) slave trade ships. 1998. p. 425. Air Space ★ the air space above the State’s terrestrial and maritime territory ★ “…Every State has complete and exclusive sovereignty over the air space above its territory” ★ Convention on International Civil Aviation –“Territory” – includes terrestrial and maritime territory ★ thus. Freedom of Navigation the right to sail ships on the seas which is open to all States and land-locked countries General Rule: vessels sailing on the high seas are subject only to international law and the laws of the flag state Exceptions: a) foreign merchant ships violating the laws of the coastal State. or flying a false flag or refusing to show its flag. Cases and Materilas on International Law.) AERIAL DOMAIN ★ the airspace above the territorial and maritime domains of the State.. (Harris. (d) embark traffic destined for state of aircraft. Outer Space (res commones) ★ the space beyond the airspace surrounding the earth or beyond the national airspace. even as a measure of navigation shall be ordered by the authorities other than those of the flag state. b) pirate ships. 5th ed.29 the master or any other person in the service of the ship. it is not subject to national appropriation ★ free for all exploration and use by all States and cannot be annexed by any State ★ governed by a regime similar to that of the high seas Treaty on Principles Governing the Activities of States in the Exploration and Use of Outer Space (Outer Space Treaty) ☀ Outer Space is free for exploration and use by States ☀ Cannot be annexed by any State ☀ Its use and exploration must be carried out for the benefit of all countries and in accordance with international law ☀ Celestial bodies shall be used exclusively for peaceful purposes ☀ Nuclear weapons and weapons of mass destruction shall not be placed in orbit around the earth Q: What is the boundary between the air space and the outer space? A: No accepted answer yet! There are different opinions: 1. (Article 91 of the Convention of the Law of the Sea. Flag State the State whose nationality (ship’s registration) the ship possesses. and e) ships without nationality. but it does not mean that States have an unlimited right to attack the intruding aircraft (intruding aircraft can be ordered either to leave the State’s air space or to land) Q: What are the 5 air freedoms? A: (a) overflight without landing. for it is nationality which gives the right to fly a country’s flag Flags of Convenience – registration of any ship in return for a payment fee Q: Distinguish briefly but clearly between the flag state and the flag of convenience. which is completely beyond the sovereignty of any State ★ the moon and the other celestial bodies form part of the outer space (Moon Treaty of 1979) ★ thus. For this purpose. To maintain international peace and security 2. social. not on a boundary line. (1979 Bar) A: No. (Harris. a State on whose registry an object launched into outer space retains jurisdiction over the astronauts while they are in outer space. To be a center of harmonizing the actions of nations towards those common goals. composed originally of only 51 members. In law. the space satellites or objects are under the jurisdiction of States of registry which covers astronauts and cosmonauts. because the outer space and celestial bodies found therein including the moon are not susceptible to the national appropriation but legally regarded as res communes. the moon and the other celestial bodies form part of outer space. To settle their disputes with each other by peaceful means 3. Q: May the USA lay exclusive claim over the moon. Another school of thought proceeds by analogy to the law of the sea. The U. To promote respect for human rights 5. Theoretical limit of air flights is 90 km above the earth 3. 1945. 251253) Under Article 8 of the Treaty on the Principles Governing the Activities of States in the Exploration and Use of Outer Space. the UN has grown rapidly to include most of the states in the world. the height of atmospheric space.N. All its members are equal and all are committed to fulfill in good faith their obligations under the Charter 2. To achieve international cooperation in solving international economic. infinity. Under the Moon Treaty of 1979. What are the principles of the UN? 1. Non-militant flight instrumentalities should be allowed over a second area. Cases and Materials on International Law. 1945. This matter is covered by the Registration of Objects in Space Convention of 1974 and the Liability for Damage Caused by Spaced Objects Convention of 1972. But in theory. cultural and humanitarian problems 4.” And so. What are the principal purposes of the UN? 1. the lowest altitude of an artificial satellite. The boundary between airspace and outer space has not yet been defined. THE UNITED NATIONS The United Nations Formation of the United Nations Purpose of United Nations Principles of United Nations Membership Principal Organs Privileges and Immunities of the United Nations ¯°º°¯ THE UNITED NATIONS It is an international organization created at the San Francisco Conference which was held in the United States from April 25 to June 26. To develop friendly relations among nations 3. Including the Moon and Other Celestial Bodies. as it is commonly called. To refrain form the threat or use of force in their international relations Notes: . Who was the advocate of forming the UN? In his famous Fourteen Points for the peace settlement. the League of Nations was formed. Over that should be outer space. In outer space. pp. the boundary between outer space and airspace has remained undetermined. succeeded the League of Nations and is governed by a Charter which came into force on October 24. It proposes that a State should exercise full sovereignty up to the height to which an aircraft can ascend. Outer space in this estimate begins from the lowest altitude an artificial satellite can remain in orbit. 5th Ed.. and an altitude approximating aerodynamic lift. this has been estimated to be between 80 to 90 kilometers. but on the nature of the activities Q: What is outer space? Who or which can exercise jurisdiction over astronauts while in outer space? (2003 Bar) A: There are several schools of thought regarding the determination of outer space. Woodrow Wilson called for the establishment of a “general association of nations for world peace under specific covenants for mutual guarantees of political independence and territorial integrity to large and small States alike. such as the limit of air flight. Who coined the name UN? It was President Roosevelt who suggested early in 1942 the name UN for the group of countries which were fighting the Axis powers. Alternative A: Outer space is the space beyond the airspace surrounding the Earth or beyond the national airspace. having explored it and having planted her flag therein to the exclusion of other states? Explain.30 PUBLIC INTERNATIONAL LAW 2008 2.. a contiguous zone of 300 miles. Functional Approach The legal regime governing space activities are based. Suspension of Membership Suspension may occur when a preventive or enforcement action has been taken by the SC. 2. each delegation is entitled only to one vote in the decisions to be made by the GA. Discipline does not suspend the member’s obligations but only the exercise of its rights and privileges as a member. 1. which was accepted by the UN. created in 1947 for a term of one eyar and reestablished in 1949 for an indefinite term. but have been brought into close contact with it because of their purposes and functions. PUBLIC INTERNATIONAL LAW 2008 2 Kinds of Membership a. Little Assembly – Interim Committee. recommend suspension to the GA who shall in turn concur with a 2/3 vote of those present and voting. In the judgment of the Organization. 2. Composed of one delegate for each memberstate. Military Staff Committee 3. General Assembly (GA) 2. To refrain from assisting any State against which the UN is taking preventive or enforcement action. or one member with the concurrence of the majority. such as: 1. World Health Organization 2. Security Council (SC) 3. Economic and Social Council (ESC) 4. Subsequently. The Principal Organs 1. Human Rights Commission Specialized Agencies – not part of the UN. Indonesia resumed its membership. Must be State 2. it meets when the General Assembly is in recess and assists this body in the performance of its functions. Each member is entitled to send no more than 5 delegates and 5 alternates and as many technical and other personnel as it may need. Secretariat Subsidiary Organs – those which was created by the Charter itself or which it allows to be created whenever necessary by the SC or GA. Same voting requirement as to suspension. Elective – those subsequently admitted upon the recommendation of the UN Security Council. ¯°º°¯ UN General Assembly This is the central organ of the UN. International Court of Justice (ICJ) 6. Original b. Special sessions – may be called at the request of the SC. directly. Notes: . Indonesia withdrew its membership from the UN and it was not compelled to remain. International Monetary Fund 3. by 2/3 votes of all GA members b. Regular sessions – every year beginning the third Tuesday of September. Must be Peace-loving 3. upon President Sukarno’s overthrow. GA Sessions 1. Any amendment thus proposed shall be subject to ratification by at least 2/3 of the GA. be able and willing to carry out such obligation. The reason for this system of multiple delegates is to enable the members to attend of several meetings that may be taking place at the same time in the different organs or committees of the Organization. How is Admission conducted? 1. including the permanent members of the SC. The SC may. Recommendation of a qualified majority in the Security Council . by a qualified majority. a majority of the member states. The principal deliberative body of the organization and is vested with jurisdiction over matters concerning the internal machinery and operations of the UN. In 1985. Trusteeship Council (TC) 5. by 2/3 of a general conference called for this purpose by 2/3 of the GA and any 9 members of the SC. Note: Both SC and GA votes must be complied with.31 4. Withdrawal of Membership – Indonesia Case The Charter is silent regarding withdrawal of membership. Approval of the General Assembly (GA) by a vote of at least 2/3 of those present and voting. However. GA Composition Consists of all the members of the UN. Qualifications for Membership 1. Only the SC may lift the suspension by a qualified majority. Technical Assistance Board Proposals for Amendments to the UN Charter and Ratification 2 ways of adopting proposals: a.The affirmative vote of at least 9 members including the Big 5. 2. Must accept the obligations as member 4. Expulsion of a Member The penalty of expulsion may be imposed upon a member which has persistently violated the principles in the UN Charter. Legal Some issues are considered only in plenary meetings. All other matters. are decided by simple majority. some members of the TC and all the members of the ESC. the European Union. The other ten members are elected for 2-year terms by the GA. Supervisory – receives and considers reports from the other organs of the UN. the will of the majority of the members as expressed in resolutions adopted by the Assembly. and 2 from Western Notes: Some Important Functions of the GA 1. Important Questions are decided by 2/3 majority of those present and voting. by the Secretariat of the UN . Constituent – amendment of the charter. Budgetary – controls the finances of the UN 5. to elect the Judges of the International Court of Justice.Social. That work is carried out: a. as well as the moral authority of the world community. to maintain international peace and security in accordance with the principles and purposes of the UN. without objection or without a vote.32 3. to recommend to the General Assembly the appointment of the Secretary-General and. b. PUBLIC INTERNATIONAL LAW 2008 weight of world opinion. to call on Members to apply economic sanctions and other measures not involving the use of force to prevent or stop aggression. 4. 2. All issues are voted on through resolutions passed in plenary meetings. The so-called Big Five are China. 2. 8.Economic & Financial • 3rd . 4. ¯°º°¯ UN Security Council An organ of the UN primarily responsible for the maintenance of international peace and security. they carry the . SC Functions and Powers: 1. Elective – important voting functions are also vested in the GA. and the United States. or the vote may be recorded or taken by roll-call. 7. by committees and other bodies established by the Assembly to study and report on specific issues. 5 from the African and Asian states. In plenary meetings.the SecretaryGeneral and his staff of international civil servants. usually towards the end of the regular session. 3. Humanitarian & Cultural • 4th .Special Political & Decolonization • 5th . peacekeeping. Important Questions include: a) peace and security b) membership c) election d) trusteeship system e) budget GA Main Committees Most questions are then discussed in its six main committees: • 1st Committee . to formulate plans for the establishment of a system to regulate armaments. 5 of which are permanent. resolutions may be adopted by acclamation. and 10.that is to say.Disarmament & International Security • 2nd . 1 from Eastern European states. to determine the existence of a threat to the peace or act of aggression and to recommend what action should be taken. to exercise the trusteeship functions of the UN in "strategic areas". 5. to recommend the admission of new Members. GA Voting Rules Each member or delegation has 1 vote in the GA. to take military action against an aggressor. such as the election of the non-permanent members of the SC. While the decisions of the Assembly have no legally binding force for governments. France. and with the SC selects the judges of the ICJ. including the determination of whether a question is important or not. SC Composition Composed of 15 members. the United Kingdom. 9. 3. 6. The work of the UN year-round derives largely from the decisions of the General Assembly . also participates in the amendment of the Charter. while others are allocated to one of the six main committees. together with the Assembly. after the committees have completed their consideration of them and submitted draft resolutions to the plenary Assembly. to investigate any dispute or situation which mightlead to international friction. 2 from Latin American states. Deliberative – discuss principles regarding maintenance of international peace and security and may take appropriate measures toward this end. Voting in Committees is by a simple majority. in international conferences called for by the Assembly. such as disarmament. and c. development and human rights. to recommend methods of adjusting such disputes or the terms of settlement. Their responsibility makes the SC a key influence in the direction of the affairs not only of the Organization but of the entire international community as well.Administrative & Budgetary • 6th . Emergency special session – may be called within 24 hours at the request of the SC by vote of any 9 members or by a majority of the members of the UN. Substantial matters include those that may require the SC under its responsibility of maintaining or restoring world peace to invoke measures of enforcement. Such member is likewise to be invited by the Council to participate (without PUBLIC INTERNATIONAL LAW 2008 vote)in the discussion of any dispute to which the Member is a party.Abstention or absence of a member is not regarded as veto Procedural and Substantive Matters Distinguished Procedural matters include: a. and retiring judges may be re-elected. No member. it may participate (without vote) in the discussion of any question before the Council whenever the latter feels that the interests of that member are specially affected. Rule of Great-Power Unanimity: a negative vote by any permanent member on a non-procedural matter. and c. Elections are held every three years for one-third of the seats. . Their terms have been so staggered as to provide for the retirement of ½ of them every year. the establishment of subsidiary organs. when it replaced the Permanent Court of International Justice which had functioned in the Peace Palace since 1922. Substantive matters – 9 votes including 5 permanent votes. As much as possible. means rejection of the draft resolution or proposal. Notes: . They must be of high moral character. It began work in 1946. ICJ Composition and Qualifications The Court is composed of 15 judges elected to nine-year terms of office by the United Nations General Assembly and Security Council sitting independently of each other. What is the role of a Member of the UN but not a member of the Security Council? Although not a member of the SC. Chairmanship of the SC is rotated monthly on the basis of the English alphabetical order of the names of the members. their degree of readiness and general locations. Q: Loolapalooza conducted illegal invasion and conquest against Moooxaxa. they must represent the main forms of civilization and the principal legal systems of the world. Yalta Voting Formula a. permanent or not. Its seat is at the Peace Palace in The Hague (Netherlands). all members should be represented at all times at the seat of the Organization. but distinction is made between the permanent and the nonpermanent members in the decision of substantive questions. questions relating to the organization and meetings of the Council. Procedural matters – 9 votes of any of SC members b. the participation of states parties to a dispute in the discussion of the SC. The Members of the Court do not represent their governments but are independent magistrates. It operates under a Statute largely similar to that of its predecessor. often referred to as “veto”. and 3. The UN Security Council called for enforcement action against Loolapalooza. and the nature of the facilities and assistance to be supplied by UN members. International Court of Justice International Court of Justice Composition Qualifications Jurisdiction Functions of International Court of Justice Procedure ¯°º°¯ International Court of Justice The International Court of Justice is the principal judicial organ of the United Nations. which is an integral part of the Charter of the United Nations. These members are not eligible for immediate reelection. Does enforcement action include sending of fighting troops? A: NO. For this purpose.33 European and other states. QUALIFICIATIONS OF JUDGES 1. Compliance with the resolution calling for enforcement action does not necessarily call for the sending of fighting troops. even if it has received 9 affirmative votes. 2. is allowed to vote on questions concerning the pacific settlement of a dispute to which it is a party. Possess the qualifications required in their respective countries for appointment to the highest judicial office or are jurists of recognized competence in international law. It may not include more than one judge of any nationality. SC Sessions The SC is required to function continuously and to hold itself in readiness in case of threat to or actual breach of international peace. b. There must be a special agreement with the SC before sending of fighting troops may be had and such agreement shall govern the numbers and types of forces. SC Voting Rules Each member of the SC has 1 vote. and an oral phase consisting of public hearings at which agents and counsel address the Court. it may also establish a special chamber.e. The judgment is final and without appeal. the quorum being nine when it is sitting en banc. In case of tie. it is the Court itself which decides. the President or his substitute shall have a casting vote. The latest version of the Rules dates from 5 December 2000. Article 36(1): The jurisdiction of the Court comprises all cases which the parties refer to it and all matters specially provided for in the Charter of the UN or in treaties and conventions in force. Functions of ICJ The principal functions of the Court are: 2. counsel or advocate for one of the parties. and in the Rules of Court adopted by it under the Statute. a number of them having been made subject to the exclusion of certain categories of dispute. ICJ Jurisdiction The Court is competent to entertain a dispute only if the States concerned have accepted its jurisdiction in one or more of the following ways: a. The declarations of 65 States are at present in force. one of them may refer the dispute to the Court. b. Candidates obtaining an absolute majority in the GA and SC are considered elected. Notes: . when they are parties to a treaty containing a provision whereby. No group shall nominate more than four persons and not more than two of whom shall be of their own nationality. Nomination made by national groups in accordance with the Hague Conventions of 1907. the judges elected shall fill the remaining vacancies. in which the parties file and exchange pleadings. to decide contentious case. 2. In cases of doubt as to whether the Court has jurisdiction. only the eldest is chosen. in the event of a disagreement over its interpretation or application. Procedure in the ICJ The procedure followed by the Court in contentious cases is defined in its Statute. The proceedings include a written phase. or in any other capacity. The Member States of the United Nations (at present numbering 191) are so entitled. i. In cases when membership is not completed by the regular elections. Term of Office Term of 9 years. through the reciprocal effect of declarations made by them under the Statute whereby each has accepted the jurisdiction of the Court as compulsory in the event of a dispute with another State having made a similar declaration. or as a member of a national or international court.. T The Court discharges its duties as a full court but. Immediate re-election is allowed. typically. In July 1993 the Court also established a seven-member Chamber to deal with any environmental cases falling within its jurisdiction ICJ Voting Rules All questions before the Court are decided by a majority of the judges present. at the request of the parties. may also be re-elected. As the Court has two official languages (English and French) everything written or said in one language is translated into the other. After the oral proceedings the Court deliberates in camera and then delivers its judgment at a public sitting. and 3. to render advisory opinions. • Article 34(1): Only states may be parties in cases before the Court. or of a commission of injury. • 2. staggered at three year year intervals by dividing the judges first elected into three equal groups and assigning them by lottery terms of three. six and nine years respectively. that State may appoint a person to sit as a judge ad hoc for the purpose of the case. 3. If this still fails. Should one of the States involved fail to comply with it. In the event that more than 1 national of the same state obtain the requisite majorities in both bodies. The President and the Vice President elected by the Court for three years. by the conclusion between them of a special agreement to submit the dispute to the Court. ICJ Sessions The Court shall remain permanently in session at the Hague or elsewhere as it may decide. except PUBLIC INTERNATIONAL LAW 2008 during the judicial vacations the dates and duration of which it shall fix. Several hundred treaties or conventions contain a clause to such effect. by virtue of a jurisdictional clause. Only States may apply to and appear before the Court. How members of ICJ are chosen 1. or c. a joint conference shall be convened. Terms of office of 5 of the 15 members shall expire at the end of every 3 years. the other party may have recourse to the Security Council.34 When the Court does not include a judge possessing the nationality of a State party to a case. Who may file contentious cases? Only states can file contentious cases and both must agree to the court’s jurisdiction. Rule for Inhibition of Judges No judge may participate in the decision of a case in which he has previously taken part as agent. A Chamber of Summary Procedure is elected every year by the Court in accordance with its Statute. and the sources of applicable law are the same. Q: The State of Nova. America placed floating mines on the territorial waters surrounding Nova. If either or both America and Nova are not members of the UN. 2(4). it can invoke the defense of lack of jurisdiction. Nova decided to file a case against America in the International Court of Justice. the Court decides which States and organizations might provide useful information and gives them an opportunity of presenting written or oral statements. even if the provision of support is not enough to consider the act a violation of the nonuse of force principle. which have not been redeemed until now? May the suit be brought to the ICJ? (1979 Bar) A: No! Even foreign states are entitled to the doctrine of state immunity in the local state. Will the action prosper? (1978 Bar) A: No! Only States may be parties in contentious cases before the International Court of Justice. this is a violation of the principle of non-intervention in customary international law. 2(4) of the UN Charter. the International Court of Justice considered the planting mines by one state within the territorial waters of another as a violation of Art. America supported a group of rebels organized to overthrow the government of Nova and to replace it with a friendly government. Certain instruments or regulations can. The only bodies at present authorized to request advisory opinions of the Court are five organs of the United Nations and 16 specialized agencies of the United Nations family. America. In addition. only States which are parties to the statute of the ICJ and other states on conditions to be laid down by the Security Council may be such parties. Aggression is the use of armed force by a state against the sovereignty or territorial integrity or political independence of another state or in any other manner inconsistence with the UN Charter. as well as Japan for the “Mickey Mouse” money in payment for private properties. Notes: • Only organizations can request advisory opinions [Article 65(1)]: The Court may give an advisory opinion on any legal question at the request of whatever body may be authorized by or in accordance with the Charter of the UN to make such a request. If the support provided by America to rebels of Nova goes beyond the mere giving of monetary or psychological support but consist in the provision of arms and training. 1) What grounds may Nova’s cause of action against America be based? 2) On what grounds may America move to dismiss the case with the ICJ? 3) Decide the case. no sovereign state can be made a party to a proceeding before the ICJ unless it has given its consent. 2(4) of the UN Charter. was arrested and detained for several years without charges or trial. had unfriendly . (1994 Bar) A: 1) If Nova and America are members of the UN. another neighboring state. Nova may premise its cause of action of violation of the non-use of force principle in customary international law which exist parallel as to Art. In the case concerning the Military and Parliamentary activities in and against Nicaragua (1986 ICJ Report 14). Therefore. Bresia. 2(4) of the UN Charter. which requires members to refrain from threat or use of force against the territorial integrity of political independence of any state. Q: A. however. a private individual like A cannot bring an action before it. In principle the Court's advisory opinions are consultative in character and are therefore not binding as such on the requesting bodies. The suit may not be brought before the ICJ without the consent of the United States as jurisdiction of the ICJ in contentious cases is based upon the consent of the parties. it may invoke such limitations of its consent as a bar to the assumption of jurisdiction. • There is no rule of stare decisis.35 PUBLIC INTERNATIONAL LAW 2008 Advisory Opinions The advisory procedure of the Court is open solely to international organizations. relations with its neighboring state. a citizen of State X. 2) By virtue of the principle of sovereign immunity. He brings his case to the courts of State X. He desires to seek redress from any international forum. He goes to you as counsel to file his case with the International Court of Justice. provide in advance that the advisory opinion shall be binding. In fact. the acts of America can be considered as indirect aggression amount to another violation of Art. Nova can premise its cause of action on a violation of Art. Even if it has accepted the jurisdiction of the ICJ but the acceptance limited and the limitation applies to the case. To forestall am attack. had been shipping arms and ammunitions to Nova for use in attacking America. On receiving a request. but to no avail. Q: May the United States be sued in our courts for the value of private properties requisitioned by its Army during the last World War. controlled by an authoritarian government. The Court's advisory procedure is otherwise modelled on that for contentious proceedings. If America has not accepted the jurisdiction of the ICJ. However. Rome Statute). because America violated the principle against the use of force and the principle of non-intervention. The Philippines signed the Statute on December 28. OFFICE OF THE EXECUTIVE SECRETARY 462 SCRA 622. the Court must. the other party may ask the Court to decide in favor of its claim. before doing so. The defense of anticipatory self-defense cannot be sustained because there is no showing that Nova had mobilized to such an extent that if America were to wait for Nova to strike first it would not be able to retaliate. The Statute was opened for signature by all states in Rome on July 17. 1) Does the ICJ have the jurisdiction to take cognizance of the case? 2) Who shall represent the parties before the Court? 3) What language shall be used in the pleading and the oral arguments? 4) In case State A.” (Article I. Jr. In the absence of an agreement. 3) Under Art. however. 2000 through Charge d’ Affairs Enrique A. whenever one of the parties does not appear before the court or fails to defends its case. Manalo of the Philippine Mission to the United Nations. Q: The sovereignty over certain island is disputed between State A and State B. 39 of the Statute of ICJ. Notes: On Locus Standi of Petitioners The petition at bar was filed by Senator Aquilino Pimentel. Rome Statute). 1988 and had remained open for signature until December 31. The Rome State of the International Criminal Court The Rome Statute established the International Criminal Court which “shall have the power to exercise its jurisdiction over person for the most serious crimes of international concern x x x and shall be complementary to the national criminal jurisdictions. Article VII of the 1987 Constitution. can State B. it is the duty of the executive department to transmit the signed copy of the Rome Statute to the Senate to allow it to exercise its discretion with respect to ratification of treaties. v. Moreover.. the case should be decided in its favor because of the principle of sovereign immunity. PUBLIC INTERNATIONAL LAW 2008 This is a petition for mandamus to compel the Office of the Executive Secretary and the Department of Foreign Affairs to transmit the signed copy of the Rome Statute of the International Criminal Court to the Senate of the Philippines for its concurrence in accordance with §21. acceptance or approval of the signatory states (Article 25. 4) Under Art. However. the official languages of the Court are English and French. the Philippine Coalition for the Establishment of the International Criminal Court which is composed of individuals and corporate entities dedicated to the Philippine ratification of the Rome Statute. 2000 at the United Nations Headquarters in New York. no member of the Court may appear as agent in any case. However. Petitioners invoke (Article 18. JR. under both domestic law and international law. the respondent. crimes against humanity. Garcia J. Issues It is the theory of the petitioners that ratification of a treaty. move for the dismissal of the action? (1994 Bar) A: 1) The ICJ has jurisdiction because the parties have jointly submitted the case to it and have thus indicated their consent to its jurisdiction. the case should be decided in favor of Nova. is a function of the Senate. 16 of the Statute of ICJ. 2) Parties to a case may appoint agents to appear before the ICJ in their behalf. America can involve the principle of anticipatory self-defense recognized under customary international law because Nova is planning to launch an attack against America by using the arms it brought from Bresia. the Task Force Detainees of the . 6 July 2005 En Banc. petitioners submit that the Philippines has a ministerial duty to ratify the Rome Statute under treaty law and customary international law. require that it be subject to ratification. and these agents need not be their own nationals. Its provisions. the Court may authorize a party to use a language other than English or French. These two states agreed to submit their disputes to the ICJ. who asserts his legal standing to file the suit as member of the Senate.36 If the jurisdiction has been accepted. under Art. a member of the House of Representatives and Chairperson of its Committee on Human Rights. if jurisdiction over America is not established. and the crime of aggression as defined in the Statute (Article 5. Hence. Rome Statute) Its jurisdiction covers the crime of genocide. 3) If jurisdiction over America is established. Vienna Convention on the Law of Treaties). 51 of the Statute of ICJ. each party may use the language it prefers. Congresswoman Loretta Ann Rosales. war crimes. the petitioner fails to appear at the oral argument. At the request of any party. satisfy itself that it has jurisdiction and that the claim is well-founded in fact and in law. PIMENTEL. Bianca Hacintha Roque and Harrison Jacob Roque. being the head of state. ratification. it has been held that “to the extent the powers of Congress are impaired. Hence. The petition seeks to order the executive branch to transmit the copy of the treaty to the Senate to allow it to exercise such authority. the President. Philippine Political Law (1996 Ed. The Rome Statute is intended to complement national criminal laws and courts. as member of the institution. Their contention that they will be deprived of their remedies for the protection and enforcement of their rights does not persuade. The Substantive Issue PUBLIC INTERNATIONAL LAW 2008. the Constitution ensures a healthy system of checks and balance necessary in the nation’s pursuit of political maturity and growth [Bayan vs. and exchange of the instruments of ratification. maintain diplomatic relations. We rule in the negative. As regards Senator Pimentel. Philippine Amusement and Gaming Corporation. We disagree. Nonetheless. powers and privileges vested by the Constitution in their office and are allowed to sue to question the validity of any official action which they claim infringes their prerogatives as legislators. They have not shown. Zamora. Factoran. p. Xxx We find that among the petitioners. the President has the sole authority to negotiate with other states. in this case.). only Senator Pimentel has the legal standing to file the instant suit.”[Del Mar vs. that they have sustained or will sustain a direct injury from the nontransmittal of the signed text of the Rome Statute to the Senate. the Constitution provides a limitation to his power by requiring the concurrence of 2/3 of all the members of the Senate for the validity of the treaty entered into by him. is regarded as the sole organ and authority in external relations and is the country’s sole representative with foreign nations(Cortes. 189). 342 SCRA 449 (2000)]. describes the treaty-making process in this wise: The usual steps in the treaty-making process are: negotiation. the President acts as the country’s mouthpiece with respect to international affairs. aged two (2) and one (1). Senator Pimentel. In filing this petition. respectively. In the realm of treatymaking. the Families of Victims of Involuntary Disappearances. xxx The participation of the legislative branch in the treaty-making process was deemed essential to provide a check on the executive in the field of foreign relations (Cortes. since his office confers a right to participate in the exercise of the powers of that institution. and as citizens of the country. Jr. p. signature. in his book on International Law. enter into treaties. The treaty may then be submitted for registration and publication under the U. The Philippine Presidency: A Study of Executive Power (1966).N. supra note 12. By requiring the concurrence of the legislature in the treaties entered into by the President. although this step is not Notes: . legislators have the standing to maintain inviolate the prerogatives. Charter. The other petitioners maintain their standing as advocates and defenders of human rights. Article VII of the 1987 Constitution to mean that the power to ratify treaties belongs to the Senate. 224 SCRA 792 (1993) and a group of fifth year working law students from the University of the Philippines College of Law who are suing as taxpayers. 346 SCRA 485 (2000)] Thus. extend or withhold recognition. the President is vested with the authority to deal with foreign states and governments. while the President has the sole authority to negotiate and enter into treaties. Sufficient remedies are available under our national laws to protect our citizens against human rights violations and petitioners can always seek redress for any abuse in our domestic courts. a juridical entity with the avowed purpose of promoting the cause of human rights and human rights victims in the country. Justice Isagani Cruz. 223] . so is the power of each member thereof. and otherwise transact the business of foreign relations [Cruz. however. a juridical entity duly organized and existing pursuant to Philippine Laws with the avowed purpose of promoting the cause of families and victims of human rights violations in the country.37 Philippines. p. certainly has the legal standing to assert such authority of the Senate. the petitioners interpret Section 21. at the time of filing of the instant petition. and suing under the doctrine of inter-generational rights enunciated in the case of Oposa vs. The petition at bar invokes the power of the Senate to grant or withhold its concurrence to a treaty entered into by the executive branch. 187) As the chief architect of foreign policy. In our system of government. the Rome Statute. the President. p. xxx Xxx Petitioners’ submission that the Philippines is bound under treaty law and international law to ratify the treaty which it has signed is without basis. Upon receipt of the concurrence of the Senate. Ratification is the act by which the provisions of a treaty are formally confirmed and approved by a State. Executive Order No. After the President has ratified the treaty. The negotiations may be brief or protracted. the signature is primarily intended as a means of authenticating the instrument and as a symbol of the good faith of the parties. As earlier discussed. The document is ordinarily signed in accordance with the alternat. The Department of Foreign Affairs shall then prepare the ratification papers and forward the signed copy of the treaty to the President for ratification. the same is opened for signature. is the formal act by which a state confirms and accepts the provisions of a treaty concluded by its representative. being accountable to the people. the same shall be transmitted to the Department of Foreign Affairs. the President has the discretion even after the signing of the treaty by the Philippine representative whether or not to ratify the same. Zamora. It is usually performed by the state’s authorized representative in the diplomatic mission. It is generally held to be an executive act. the Department of Foreign Affairs shall comply with the provisions of the treaty to render it effective. Ratification. but.). 138]. It has been held that a state has no legal or even moral duty to ratify a treaty which has been signed by its plenipotentiaries [Salonga and Yap. which is the next step. Thus. There is Notes: . It mandates that after the treaty has been signed by the Philippine representative. Ratification. Ramos on November 25. It should be underscored that the signing of the treaty and the ratification are two separate and distinct steps in the treaty-making PUBLIC INTERNATIONAL LAW 2008 process. undertaken by the head of the state or of the government (Bayan vs. each of the several negotiators is allowed to sign first on the copy which he will bring home to his own state. depending on the issues involved. supra note 15). After the treaty is signed by the state’s representative. The Vienna Convention on the Law of Treaties does not contemplate to defeat or even restrain this power of the head of states. 172-174]. Public International Law (5th Edition). and may even “collapse” in case the parties are unable to come to an agreement on the points under consideration. 1997 provides the guidelines in the negotiation of international agreements and its ratification. that is. it does not indicate the final consent of the state in cases where ratification of the treaty is required. which they exhibit to the other negotiators at the start of the formal discussions. significantly. By ratifying a treaty signed in its behalf. the instrument is deemed effective upon its signature [Cruz. If that were so. the requirement of ratification of treaties would be pointless and futile. These representatives are provided with credentials known as full powers. a state expresses its willingness to be bound by the provisions of such treaty. Thus. is burdened with the responsibility and the duty to carefully study the contents of the treaty and ensure that they are not inimical to the interest of the state and its people. The signature does not signify the final consent of the state to the treaty. together with the counter-proposals. In fact. which usually also signifies the effectivity of the treaty unless a different date has been agreed upon by the parties. the Department of Foreign Affairs shall submit the same to the Senate for concurrence. This step is primarily intended as a means of authenticating the instrument and for the purpose of symbolizing the good faith of the parties. The purpose of ratification is to enable the contracting states to examine the treaty more closely and to give them an opportunity to refuse to be bound by it should they find it inimical to their interests. International Law (1998 Ed. on the other hand. xxx The last step in the treaty-making process is the exchange of the instruments of ratification. If and when the negotiators finally decide on the terms of the treaty. becomes the basis of the subsequent negotiations. It is for this reason that most treaties are made subject to the scrutiny and consent of a department of the government other than that which negotiated them. 459 issued by President Fidel V. Negotiation may be undertaken directly by the head of state but he now usually assigns this task to his authorized representatives. [emphasis supplied] Petitioners’ arguments equate the signing of the treaty by the Philippine representative with ratification. Where ratification is dispensed with and no effectivity clause is embodied in the treaty.38 essential to the validity of the agreement as between the parties. is the formal act by which a state confirms and accepts the provisions of a treaty concluded by its representatives. It is the ratification that binds the state to the provisions thereof. the Rome Statute itself requires that the signature of the representatives of the states be subject to ratification. It is standard practice for one of the parties to submit a draft of the proposed treaty which. pp. acceptance or approval of the signatory states. and upon states? (1979 Bar) A: All persons within our national territory are subject to the jurisdiction of the Philippines. for example. The role of the Senate. paragraph 4 of the UN Charter. supra note 16. with certain exceptions like heads and diplomatic agents of foreign states. [See Severino vs. such decision is within the competence of the President alone. Although the refusal of a state to ratify a treaty which has been signed in its behalf is a serious step that should not be taken lightly (Salonga and Yap. International Law. Governor-General. Under such situation. Any encroachments upon our territory. It should be emphasized that under our Constitution. but wholly or partly withdrawn from the State’s jurisdiction” by a rule of international law. supra note 18). PUBLIC INTERNATIONAL LAW 2008 ☀ all persons. property. . the power to ratify is vested in the President. refuse to ratify it (Cruz. This Court has no jurisdiction over actions seeking to enjoin the President in the performance of his official duties. The Court. it is within the authority of the President to refuse to submit a treaty to the Senate or. NCC EXTRATERRITORIAL JURISDICTION – ☀ often claimed by States with respect to so-called continuing offenses where the commission of the crime has started in one State and is consummated in another. 366 (1910)].174). is limited only to giving or withholding its consent. Territoriality Principle Q: How can the observance of our law on national theory be enforced upon individuals. specifically under Article II. 16 Phil. transactions and occurrences within the territory of a State are under its jurisdiction. however. Hence. cannot issue the writ of mandamus prayed for by the petitioners as it is beyond its jurisdiction to compel the executive branch of the government to transmit the signed text of Rome Statute to the Senate. may be punished under our own laws. the other state would be justified in taking offense (Cruz. Otherwise. Q: Distinguish “exTERritoriality” and “exTRAterritoriality. ☀ vests jurisdiction in state where offense was committed ☀ Art. or by sanctions allowed under the generally accepted principles of international law. States are required under international law. Territoriality Principle 2. both states have jurisdiction. but wholly or partly withdrawn from the State’s jurisdiction” by a rule of international law Notes: Jurisdiction of States Bases of Jurisdiction 1. Nationality Principle 3. Protective Principle 4. p. Universality Principle Exemptions from Jurisdiction Doctrine of Sovereign Immunity Act of State Doctrine Right of Legation Classes of Heads of Missions Diplomatic Corps Privileges and Immunities Letter of Credence Functions of Diplomatic Representatives Waiver of Diplomatic Immunity and Privileges Duration of Immunity Termination of Diplomatic Relation Consular Immunity 2 Kinds of Consuls Consular Privileges and Immunities ¯°º°¯ BASES OF JURISDICTION A.174). supra note 15). or concurrence.39 no legal obligation to ratify a treaty. Q: What is the meaning or concept of extraterritoriality? (1977 Bar) A: The term “extraterritoriality has been used to denote the status of a person or things physically present on a State’s territory. having secured its consent for its ratification. subject to the concurrence of the Senate. Note: The concept of extraterritoriality is already obsolete. therefore. by a foreign vessel. to respect the territorial integrity of other states.” A: exTERritoriality exTRAterritoriality exception of persons and property from local jurisdiction on basis of international customs used to denote the status of a person or things physically present on a State’s territory. to the ratification (Bayan vs. p. Zamora. 14. but it goes without saying that the refusal must be based on substantial grounds and not on superficial or whimsical reasons. as well as over certain consequences produced within the territory by persons acting outside it. International Law. which cannot be encroached by this Court via a writ of mandamus. supra note 16. however. Guinto. As it is against all. if serious enough as to compromise the peace of its port. the crime will be tried by the local state A. (1996 Bar) a) How can the Republic of Balau invoke its sovereign immunity? Explain. if such acts are adverse to the interest of the national state. generally considered as forbidden. The hijackers were captured in Damaseus and sent to the Philippines for trial. in Public International Law. Where can he be tried? (1979 Bar) A: Under both the English and French rules. the practice is for the foreign government to first secure an executive endorsement of its claim of immunity. b) No. 43 Phil 19 as robbery or forcible depredation in the high seas without lawful authority and done animo furandi and in the spirit and intention of universal hostility. the defense of sovereign immunity is submitted directly to the local court by the foreign state through counsel by filing a motion to dismiss on the ground that the court has no jurisdiction over its person. (1991 Bar) A: Protective Personality Principle is the principle on which the State exercise jurisdiction over the acts of an alien even if committed outside its territory. In one transaction. though neutral to war. defined in People vs. treason. it may be punished in the competent tribunal if any country where the offender may be found or into which he may be carried. Hijacking is actually piracy. NCC. the local buyer complained that the Balau goods delivered to him were substandard and he sued the Republic of Balau before the RTC of Pasig for damages. b) Will such defense of sovereign immunity prosper? Explain. The jurisdiction on piracy unlike all other crimes has no territorial limits. when a state wishes to plead sovereign immunity in a foreign court. The sale of Balau products as a contract involves a commercial activity. it requests the Foreign office of the state where it is being sued to convey to the court that it is entitled to immunity. Rosario. Nationality Principle ☀ a State may punish offenses committed by its nationals anywhere in the world. In the Philippines. genocide Q: A Filipino owned construction company with principal office in Manila leased an aircraft registered in England to ferry construction workers to the Middle East. even where the offenses are perpetrated by non-nationals. The courts of one state may not assume jurisdiction over another state. A: a) By filing a motion to dismiss in accordance with Section 1 (a) Rule 16 of the Rules of Court on the ground that the court has no jurisdiction over its person. Japan if it involves only the members of the crew and is of such a petty nature as not to disturb the peace of the local state. DOCTRINE OF SOVEREIGN IMMUNITY Under this doctrine. ☀ vest jurisdiction in state whose national interests is injured or national security compromised ☀ counterfeiting. Lol-lo. Ruiz and USA vs. whether nationals or non-nationals. Do courts of Manila have jurisdiction over the case? (1981 Bar) PUBLIC INTERNATIONAL LAW 2008 A: Yes. Restrictive Application of the Doctrine of State Immunity Q: The Republic of Balau opened and operated in Manila an office engaged in trading of Balau products with the Philippine products. This is. tax laws C. Universality Principle ☀ A State has extraterritorial jurisdiction over all crimes regardless of where they are committed or who committed them. the aircraft was highjacked by drug traffickers. Piracy is a crime against all mankind. 15.40 Q: A crime was committed in a private vessel registered in Japan by a Filipino against an Englishman while the vessel is anchored in a port of State A. a state enjoys immunity from the exercise of jurisdiction by another state. ☀ vest jurisdiction in state which has custody of offender of universal crimes ☀ piracy. Accordingly. all so may punish it. Protective Principle ☀ States claim extraterritorial criminal jurisdiction to punish crimes committed abroad which are prejudicial to their national security or vital interests. According to the case of Holy See vs. otherwise by the flag state. D. are not neutral to crimes. While on a flight to Saudi Arabia with Filipino crew provided by the lessee. As held by the Supreme Court in the case of USA vs. it was stated that a foreign state couldn’t invoke immunity from suit if it enters into Notes: . In some case. Nor does it matter that the crime was committed within the jurisdictional 3-mile limit of a foreign state for those limits. B. ☀ vest jurisdiction in state of offender ☀ Art. espionage Q: Explain the Protective Personality Principle. submitted a bid to supply 500.000 pairs of combat boots for the use of the Indonesian Army. Diplomatic Immunity. (You can look but you can’t touch. Doctrine of State Immunity. invited for a bid for the supply of 500. The Philippines adheres to restrictive Sovereign Immunity. 3. Courts cannot pass judgment on acts of State done within its territorial jurisdiction. Indonesia went to the Court of Appeals on a petition for certiorari under Rule 65 of the Rules of Court.000 pairs will also be paid for. it will be barred. Indonesia moved to dismiss the counterclaim asserting that it is entitled to sovereign immunity from suit. 2. The trial court denied the motion to dismiss and issued two writs of garnishment upon Indonesian Government funds deposited in the PNB and BPI. As such. and its Officers. An act of State cannot be questioned or made the subject of legal proceedings in court of law. Notes: . the state of Indonesia waived its immunity from suit.000 pairs of combat boots at $30 per pair delivered in Jakarta on or before October 1990. Warships and other public vessels of another State operated for non-commercial purposes. Pan Oriental Shipping Co. It is not right that it can sue in the courts of the Philippines if in the first place it cannot be sued. 4. 95 Phil 905. In its Answer. DIPLOMATIC IMMUNITY THE RIGHT OF LEGATION It is the right to send and receive diplomatic missions. Carpenters. The Ministry of the Army promised to pay for the other 100. 7. ACT OF STATE DOCTRINE Q: What is an Act of State? A: An act of state is an act done by the sovereign power of a country. The counterclaim in this case is a compulsory counterclaim since it arises from the same contract involved in the complaint. as held in Froilan vs. Q: Why? A: Would unduly vex the peace of nations based on the doctrine of sovereign equality of States – “Par in parem non habet imperium” Q: What is the meaning or concept of “Act of State” Doctrine? (1977 Bar) A: The Act of State Doctrine states that every sovereign state is bound to respect the independence of other states and the court of one country will not sit in judgment to the acts of the foreign government done within its territory. PUBLIC INTERNATIONAL LAW 2008 Consent to the exercise of jurisdiction of a foreign court does not involve waiver of the separate immunity from execution. 1990 and received payment for 100. Foreign Merchant vessels exercising the right of innocent passage. which were deposited in the PNB and BPI.000 pairs of combat boots in Jakarta by October 30. Redress of grievances by reason of such acts must be obtained through the means open to be availed of by sovereign powers as between themselves. Immunity of UN Specialized agencies. 1991. Here. it must be set up. the Republic of Indonesia filed an action before the RTC of Pasig. 5. by filing a complaint. The contract was awarded by the Ministry of the Army to Marikina Shoe Corporation and was signed by the parties in Jakarta. Q: Marikina Shoe Corporation failed to deliver any more combat boots. you cannot sue a sovereign State in the courts of another State. Foreign armies passing through or stationed in the territory with the permission of the State. The Court of Appeals should grant the petition of the Indonesian Government insofar as it sought to annul the garnishment of the funds of Indonesia. at which time the said 300. It is strictly not a right since no State can be compelled to enter into diplomatic relations with another State. It is different from Sovereign Immunity from Suit. Above all. Marikina Shoe Corporation sets up a counterclaim for $3.000.000 representing the payment for the 100. The Marikina Shoe Corporation. other International Organizations.) Thus as held in the case of Dexter vs. P2d 705. Marikina Shoe Expo was able to deliver only 200.41 a commercial contract.000 pairs of combat boots are delivered.000 pairs or a total of $3. In February 1990. Republic of Indonesia.000 pairs of combat boots already delivered but unpaid. which has a branch office and with no assets in Indonesia. Exemptions from Jurisdiction 1.000 pairs already delivered as soon as the remaining 300. On June 1. The defendant therefore acquires the right to set up a compulsory counterclaim against it.000. Act of State Doctrine – court of one state will not sit in judgment over acts of government of another state done in its territory. However. the Ministry of the Army. or by its delegate.000. How would the Court of Appeals decide the case? (1991 Bar) A: The Court of Appeals should dismiss the petition in so far as it seeks to annul the order denying the motion of the Government of Indonesia to dismiss the counterclaim. within the limits of the power vested in him. 6. it was held that consent to be sued does not give consent to the attachment of the property of sovereign government. a Philippine Corporation. Diplomatic relations is established by mutual consent between two States. to compel Marikina Shoe Corporation to perform the balance of its obligation under the contract and for damages. otherwise. Exemption from local jurisdiction. a state may shut itself from the rest of the world. representing friendly governments at their request. The members of the diplomatic service. The foreign secretary or minister. Charges d’ affaires accredited to ministers for foreign affairs The diplomatic corps consists of different diplomatic representatives who have been accredited to the local or receiving state. in some cases. Personal inviolability. Right of an official communication. usually informal. as the right of legation is purely consensual. Inviolability of premises and archives. Ambassadors or nuncios accredited to Heads of State and other heads of missions of equivalent rank. It designates his rank and Notes: i. 5.42 Q: Is the state obliged to maintain diplomatic relations with other states? A: No. It consist of two acts: The Inquiry. A doyen du corps or a dean. as Japan did until the close of the 19th century. It is only when the receiving state manifests its agreement or consent that the diplomatic representative is appointed and formally accredited. by which the receiving state indicates to the sending state that such person. representing sending state in receiving state. a policy of isolation would hinder the progress of a state since it would be denying itself of the many benefits available from the international community. addressed by the sending state to the receiving state regarding the acceptability of an individual to be its chief of mission. resulting in strained relations between the sending and receiving state. Functions of Diplomatic Missions 1. and ii. the dean is the Papal Nuncio. and 6. most states now observe the practice of agreation. Letter of Credence (Letre d’ Creance) The document. f. Ambassadors or nuncios accredited to heads of states ii. Envoys. Q: How are the regular diplomatic representatives classified? A: i. heads it. ascertaining by all lawful means conditions and developments in receiving state and reporting thereon to government of sending state. Active right of legation – send diplomatic representatives Passive right of legation – receive diplomatic representatives Resident Missions Classes of heads of missions [ A N E M I C ] a. PUBLIC INTERNATIONAL LAW 2008 Sometimes the state may appoint special diplomatic agents charged with either political or ceremonial duties. The agreement. Exemption from taxation Q: Who are the usual agents of diplomatic intercourse? A: The diplomatic relations of a state are usually conducted through: i. Charges d’affaires accredited to Ministers for Foreign Affairs. which the envoy receives from his government accrediting him to the foreign state to which he is being sent. . d. Q: How are diplomatic representatives chosen? A: The appointment of diplomats is not merely a matter of municipal law for the receiving state is not obliged to accept a representative who is a persona non grata to it. Exemption from subpoena as witness. b. Indeed. The head of state. The Doyen or head of this body is usually the Papal Nuncio. also informal. Envoys ministers and internuncios accredited to Heads of State. e. such as the negotiation of a treaty or attendance at a state function like a coronation or a funeral. or the oldest accredited ambassador or plenipotentiary. 4. ministers and internuncios accredited to heads of states iii. promoting friendly relations between sending and receiving states and developing their economic. Diplomatic Corps A body formed by all diplomatic envoys accredited to the same State. 2. and iii. If it wants to. However. b. by means of which inquiries are addressed to the receiving state regarding a proposed diplomatic representative of the sending state. 3. negotiating with government of receiving state. who is usually the member of the highest rank and the longest service to the state. To avoid such awkward situation. protecting in receiving state interests of sending state and its nationals. c. Q: What is agreation? A: It is a practice of the states before appointing a particular individual to be the chief of their diplomatic mission in order to avoid possible embarrassment. In Catholic countries. ii. cultural and scientific relations. there have been cases when duly accredited diplomatic representatives have been rejected. c. would be acceptable. Privileges and immunities a. national. regional. (See movie “Red Corner” starring Richard Gere). freedom or dignity.43 the general object of his mission and asks that he be received favorably and that full credence be given to what he says on behalf of his state. f) In some cases. representing friendly governments at their request. The receiving state shall permit and protect free communication on the part of the mission for all official purposes. e) Promoting friendly relations between the sending and receiving state and developing their economic. d) The archives and documents of the mission shall be inviolable at any time and wherever they may be. the receiving state shall insure to all members of the mission freedom of movement and travel in its territory. including the residences of the head of the mission and on his means of transport. cultural and scientific relations. personal or real. and the agents of the receiving state may not enter them without the consent of the head of the mission. The official correspondence of the mission shall be inviolable. Such premises. or municipal except in certain specified cases like the imposition of indirect taxes. c) Negotiating with the government of the receiving state. including diplomatic couriers and messages in code or cipher. A diplomatic agent shall be exempt from all dues and taxes. The receiving state shall treat him with due respect and shall take all appropriate steps to prevent any attack on his person. except in certain cases as. and consulates of the sending state wherever situated. Notes: e) f) g) h) i) b) Q: Who may waive the diplomatic immunity and privileges? A: The waiver may be made expressly by the sending state. the mission may employ all appropriate means. civil and administrative jurisdiction of the receiving state. Pointers on Diplomatic Immunities and Privileges The more important are the following: a) The person of a diplomatic agent shall be inviolable and he shall not be liable to any form of arrest or detention. d) Ascertainment through lawful means of the conditions and developments in the receiving state and reporting thereon to the government of the sending state. attachment or execution. However. The diplomatic premises shall be inviolable. Functions of diplomatic representatives The functions of diplomatic mission consist inter alia in: a) Representing the sending state in the receiving state. The mission and its head shall have the right to use the flag and emblem of the sending state on the premises of the mission. In communicating with the government and other missions. A diplomatic agent is not obliged to give evidence as a witness. It may also be done impliedly. Subject to its laws and regulations concerning national security. A diplomatic agent shall enjoy immunity from the criminal. known sometimes as letter patent or letre d’ provision. their furnishings and other property thereon and the means of transportation of the mission shall be immune from PUBLIC INTERNATIONAL LAW 2008 search. waiver of immunity from jurisdiction with regard to civil and administrative proceedings shall not be held to mean implied waiver of the immunity with respect to the execution of c) . Letter Patent (Letre d’ Provision) The appointment of a consul is usually evidenced by a commission. issued by the appointing authority of the sending state and transmitted to the receiving state through diplomatic channels. for example. when the civil action deals with property held by him in a private or proprietary capacity. requisition. b) Protecting in the receiving state the interests of the sending state and its nationals. as when the person entitled to the immunity from jurisdiction commences litigation in the local courts and thereby opens himself to any counterclaim directly connected with the principal claim. The official staff is made up of the administrative and technical personnel of the mission. his immunity from the jurisdiction of the receiving state continues indefinitely as these are the acts attributed not to him but to the sending state. The Foreign Ambassador sought their immediate release. and water motor pumps. and lasts until he leaves. domestic servants enjoy immunities and privileges only to the extent admitted by the receiving state and insofar as they are connected with the performance of their duties. Q: Italy. it provided that any suit arising from the contract shall be filed with the proper courts in the City of Manila. for which a separate waiver shall be necessary. (DFA vs. Since the establishment of a diplomatic mission requires the maintainance and upkeep of the embassy and the residence of the ambassador. such as the domestic servants. (b) At any rate. what should be the court’s ruling on the said defenses? A: (a) As a counsel of Abad. if they are not nationals of or permanent residents in the receiving State. He shall not be liable to any form of arrest or detention. Article 29 of the Vienna Convention on Diplomatic Relations provides: “The person of a diplomatic agent shall be inviolable. water heaters. diplomatic immunities and privileges begin from the moment diplomatic agent arrives in the territory of the receiving state or. if already there. form the moment his appointment is notified to its government. and the member of their respective families. Among the defenses they raised were “sovereign immunity” and “diplomatic immunity”. members of the administrative and technical staff of the diplomatic mission. because the suit relates to a commercial activity. butlers. Claiming that the Maintenance Contract was unilaterally. through its Ambassador. however. Vinzon.44 judgment. 405 SCRA 126 (2003)] Q: A group of high-ranking officials and rank and file employees stationed in a foreign embassy in Manila were arrested outside embassy grounds and detained at Camp Crame on suspicion that they were actively collaborating with “terrorists” out to overthrow or destabilize the Philippine Government. Abad sued the State of Italy and its PUBLIC INTERNATIONAL LAW 2008 Ambassador before a court in the City of Manila. enjoy the privileges and immunities specified in Article 29. generator sets. The contract does not involve a commercial activity of the ambassador. Further. The provision in the contract regarding the venue of lawsuits is not necessarily a wavier of sovereign immunity from suit. As a rule. electrical facilities. refute the defenses of “sovereign immunity” and “diplomatic immunity” raised by the State of Italy and its Ambassador. NLRC. Q: Who else besides the head of the mission are entitled to diplomatic immunities and privileges? A: The diplomatic immunities and privileges are also enjoyed by the diplomatic suite or retinue. however. including those performing clerical work. (b) The court should reject the defenses. Notes: . what advice would you give. Q: Is Diplomatic Immunity a Political Question? A: Diplomatic immunity is essentially a political question and the courts should refuse to look beyond the determination by the executive branch. shall. which must be within a reasonable period following the termination of his mission. (2005 Bar) (a) As counsel of Abad. which consists of the official and non-official staff of the mission. If invited to express your legal opinion on the matter.” Under Article 37 of the Vienna Convention on Diplomatic Relations. baselessly and arbitrarily terminated. It should be interpreted to apply only where Italy elects to sue in the Philippine courts or waives its immunity by a subsequent act. (2003 Bar) A: I shall advise that the high ranking officials and rank and file employees be released because of their diplomatic immunity. for which he may later be sued or prosecuted should he return in a private capacity to the receiving state or fail to leave it in due time after the end of his mission. and cooks and chauffeurs employed by the mission. With respect to his official acts. such as air conditioning units. But this rule does not apply to his private acts. I shall also argue that the ambassador does not enjoy diplomatic immunity. entered into a contract with Abad for the maintenance and repair of specified equipment at its Embassy and Ambassador’s Residence. It was stipulated that the agreement shall be effective for a period of four years and automatically renewed unless cancelled. [Republic of Indonesia v. because it is connected with his official functions. Italy was acting in pursuit of a sovereign activity when it entered into the contract. claiming that the detained embassy officials and employees enjoyed diplomatic immunity. The non-official staff is composed of the household help. I shall argue that the contract is not a sovereign function and that the stipulation that any suit arising under the contract shall be filed with the proper courts of the City of Manila is a waiver of the sovereign immunity from suit of Italy. 1996) Duration of the diplomatic immunities Unless waived. a) Can the foreign ambassador invoke his diplomatic immunity to resist the lessor’s action? b) The lessor gets hold of evidence that the ambassador is about to return to his home country. the Register of Deeds correctly refused registration. the lessor cannot ask the court to stop the departure of the ambassador from the Philippines. in accordance with its laws. The receiving state is under obligation to facilitate the acquisition on its territory. With respect to the “rank and file employees” that are covered by the immunity referred to above. by the sending state of premises necessary for its mission. Under Article 29 of the Vienna Convention. the prohibition in the constitution against the transfer of properties to parties other than the Filipino citizens or corporation 60% of the capital of which is owned by such citizens should be followed. the refusal of the Register of Deeds to register the sale and the issuance of TCT in the name of state X is unjustified. provided that are not nationals or permanent residents of the Philippines pursuant to Article 37(2) of the said Convention. Here. The consul is immune from criminal prosecution ONLY for acts committed by him in connection with his official functions. The Register of Deeds refused to register the sale and to issue Transfer Certificates of Title in the name of State X.45 PUBLIC INTERNATIONAL LAW 2008 Under Article 9 of the Vienna Convention on Diplomatic Relations. The lessor filed an action for the recovery of his property in court. One house is used as the chancery and residence of the ambassador. Is his refusal justified? A: The prohibition in the Constitution against alienation of lands in favor of aliens does not apply to alienation of the same in favor of foreign governments to be used as chancery and residence of its diplomatic representatives. Can the lessor ask the court to stop the ambassador’s departure from the Philippine? (2000 Bar) A: a) No. Q: The United States Ambassador from the Philippines and the American Consul General also in the Philippines quarreled in the lobby of Manila Hotel and shot each other. still he would be covered by the immunity. a diplomatic agent shall not be liable to any form of arrest or detention. b) No. Q: A foreign ambassador to the Philippines leased a vacation house in Tagaytay for his personal use. who are assumed to be diplomatic officers or agents. the remedy is to declare the high-ranking officials and rank and file employees personae non gratae and ask them to leave. For some reason. Therefore. However. Alternative A: Under the Vienna Convention on Diplomatic Relations. if at the time of the arrest they were in “acts performed in the course of their duties. he failed to pay the rentals for more than one year. Makati.” If a driver was among the said rank and file employees and he was arrested while driving a diplomatic vehicle or engaged in related acts. a diplomatic agent “shall not be liable to any form of arrest or detention (Article 29) and he enjoys immunity from criminal jurisdiction (Article 31). the foreign ambassador cannot invoke the diplomatic immunity to resist the action. Under 3(1)(a) of the Vienna Convention on Diplomatic Relations. Termination of Diplomatic Relation A diplomatic mission may come to an end by any of the usual methods of terminating official relations like: Under Municipal Law: [ R A D A R ] a) Resignation b) Accomplishment of the purpose c) Death d) Abolition of the office Notes: . If the said rank and file employees belong to the service staff of the diplomatic mission (such as drivers) they may be covered by the immunity (even if they are not Philippine nationals or residents) as set out in Article 37(3). a diplomatic agent has no immunity in case of a real action relating to private immovable property situated in the territory of the receiving State unless he holds it on behalf of the sending State for purposes of the mission. since he is not using the house in Tagaytay City for the purposes of his mission but merely for vacation. May the Philippine courts take jurisdiction over them for trial and punishment for the crime they may have committed? (1979 Bar) A: The Ambassador is immune from prosecution for all crimes committed by him whether officially or in his private capacity. This immunity may cover the “high ranking officials” in question. Q: The Ambassador of State X to the Philippines bought in the name of his government two houses and lots at Forbes Park. in so far as the house and lot to be used as quarters of the nationals of State X who are studying in De La Salle University are concerned. and the other as quarters for nationals of State X who are studying in De La Salle University. or to assist the latter in obtaining accommodation in some other way. archives and other documents. (1995 Bar) A: Under Article 32 of the Vienna Convention of Diplomatic Relations.extinction of either the sending state or the receiving state will also automatically terminate diplomatic relations between them. b) An action relating to succession in which the diplomatic agent is involved as executor. by means of which the offending diplomat is summarily presented with his passport and asked to leave the country. which is usually severed before the actual commencement of hostilities. if any. Q: Do consuls enjoy their own immunities and privileges? Explain. but not to the same extent as those enjoyed by the diplomats. consular officers are not amenable to the jurisdiction of the judicial or administrative authorities of the receiving state in respect of acts performed in the exercise of consular functions. They are not clothed with diplomatic character and are not accredited to the government of the country where they exercised their consular functions. which is the permission given them by the receiving state to perform their functions therein. this does not apply in respect of a civil action either: a) Arising out of a CONTRACT concluded by a consular officer in which he did not enter expressly or impliedly as an agent of the sending state. they deal directly with local authorities. consuls are entitled to the inviolability of their correspondence. They look mainly after the commercial interest of their own state in the territory of a foreign state. . immunity from jurisdiction for acts performed in their official capacity and exemption from certain taxes and customs duties. the receiving state may resort to the more drastic method of dismissal. freedom of movement and travel. administrator. c) consules electi –may or may not be nationals of the sending state and perform their consular functions only in addition to their regular callings. a consular officer does not enjoy immunity from the criminal jurisdiction of the receiving state. Like diplomats. a diplomatic agent shall enjoy immunity from the criminal jurisdiction of the receiving state. They do not represent their state in its relations with foreign states and are not intermediaries through whom matters of state are discussed between governments. unless he holds it on behalf of the sending state for the purpose of the mission. Q: Discuss the differences. Q: Will the termination of diplomatic relations also terminate consular relations between the sending and receiving states? A: NO. The consular offices are immune only with respect to that part where the consular work is being performed and they may be expropriated for purposes of national defense or public utility. He shall also enjoy immunity from its civil and administrative jurisdiction except in the case of: Notes: a) A real action relating to private immovable property situated in the territory of the receiving state. to wit. c) An action relating to any professional or commercial activity exercised by the diplomatic agent in the receiving state outside of his official functions.the outbreak of war between the sending and receiving states terminates their diplomatic relations. under Article 41 of the Vienna Convention on the Consular Relations. A: Yes. Where the demand is rejected by the sending state.46 e) Removal PUBLIC INTERNATIONAL LAW 2008 Under the International Law: [ W E R ] a) War . 2 Kinds of Consuls b) consules missi – professional or career consuls who are nationals of the sending state and are required to devote their full time to the discharge of their duties. in the privileges or immunities of diplomatic envoys and consular officers from the civil and criminal jurisdiction of the receiving state. and the exequator. Under Article 43 of the Vienna Convention on Consular Relations. b) Extinction . the letter patent or letter ‘de provision. However. OR c) Recall – may be demanded by the receiving state when the foreign diplomat becomes a persona non grata to it for any reason. subject to certain exceptions. heir or legatee as private person and not on behalf of the sending state. Consuls belong to a class of state agents distinct from that of diplomatic officers. On the other hand. However. consuls are liable to arrest and punishment for grave offenses and may be required to give testimony. which is the commission issued by the sending state. Q: Where do consuls derive their authority? A: Consuls derive their authority from two principal sources. On account of military disturbance in Nepal. the meaning of exequator. Section 4 of RA 75 provides that any writ or process issued by any court in the Philippines for the attachment of the . on the assumption that the Kingdom of Nepal grants similar protection to Philippine diplomatic agents. he is a diplomatic agent. E. the lessor. Article 30 and 31 of the Vienna Convention on Diplomatic Relations provide that the papers. Under paragraph 3 of Article 41 of the Vienna Conventions. As secretary. Q: a) A consul of a South American country stationed in Manila was charged with serious physical injuries. The action falls within the exception to the grant of immunity from the civil and administrative jurisdiction of the Philippines. b) No. The purchase price was paid in check drawn upon the Citibank. As consul. The action against the ambassador is a real action involving private immovable property situated within the territory of the Philippines as the receiving state. Q: Explain. E cannot ask for the attachment of the personal properties of the Ambassador. Although the action is a real action relating to private immovable property within the territory of the Philippines. and therefore. how would you resolve the motion to dismiss? (1997 Bar) A: The motion to dismiss should be granted. PUBLIC INTERNATIONAL LAW 2008 goods or chattel of the ambassador of a foreign state to the Philippines shall be void. b) Suppose after he was charged. using example. (1991 Bar) A: Exequator is an authorization from the receiving state admitting the head of a consular post to the exercise of his functions. a consular officer is not immune from the criminal jurisdiction of the receiving state. B filed a complaint against X in the Office of the City Prosecutor of Manila for violation of BP 22. correspondence and the property of the diplomatic agent shall be inviolable. the information was filed against X in the City Court of Manila. he was appointed as his country’s ambassador to the Notes: Q: D. Article 29 of the Vienna Convention on Diplomatic Relations provides: “The person of a diplomatic agent shall be inviolable. Therefore. Under paragraph 1 of Article 3 of the Vienna Convention. Mora. a diplomatic agent against enjoys immunity from the criminal jurisdiction of the receiving state. the vacation house may be considered property held by the Ambassador in behalf of his State (Kingdom of Nepal) for the purposes of the mission. as a secretary in the American Embassy. E cannot ask the court to stop the departure of the Ambassador of the Kingdom of Nepal from the Philippines. a writ of attachment cannot be issued against the furniture and any personal property. if the Philippines appoint a consul general for New York. Moreover. X enjoys diplomatic immunity from the criminal prosecution. May he claim immunity from jurisdiction of the local court? Explain. a secretary and consul in the American embassy in Manila. 63 Phil 249. If you were the judge. vessel or aircraft. the Ambassador of the Kingdom of Nepal to the Philippines leased a house in Baguio City as his personal vacation home. nonetheless. He shall also enjoy immunity from its civil and administrative jurisdiction. unless he holds it on behalf of the sending state for the purpose of the mission. bought from B a diamond ring in the amount of P 50. In Schneekenburger vs. it was held that a consul is not exempt from criminal prosecution in the country where he is assigned. Alternative A: No. However. After preliminary investigation. including its court.47 b) By a third party for DAMAGES arising from an accident in the receiving state caused by a vehicle. which he later gave as a birthday present to his Filipino girlfriend. filed an action for recovery of his property with the RTC of Baguio City. Q: X. c) No. he cannot start performing his functions unless the President of the United States issues an exequator to him. 1989 Bar) a) Can the action of E prosper? b) Can E ask for the attachment of the furniture and other personal properties of d after getting hold of evidence that D is about to leave the country? c) Can E ask the court to stop D’s departure from the Philippines? A: a) Yes Article 31 of the Vienna Convention on Diplomatic Relations provides: “A diplomatic agent shall enjoy immunity from the criminal jurisdiction of the receiving state. D did not receive his salary and allowances from his government and so he failed to pay his rental for more than one year. Because X’s failure to make good of the dishonored check. the check was dishonored for insufficiency of funds.000. He shall not be liable to any form of arrest or detention. Upon presentment for payment. X is not immune from criminal prosecution. such is beyond the civil and administrative jurisdiction of the Philippines. the action will not prosper. (2000. X filed a motion to dismiss the case against him on the ground that he is a Secretary and Consul in the American Embassy enjoying diplomatic immunity from criminal prosecution in the Philippines. except in the case of: A real action relating to private immovable property situated in the territory of the receiving state. For example. the suit against him is a suit against the United States without its consent and is barred by state immunity from suit. Among the defenses raised by Adams is that he has diplomatic immunity. child. and Baker was charged with Violation of the Dangerous Drugs Act. Adams arrived with 30 members of the Philippine National Police. the third state shall accord him inviolability and such other immunities as may be required to ensure his transit. Thus. because he is not performing diplomatic functions. However. Under Article 40 of the Vienna Convention. It was also stated that PUBLIC INTERNATIONAL LAW 2008 after having ascertained the target. b) Yes. I will argue that Adam’s diplomatic immunity cannot be accepted as the sole basis for the dismissal of the damage suit. consuls do not enjoy immunity from the criminal jurisdiction of the receiving state. considering that as a matter of diplomatic practice a diplomatic agent may be allowed or authorized to give evidence as a witness by the sending state. if a diplomatic agent is in the territory of a third state. (b) As counsel of defendant Adams. ascendant. (2005 Bar) (a) As counsel of plaintiff Baker. Q: Adams and Baker are American citizens residing in the Philippines. MUNICHER v. 397 SCRA 244. The search purportedly yielded positive results. (2003)] Notes: JURISDICTIONAL ASSISTANCE Extradition Defined Extradition distinguished from Double Criminality Basis for Allowing Extradition Rules in Interpretation of Extradition Treaty Extradition Distinguished from Deportation Fundamental Principles Governing Extradition Extradition of War Criminals and Terrorists Attentat Clause Five Postulates of Extradition Right of Asylum Asylum Distinguished from Refugees 3 Essentials Elements of Refugees Non-Refoulment Principle Nationality Distinguished from Citizenship Doctrine of Effective Nationality Statelessness ¯°º°¯ Extradition The delivery of an accused or a convicted individual to the State in whose territory he is alleged to have committed a crime by the State on whose territory the alleged criminal or criminal happens to be at the time. mother. His diplomatic status was matter of serious doubt on account of his failure to disclose it when he appeared as principal witness in the earlier criminal (drug) case against Baker. Baker was acquitted. (b) As counsel of Adams. which has granted him a passport visa if such was necessary.R. . although not necessarily a diplomatic personage. argue why his complaint should not be dismissed on the ground of defendant Adams’ diplomatic immunity from suit. Under Article 41 of the Vienna Convention. Adams befriended Baker and became a frequent visitor at his house.48 Philippines. Adams was the prosecution’s principal witness. his diplomatic status was not sufficiently established. descendant or spouse. [Minucher v. The crime of physical injuries is not a grave crime unless it is committed against the above-mentioned persons. He presented Diplomatic Notes from the American Embassy stating that he is an agent of the United States Drug Enforcement Agency tasked with “conducting surveillance operations” on suspected drug dealers in the Philippines believed to be the source of prohibited drugs being shipped to the U. 142396. CA G. for failure to prove his guilt beyond reasonable doubt.S. I shall argue that since he was acting within his assigned functions with the consent of the Philippines. No. I shall argue that Baker has no diplomatic immunity. argue for the dismissal of the complaint. A: (a) As a counsel of Baker. CA. by mere presentation of Diplomatic Notes stating that he is an agent of the US Drug Enforcement Agency. (1995 Bar) A: a) No. conformably with the Vienna Convention on Diplomatic Relations. Consuls are not liable to arrest and detention pending trial except in the case of grave crime and pursuant to a decision by the competent judicial authority. He is not liable to arrest or detention pending the trial unless the offense was committed against his father. the complaint could be barred by the immunity of the foreign sovereign from suit without its consent. Baker then sued Adams for damages for filing trumped-up charges against him. armed with a Search Warrant authorizing the search of Baker’s house and its premises for dangerous drugs being trafficked to the United States of America. Adams would then inform the Philippine narcotic agents to make the actual arrest. One day. Alternative A: (a) As a counsel for Baker. Can his newly gained diplomatic status be a ground for the dismissal of his criminal case? Explain. while proceeding to take up his post. but acting in his official capacity. 11 February 2003 If the acts giving rise to a suit are those of a foreign government done by its foreign agent. It applies to those who are merely charged with an offense but have not been brought to trial. Sometimes. the process of extradition does not involve the determination of the guilt or innocence of an accused. 236. As held by the US Supreme Court in United States v. Galanis: “An extradition proceeding is not a criminal prosecution. Held: Extradition was first practiced by the Egyptians. In sharp contrast. Principle of Double Criminality Sometimes called “no list treaty” The more modern type contains no list of crimes but provides that the offenses in question should be punishable in both states. To begin with. D' Amato. J. 18. 630 [1990]. which contains a specific list of offenses that a fugitive should have committed in order to be extradited. In contradistinction to a criminal proceeding. His guilt or innocence will be adjudged in the court of the state where he will be extradited. Grotius and Vattel led the school of thought that international law imposed a legal duty called civitas maxima to extradite criminals. the US Supreme Court in US v. 18. 425 [1886]). 741 [1998]. 30 L. This has been done generally by treaties x x x Prior to these treaties. and apart from them there was no well-defined obligation on one country to deliver up such fugitives to another. whether bilateral or multilateral. Puno.. 7 S Ct. 139465.whether the duty is legal or moral in character. Ralph C. 1977]) There are other differences between an extradition proceeding and a criminal proceeding. ed. Falk. No. PUBLIC INTERNATIONAL LAW 2008 Modern nations tilted towards the view of Puffendorf and Billot that under international law there is no duty to extradite in the absence of treaty. 139465. 234. 2000. in Secretary of Justice v. to those who have been tried and convicted and have subsequently escaped from custody. Chinese. and the constitutional safeguards that accompany a criminal trial in this country do not shield an accused from extradition pursuant to a valid treaty. 429 F. Chaldeans and AssyroBabylonians but their basis for allowing extradition was unclear. Thus. En Banc) Q: What is the nature of an extradition proceeding? Is it akin to a criminal proceeding? Held: [A]n extradition proceeding is sui generis. It does not apply to persons merely suspected of having committed an offense but against whom no charge has been laid or to a person whose presence is desired as a witness or for obtaining or enforcing a civil judgment. An extradition proceeding is summary in natural while criminal proceedings involve a full-blown trial. Puffendorf and Billot led the school of thought that the socalled duty was but an "imperfect obligation which could become enforceable only by a contract or agreement between states. Hon. Q: What is extradition? To whom does it apply? Held: It is the “process by which persons charged with or convicted of crime against the law of a State and found in a foreign State are returned by the latter to the former for trial or punishment. and those who have been convicted in absentia. 2000. Lantion.. Puno. G. It should not require that the name of the crime described should be the same in both countries. citing United States v. G. Ralph C. as a rule.. held: “x x x it is only in modern times that the nations of the earth have imposed upon themselves the obligation of delivering up these fugitives from justice to the states where their crimes were committed. Lantion.” (Dissenting Opinion. Hence. p. No. the rules of evidence in an extradition proceeding allow admission of evidence under less stringent standards. Galanis. Jan. a criminal case requires proof beyond reasonable doubt for conviction while a fugitive may be ordered extradited “upon showing of the existence of a prima facie case. for trial and punishment. in an extradition proceeding. The classical commentators on international law thus focused their early views on the nature of the duty to surrender an extraditee --. 411. Extradition Law at the Crossroads: The Trend Toward Extending Greater Constitutional Procedural Protections To Fugitives Fighting Extradition from the United States. It is not a criminal proceeding which will call into operation all the rights of an accused as guaranteed by the Bill of Rights. cited in Dissenting Opinion. Supp. due to plain good will. and though such delivery was often made it was upon the principle of comity x x x. Conn.R. 19 Michigan Journal of International Law 729. J.” (Weston. Hon. which are classified under two major types: Older Type One.” (Wiehl. 2nd ed. our courts may adjudge an Notes: . International Law and Order. En Banc) Q: Discuss the basis for allowing extradition. constitutional rights that are only relevant to determine the guilt or innocence of an accused cannot be invoked by an extraditee especially by one whose extradition papers are still undergoing evaluation. in Secretary of Justice v. unlike in a criminal case where judgment becomes executory upon being rendered final. 1215 [D. it was granted due to pacts. Rauscher (119 US 407. at other times.49 The legal duty to extradite a fugitive from justice is based only on treaty stipulations. In terms of the quantum of evidence to be satisfied. Jan.” Finally. It is enough that the particular act charged is a crime in both jurisdictions.R. Gibson asserts that the retroactive application of the extradition treaty amounts to an ex post facto law. 15. 2000. should be interpreted in light of their intent.R.” The concept of due process is flexible for “not all situations calling for procedural safeguards call for the same kind of procedure. Ralph C. The reason for the rule is laid down in Santos III v. Held: [A]ll treaties. This being so. 1990. where we stressed that a treaty is a joint executive-legislative act which enjoys the presumption that “it was first carefully studied and determined to be constitutional before it was adopted and given the force of law in the country. 139465. It took effect in 1990.” (Secretary of Justice v. The said offense is among those enumerated as extraditable in the Treaty. Oct. between extradition and deportation? (1995 Bar) A: BASIS Nature EXTRADITION Normally committed with criminal offenses in the territory of the requesting state Effected for the benefit of the state to which DEPORTATION Even if no crime was committed as long as the alien is extraditable Notes: Benefit Effected for the protection of the state expelling an . if any. No. Both governments have notified each other that the requirements for the entry into force of the Treaty have been complied with. The United States adheres to a similar practice whereby the Secretary of State exercises wide discretion in balancing the equities of the case and the demands of the nation's foreign relations before making the ultimate decision to extradite. the meaning given them by the departments of government particularly charged with their negotiation and enforcement is accorded great weight. This we hold for the procedural due process required by a given set of circumstances “must begin with a determination of the precise nature of the government function involved as well as the private interest that has been affected by governmental action. Aug. Hon. As an extradition proceeding is not criminal in character and the evaluation stage in an extradition proceeding is not akin to a preliminary investigation. 261 [1992]). (2005 Bar) A: The contention of Gibson is not tenable. (Wright v. No.R. 1994 [Kapunan]) Q: The Philippines and Australia entered into a Treaty of Extradition concurred in by the Senate of the Philippines on September 10. 17. Implicit in the treaties should be the unbending commitment that the perpetrators of these crimes will not be coddled by any signatory state. Nothing less than the Vienna Convention on the Law of Treaties to which the Philippines is a signatory provides that “a treaty shall be interpreted in good faith in accordance with the ordinary meaning to be given to the terms of the treaty in their context and in light of its object and purpose. [Wright v. Ralph C. The rule is recognized that while courts have the power to interpret treaties. X x x [A]n equally compelling factor to consider is the understanding of the parties themselves to the RPUS Extradition Treaty as well as the general interpretation of the issue in question by other countries with similar treaties with the Philippines. Gibson. G. who has committed in his country the indictable offense of Obtaining Property by Deception in 1985. there is no merit in the contention that the ruling sustaining an extradition treaty’s retroactive application violates the constitutional prohibition against ex post facto laws. Extradition treaties provide the assurance that the punishment of these crimes will not be frustrated by the frontiers of territorial sovereignty. Oct. 17.” X x x. Article III of the Constitution refers to ex post facto laws. CA. 139465. the due process safeguards in the latter do not necessarily apply to the former. 2000. Northwest Orient Airlines. The treaty is neither a piece of criminal legislation nor a criminal procedural statute. et al. (210 SCRA 256. En Banc [Puno]) Q: Will the retroactive application of an extradition treaty violate the constitutional prohibition against "ex post facto" laws? Held: The prohibition against ex post facto law applies only to criminal legislation which affects the substantial rights of the accused. The prohibition in Section 22. Hon. 235 SCRA 341. Lantion. including the RP-US Extradition Treaty. En Banc [Puno]) Q: What is the difference. Lantion. Rule on Gibson’s contention.50 individual extraditable but the President has the final discretion to extradite him. For his defense. G. It cannot be gainsaid that today. 235 SCRA 341 (1994)] PUBLIC INTERNATIONAL LAW 2008 Q: Discuss the rules in the interpretation of extradition treaties. An extradition treaty is not a criminal law.” (Secretary of Justice v. The Australian government is requesting the Philippine government to extradite its citizen. CA. It ought to follow that the RP-US Extradition Treaty calls for an interpretation that will minimize if not prevent the escape of extraditees from the long arm of the law and expedite their trial. countries like the Philippines forge extradition treaties to arrest the dramatic rise of international and transnational crimes like terrorism and drug trafficking. is a believer in human rights and a former follower of President Harry. self styled Moro rebels long wanted by the authorities for the fatal ambuscade of a bus load of innocent civilians. However. Even if William were in the territorial jurisdiction of Republic A. c) A person extradited can be prosecuted by the requesting state only for the crime for which he was extradited. There is no extradition treaty however between the Philippines and the United States. Republic A can extradite John because under the attentat clause.51 the person being extradited will be surrendered because he is a fugitive criminal in that state How? Effected on the basis of an extradition treaty or upon the request of another state The alien will be surrendered to the state asking for his extradition alien because his presence is inimical to public good PUBLIC INTERNATIONAL LAW 2008 Both Republic A and Republic B have conventional extradition treaties with Republic X. because his offense is a political offense. A. Reacting. William organized groups which held peaceful rallies in front of the Presidential Palace to express their grievances. John’s men were caught by member of the Presidential Security Group. C and D. Alternative A: Republic A may or can refuse the request of extradition of William because he is not in its territory and thus it is not in the position to deliver him to Republic X. On the eve of the assassination attempt. invoking the UN Declaration on Human Rights. In that country. b) Religious and political offenses are generally not extraditable. of which he is charged. (1976 Bar) Q: Sergio Osmeña III and Eugenio Lopez Jr. the Philippine Government. constitutes a political offense. he set out to destabilize the government of President Harry by means of a series of protest actions. B. if the extradition treaty contains an attentat clause. C and D to the Philippines. John fled to Republic A. Alternative A: Republic B can deny the request the request of Republic X to extradite William. and students seeking free tuition. B. Noting the systematic acts of harassment committed by government agents against farmers protesting the seizure of their lands. C and D sought political asylum. . President Harry went on air threatening to prosecute plotters and dissidents of his administration. B. to assassinate President Harry. flew to Hong Kong and then to California USA where they are reportedly seeking political asylum. bent on regaining power which he lost to President Harry in an election. 1976. through proper diplomatic channels sought after their extradition. Q: John is a former President of the Republic X. Fully convinced that he was cheated. and landed in Jakarta Indonesia. who was in Republic B attending a lecture on democracy. Q: On November 1. laborers complaining of low wages. and d) Unless provided for in a treaty. The next day. It is a standard provision of extradition treaties. was advised by his friends to stay in Republic B. escaped from military custody. his acts were not directly connected to any purely political offense. the crime for which a person is extradited must have been committed in the territory of the requesting state. (2002 Bar) A: Republic A can refuse to extradite John. hijacked a PAL lane on its Manila-Davao flight which they forcibly diverted to. William. he may not be extradited because inciting to sedition. His plan was to weaken the government and when the situation became ripe for a take-over. On the basis of the predominance of proportionality test. John was plotting to take over the government and the plan of John to assassinate President Harry was part of such plan. Assuming that the Philippine Government desires the surrender Notes: The unilateral act of the state expelling the alien Where? The undesirable alien may be sent to any state willing to accept him Fundamental Principles Governing Extradition: a) There is no legal obligation to surrender a fugitive unless there is a treaty. May Indonesia grant asylum or should it extradite A. William. because his offense was not a political offense. A. the taking of the life or attempt against the life of a head of state or that of the members of his family does not constitute a political offense and is therefore extraditable. both charged with attempted assassination of President Marcos before the military tribunal. can Republic A deny the request? Why? State your reason fully. such as the one between Republic A and Republic X. If Republic X requests the extradition of John and William. that political offenses are not extraditable. the government charged John with assassination attempt and William with inciting to sedition. on the other hand. It is the only regular system hat has been devised to return fugitives to the jurisdiction of a court Notes: . because the escapees are sought for political offense and can claim the right of asylum under the Universal Declaration of Human Rights. As Whiteman points out. as held in WRIGHT vs. it was held that an extradition treaty applies to Crimes committed before its effectivity unless the extradition treaty expressly exempts them. war criminals are subject to extradition in 1946. the crime for which the extradition is requested must be a crime in both the requesting state and the state to which the fugitive fled. Accordingly. CA. the prohibition against ex post facto laws in Section 22 of Article III of the Constitution applies to penal laws only and does not apply to extradition treaties. using example. governments are adjusting their methods of dealing with criminals and crimes that transcend international boundaries. Q: Explain. the UN General Assembly passed a resolution recommending to members and calling upon all non-members to extradite war criminals. extradition does not define crimes but merely provides a means by which a state may obtain the return and punishment of persons charged with or convicted of having PUBLIC INTERNATIONAL LAW 2008 committed a crime who fled the jurisdiction of the state whose law has been violated. the flight of affluent Criminals from one country to another for the purpose of committing crime and evading prosecution have become more frequent. It is therefore immaterial whether at the time of the commission of the crime for which extradition is sought no treaty was in existence. With the advent of easier and faster means of international travel. the treaty is applicable. This is likely. a) Can France demand the extradition of A. Q: The Extradition Treaty between France and the Philippines is silent as to applicability with respect to crimes committed prior to its effectivity. As territorial sovereign. Doctrine of Reciprocity If the requesting state is shown to be willing to surrender its own nationals for trial by the courts of another country. Extradition of War Criminals and Terrorists (Violators of crimes against international law) As violators of crimes against international law. under the Treaty of extradition between the Philippines and Canada. (1996 Bar) A: a) In Clough vs. the Philippines can request Canada to extradite Filipino who has fled to Canada. extradition treaties are entered into for the purpose of suppressing crime by facilitating the arrest and the custodial transfer of a fugitive from one state to the other. including traitors. since murder is a crime both in the Philippines and Canada. He jumped bail and managed to escape to America. how can this be legally done under International Law? (1978 Bar) A: The Philippines may only request and cannot demand the surrender of the two fugitives. Today. Patrick cannot be tried for illegal recruitment since this is not included in the list of extraditable offenses in the extradition treaty between the Philippines and the United States. for an offense committed in France prior to the effectivity of the treaty? Explain. the detaining state must also surrender its own citizens for trial. “a majority of nations in the world community have come to look upon extradition as the major effective instrument of international co-operation in the suppression of crime”. b) Can A contest his extradition on the ground that it violates the ex post facto provision in the Philippine Constitution? Explain. (1998 Bar) A: Under the principle of specialty in extradition. Patrick protested that he could not be tried for illegal recruitment. Attentat Clause A provision in an extradition treaty that stipulates that the murder of the head of a foreign government or the member of his family should not be considered as a political offense. b) No. Upon surrender of Patrick by the US Government to the Philippines. If at the time of extradition is requested there is in force between the requesting and the requested state a treaty covering the offense on which the request is based. Decide. 5 POSTULATES OF EXTRADITION Extradition Is a Major Instrument for the Suppression of Crime. For example.52 of the above-named fugitives to the Philippines to face trial before the military tribunal. however. unless the United States does not object to the trial of Patrick for illegal recruitment. the principle of Double Criminality. 109 Fed 330. 295 SCRA 341. FIRST. the United States is not obliged to return them but may decide to do so for reasons of comity. Q: Patrick is charged with illegal recruitment and estafa before the RTC of Manila. a French national residing in the Philippines. Strakesh. (1991 Bar) A: The principle of double criminality is the rule in extradition which states that for a request to be honored. Assume that there is an extradition treaty between the Philippines and America and it does not include illegal recruitment as one of the extraditable offenses. In criminal proceedings. which is sui generis . Indeed. the constitutional rights of the accused are at fore. It is not part of the function of the assisting authorities to enter into questions. and whether the person sought is extraditable. otherwise.eloquently speak of his aversion to the processes in the requesting state. if only the accused were willing to submit to trial in the requesting country. our executive branch of government voluntarily entered into the Extradition Treaty. Lantion. More pointedly. as well as his predisposition to avoid them at all cost. all relevant and basic rights in the criminal proceedings that will take place therein. Hearing. or would have been directly attacked for its unconstitutionality. Such failure would discourage other states from entering into treaties with us. Such determination during the extradition proceedings will only result in needless duplication and delay. an extradition treaty presupposes that both parties thereto have examined and that both accept and trust each other’s legal system and judicial process. what is there to stop him.53 competent to try them in accordance with municipal and international law. the demanding government. Service of Notices (1) Immediately upon receipt of the petition. the presiding judge of the court shall. in extradition. as set forth in the Treaty. and Remaining in the requested state despite learning that the requesting state is seeking his return and that the crimes he is charged with are bailable . extradition proceedings are not criminal in nature. is entitled to the delivery of the accused on the issue of the proper warrant. and the other government is under obligation to make the surrender. the treaty would not have been signed. upon extradition to the requesting state. Compliance Shall Be in Good Faith. given sufficient opportunity. is satisfied. The Proceedings Are Sui Generis. which are the prerogative of that jurisdiction. we are bound by pacta sunt servanda to comply in good faith with our obligations under the Treaty. The ultimate purpose of extradition proceedings in court is only to determine whether the extradition request complies with the Extradition Treaty. should it be found proper.” Accordingly. Extradition is merely a measure of international judicial assistance through which a person charged with or convicted of a crime is restored to a jurisdiction with the best claim to try that person. These circumstances point to an ever-present. persons to be extradited are presumed to be flight risks. This principle requires that we deliver the accused to the requesting country if the conditions precedent to extradition. 6. FOURTH. as pointed out in Secretary of Justice vs. The Requesting State Will Accord Due Process to the Accused. extradition hearings would not even begin.in a class by itself – they are not. Prior acts of herein respondent: Notes: c) d) Leaving the requesting state right before the conclusion of his indictment proceedings there. On the other hand. Fulfilling our obligations under the Extradition Treaty promotes comity with the requesting state. That signature signifies our full faith that the accused will be given. SECOND. He has demonstrated that he has the capacity and the will to flee. Temporary Arrest. There Is an Underlying Risk of Flight FIFTH. In other words. Having fled once. underlying high risk of flight. particularly an extradition treaty that hinges on reciprocity. It states: “SEC. and our legislative branch ratified it. Given the foregoing. failure to fulfill our obligations thereunder paints a bad image of our country PUBLIC INTERNATIONAL LAW 2008 before the world community. Hence. it is evident that the extradition court is not called upon to ascertain the guilt or the innocence of the person sought to be extradited. the Philippines must be ready and in a position to deliver the accused. as soon as . the Treaty carries the presumption that its implementation will serve the national interest. THIRD. where it has done all that the treaty and the law require it to do. our duly authorized representative’s signature on an extradition treaty signifies our confidence in the capacity and the willingness of the other state to protect the basic rights of the person sought to be extradited. This prima facie presumption finds reinforcement in the experience of the executive branch nothing short of confinement can ensure that the accused will not flee the jurisdiction of the requested state in order to thwart their extradition to the requesting state. from fleeing a second time? Q: Is the respondent in extradition proceeding entitled to notice and hearing before the issuance of a warrant of arrest? A: Both parties cite section 6 of PD 1069 in support of their arguments. Verily. The present extradition case further validates the premise that persons sought to be extradited have a propensity to flee. Issuance of Summons. By using the phrase “if it appears. for the very purpose of both would have been defeated by the escape of the accused from the requested state. receiving facts and arguments from them.54 practicable. respondent judge gravely abused his discretion when he set the matter for hearing upon motion of Jimenez. upon . We stress that the prima facie existence of probable cause for hearing the petition and. uses the word “immediate” to qualify the arrest of the accused. the court is expected merely to get a good first impression . This “qualification would be rendered nugatory by setting for hearing the issuance of the arrest warrant. if issued. In Ho vs. or should the accused after having received the summons fail to answer within the time fixed. Neither the Treaty nor the Law could have intended that consequence.” To determine probable cause for the issuance of arrest warrants. summon the accused to appear and to answer the petition on the day and hour fixed in the order. for issuing an arrest warrant was already evident from the petition itself and its supporting documents.under oath or affirmation of complainants and the witnesses they may produce. our Extradition Law. does not require a notice or a hearing before the issuance of a warrant of arrest. Verily. the law specifies that the court se a hearing upon receipt of the answer or upon failure of the accused to answer after receiving the summons. however. the Constitution itself requires only the examination .The right of the people to be secure in their persons. The law could not have intended the word as a mere superfluity but on the whole as a means of imparting a sense of urgency and swiftness in the determination of whether a warrant of arrest should be issued. On the Basis of the Constitution Even Section 2 of Article III of our Constitution. Arrest subsequent to a hearing can no longer be considered “immediate”. sending to persons sought to be extradited a notice of the request for their arrest and setting it for hearing at some future date would give them ample opportunity to prepare and execute an escape.sufficient to make a speedy initial determination as regards the arrest and detention of the accused. or at the very least. the silence of the Law and the Treaty leans to the more reasonable interpretation that there is no intention to punctuate with a hearing every little step in the entire proceedings. as argued by petitioner. All we required was that the “judge must have sufficient supporting documents upon which to make his independent judgment. It also bears emphasizing at this point that extradition proceedings are summary in nature. houses. 2 . On the Basis of the Extradition law It is significant to note that Section 6 of PD 1069. and giving them time to prepare and present such facts and arguments. and no search warrant or warrant of arrest shall issue except upon probable cause to be determined personally by the judge after examination under oath or affirmation of the complainant and the witnesses he may produce. had the holding of a hearing at that stage been intended. PUBLIC INTERNATIONAL LAW 2008 Moreover. Hearing entails sending notices to the opposing parties. and effects against unreasonable searches and seizures and seizures of whatever nature and for any purpose shall be inviolable. the word “hearing” is notably absent from the provision.a prima facie finding . Notes: B. which is invoked by Jimenez. Hence. shall be promptly served each upon the accused and the attorney having charge of the case. a priori. papers. immediately upon the filling of the petition. From the knowledge and the material then available to it. He may issue a warrant for the immediate arrest of the accused which may be served any where within the Philippines if it appears to the presiding judge that the immediate arrest and temporary detention of the accused will best serve the ends of justice. never was a judge required to go to the extent of conducting a hearing just for the purpose of personally determining probable cause for the issuance of a warrant of arrest. Evidently. It provides: “Sec. the presiding judge shall hear the case or set another date for the hearing thereof. the law could have easily so provided. People and in all the cases cited therein. (2) The order and notice as well as a copy of the warrant of arrest. after having already determined therefrom that a prima facie finding did not exist.” the law further conveys that accuracy is not as important as speed at such early stage. The trial court is not expected to make an exhaustive determination to ferret out the true and actual situation. In connection with the matter of immediate arrest. and particularly describing the place to be searched and the persons or things to be seized. Hence.” Does this provision sanction RTC Judge Purganan’s act of immediately setting for hearing the issuance of a warrant of arrest? We rule in the negative: A. Upon receipt of the answer. There is no requirement to notify and hear the accused before the issuance of warrants of arrest. ” At most. Where the circumstances —such as those present in an extradition case – call for it. That the offenses for which Jimenez is sought to be extradited are bailable in the United States is not an argument to grant him one in the present case. The provision in the Constitution stating that the “right to bail shall not be impaired even when the privilege of the writ of habeas corpus is suspended” does not detract from the rule that the constitutional right to bail is available only in criminal proceedings. we find no arbitrariness. In the present case validating the act of respondent judge and instituting the practice of hearing the accused and his witnesses at this early stage would be discordant with the rationale for the entire system. In doing so. judges do not conduct a de novo hearing to determine the existence of probable cause. That the case under consideration is an extradition and not a criminal action is not sufficient to justify the adoption of a set of procedures more protective of the accused. That his arrest and detention will not be arbitrary is sufficiently ensured by: 1) The DOJ’s filing in court of the Petition with its supporting documents after a determination that the extradition request meets the requirements of the law and the relevant treaty. what would stop him from presenting his entire plethora of defenses at this stage -. because extradition courts do not render judgments of conviction or acquittal. unless his guilt be proved beyond reasonable doubt. He should apply for bail before the courts trying the criminal cases against him.if he so desires -. where the presumption of innocence is not at issue. the constitutional right to bail “flows from the presumption of innocence in favor of every accused who should not be subjected to the loss of freedom as thereafter he would be entitled PUBLIC INTERNATIONAL LAW 2008 to acquittal. not before the extradition court. when the extradition court hears the Petition for Extradition. They just personally review the initial determination of the prosecutor finding a probable cause to see if it is supported by substantial evidence. we stress that before issuing warrants of arrest. his detention prior to the conclusion of the extradition proceedings does not amount to a violation of his right to due process. a more restrictive one – not the opposite – would be justified in view of respondent’s demonstrated predisposition to flee. We reiterate the familiar doctrine that the essence of due process is the opportunity to be heard but. To stress. It does not apply to extradition proceedings.” the constitutional provision on bail quoted above. in cases of clear insufficiency of evidence on record.” Hence.55 which to verify the findings of the prosecutor as to the existence of probable cause. as well as Section 4 of Rule 114 pf the Rules of Court. Moreover. This scenario is also anathema to the summary nature of extraditions. Contrary to the contention of Jimenez. Q: Is respondent Mark Jimenez entitled to bail during the pendency of the Extradition Proceeding? A: We agree with petitioner: As suggested by the use of the word “conviction. respondent will be given full opportunity to be heard subsequently. It must be noted that the suspension of the privilege of the writ of habeas corpus finds application “only to persons judicially charged for rebellion or offenses inherent in or directly connected with invasion. either. the Court categorically stated that a judge was not supposed to conduct a hearing before issuing a warrant of arrest: “Again. Hence. judges merely further examine complainants and their witnesses. at the same time. a subsequent opportunity to be heard is enough. It follows that the constitutional provision on bail will not apply to a case like extradition. point out that the doctrine does not always call for a prior opportunity to be heard. De Leon. extradition proceedings are separate and distinct from the trial for the offenses for which he is charged. If a different procedure were called for at all. there is no violation of his right to due process and fundamental fairness. In the present case. Q: Will Mark Jimenez detention prior to the conclusion of the extradition proceedings not amount of his right to due process? A: Contrary to his contention. in the immediate deprivation of his liberty prior to his being heard. applies only when a person has been arrested and detained for violation of Philippine criminal laws.” In Webb vs. the second sentence in the constitutional provision on bail merely emphasizes the right to bail in criminal proceedings for the aforementioned offenses. It cannot be taken to mean that the right is available even in extradition proceedings that are not criminal in nature. Notes: . not the certainty of guilt of an accused.in his effort to negate a prima facie finding? Such a procedure could convert the determination of a prima facie case into a fullblown trial of the entire proceedings and possibly make trial of the main case superfluous. If the accused were allowed to be heard and necessarily to present evidence during the prima facie determination for the issuance of a warrant of arrest. judges merely determine personally the probability. ” Accordingly and to best serve the ends of justice. The Court realizes that extradition is basically an executive. adaptable to every situation calling for its application. is that bail is not a matter of right in extradition cases. Indeed. he ran away. It is also worth noting that before the US government requested the extradition of respondent. as a general rule. since this practice would encourage the accused to voluntarily surrender to the requesting state to cut short their detention here. PUBLIC INTERNATIONAL LAW 2008 Q: What are the exceptions to the “No Bail” Rule in Extradition Proceedings? A: The rule. their detention pending the resolution of extradition proceedings would fall into place with the emphasis of the Extradition Law on the summary nature of extradition cases and the need for their speedy disposition. In its barest concept. He already had that opportunity in the requesting state. persons sought to be extradited are able to evade arrest or escape from our custody. so that the vital international and bilateral interests of our country will not be unreasonably impeded or compromised. as well as the power to promulgate rules to protect and enforce constitutional rights.56 2) The extradition judge’s independent prima facie determination that his arrest will best serve the ends of justice before the issuance of a warrant for his arrest. In this light. the extraditee will abide with all the orders and processes of the extradition court.” it also recognizes the limits of its own prerogatives and the need to fulfill international obligations. Hence. But because he left the jurisdiction of the requesting state before those proceedings could be completed. which is not normally a judicial prerogative. we cannot allow our country to be a haven for fugitives. we repeat. “constitutional liberties do not exist in a vacuum.expressly guaranteeing the right to bail in extradition proceedings. through overprotection or excessively liberal treatment. would be a step towards deterring fugitives from coming to the Philippines to hide from or evade their prosecutors. once granted bail. yet instead of taking it. we believe and so hold that. liberty or property” of every person. it would not be good policy to increase the risk of violating our treaty obligations if. those cited by the highest court in the requesting state when it grants provisional liberty in extradition case therein. choose to run and hide. Hence. while this Court is ever protective of “the sporting idea of fair play. any intrusion by the courts into the exercise of this power should be characterized by caution. adopting the practice of not granting them bail. it was hindered from continuing with the due processes prescribed under its laws. the judiciary has the constitutional duty to curb grave abuse of discretion and tyranny. Since this exception has no express or specific statutory basis. only upon a clear and convincing showing of the following: 1) That. the applicant bears the burden of proving the above two-tiered requirement with clarity. as a matter of reciprocity. However. It is “dynamic and resilient. and since it is derived essentially from general principles of justice and fairness. Furthermore. 3) That. it partakes of the nature of police assistance amongst states. proceedings had already been conducted in that country. Jimenez contends that there are special circumstances that are compelling enough for the Court to grant his request for provisional Notes: . we believe that the right to due process is broad enough to include the grant of basic fairness to extraditees. the applicant will not be a flight risk or a danger to the community. Likewise. the due process rights accorded to individuals must be carefully balanced against exigent and palpable government interests. not a judicial. and 2) That there exist special. the right to due process extends to the “life.. In short. In the absence of any provision . humanitarian and compelling circumstances including. after a potential extraditee has been arrested or placed under the custody of the law. and 3) His opportunity. the law or the treaty . instead of facing the consequences of their actions. precision and emphatic forcefulness.in the Constitution. Indeed. responsibility arising from the presidential power to conduct foreign relations. Along this line. The denial of bail as a matter of course in extradition cases falls into place with and gives life to Article 14 of the Treaty.” Too. to apply for bail as an exception to the no-initial-bail rule. His invocation of due process now has thus become hollow. bail may be applied for and granted as an exception. cowards and weaklings who. once he is under the court’s custody. he claims that his detention will disenfranchise his Manila district of 600. including his detention pending the final resolution of the case. Again we are not convinced. not to determine guilt or innocence. We have carefully examined these circumstances and shall now discuss them. so that the criminal process may proceed therein. Consequently. 2. Respondent Jimenez was elected as a member of the House of Representatives. We are not overruling the possibility that petitioner may. to a court’s request to police authorities for the arrest of the accused who is at large or has escaped detention or jumped bail. Thus. By entering into an extradition treaty. if at all. the judge shall make a prima facie finding whether the petition is sufficient in form and in Notes: Respondent Jimenez further contends that because the extradition proceedings are lengthy. as a rule. In People vs. Yet. he stresses that he learned of the extradition request in June 1999. Jalosjos. Immediately upon receipt of the petition for extradition and its supporting documents. the Philippines is deemed to have reposed its trust in the reliability or soundness of the legal and judicial system of its treaty partner. Giving premium to delay by considering it as a special circumstance for the grant of bail would be tantamount to giving him the power to grant bail to himself. True.or the fugitive who has illegally escaped -. Premises considered and in line with Jalosjos. his constituents were or should have been prepared for the consequences of the extradition case against their representative. To support this claim. it would be unfair to confine him during the pendency of the case. which may be granted in accordance with the guidelines in this Decision. Alleged Disenfranchisement PUBLIC INTERNATIONAL LAW 2008 While his extradition was pending.000 residents. supported by its annexes and the evidence that may be adduced during the hearing of the petition. it is settled that bail may be applied for and granted by the trial court at anytime after the applicant has been taken into custody and prior to judgment. However. It must be noted that even before private respondent ran for and won a congressional seat in Manila. In any event. unduly delay the proceedings. This is another matter that is not at issue here. We must emphasize that extradition cases are summary in nature. this fact cannot be taken to mean that he will not flee as the process moves 4) . Discuss the Ten Points in Extradition proceedings. the Court has already debunked the disenfranchisement argument xxx. It is more akin. as well as in the ability and the willingness of the latter to grant basic rights to the accused in the pending criminal case therein. we are constrained to rule against his claim that his election to public office is by itself a compelling reason to grant him bail. if the delay were due to maneuverings of respondent. an extradition case is not one in which the constitutional rights of the accused are necessarily available. the extradition court may continue hearing evidence on the application for bail. By nature then. It would also encourage him to stretch out and unreasonably delay the extradition proceedings even more. extradition proceedings are not equivalent to a criminal case in which guilt or innocence is determined. any further discussion of this point would be merely anticipatory and academic. yet.57 release on bail. 3. with all the more reason would the grant of bail not be justified. upon the resolution of the Petition for Extradition. Having once escaped the jurisdiction of the requesting state. Not a Flight Risk? 2) 3) Jimenez further claims that he is not a flight risk. in bad faith. 1) The ultimate purpose of extradition proceedings is to determine whether the request expressed in the petition. he has not fled the country. We are not persuaded. it was already of public knowledge that the United States was requesting extradition.back to its territory. They are resorted to merely to determine whether the extradition petition and its annexes conform to the Extradition Treaty. That he has not yet fled from the Philippines cannot be taken to mean that he will stand his ground and still be within reach of our government if and when it matters. The proceedings are intended merely to assist the requesting state in bringing the accused -. the reasonable prima facie presumption is that the person would escape again if given the opportunity. Neither is it. that is. as he hears the footsteps of the requesting government inching closer and closer. he has not actually fled during the preliminary stages of the request for his extradition. 1. In the present case. intended to address issues relevant to the constitutional rights available to the accused in a criminal action. On that basis. Anticipated Delay forward to its conclusion. This we cannot allow. complies with the Extradition Treaty and Law and whether the person sought is extraditable. even after bail has been previously denied. Hence. and whether the person sought is extraditable. They should not allow . 18 December 2000. a bulwark of democracy and the conscience of society.58 substance. a bastion of liberty. 9) On the other hand. MUŇOZ G. De Leon. The Philippine DOJ forwarded the request for provisional arrest to the NBI.R. lest these summary extradition proceedings become not only inutile but also sources of international embarrassment due to our inability to comply in good faith with a treaty partner’s simple request to return a fugitive. delays and “over-due process” every little step of the way. the judge immediately issues a warrant for the arrest of the potential extraditee and summons him or her to answer and to appear at scheduled hearing on the petition. ISSUE: Whether Munoz should be provisionally arrested HELD: There was urgency for the provisional arrest of the respondent. respectively. 8) We realize that extradition is essentially an executive. Second Division. Cap 201 of Hong Kong. JUAN ANTONIO MUÑOZ is charged with seven (7) counts of accepting an advantage as an agent contrary to Section 9(1)(a) of the Prevention of Bribery Ordinance of. PUBLIC INTERNATIONAL LAW 2008 contortions. contrary to the common law of Hong Kong. CUEVAS V. the Philippine DOJ received a request for the provisional arrest of MUÑOZ pursuant to the RP-Hong Kong Extradition Agreement. checkmate and defeat the quest for bilateral justice and international cooperation. 140520. But it is also well aware of the limitations of its authority and of the need for respect for the prerogatives of the other coequal and co-independent organs of government. 5) After being taken into custody. he may be punished with seven (7) and fourteen (14) years imprisonment. for each count of which. Since the applicants have a history of absconding. Indeed. it is subject to judicial discretion in the context of the peculiar facts of each case. whether it complies with the Extradition Treaty and the Law. if found guilty. Thus. RTC granted the application. and seven (7) counts of conspiracy to defraud. 6) Potential extraditees are entitled to the rights to due process and to fundamental fairness. 7) This Court will always remain a protector of human rights. bail is not a matter of right. No. courts merely perform oversight functions and exercise review authority to prevent the exercise of grave abuse and tyranny. Thereafter. to avoid the legalistic contortions. “Urgency" connotes such conditions relating to the nature of the offense charged and the personality of the prospective extraditee which would make him susceptible to the inclination if he were to learn about the impending request for his extradition and/or likely to destroy the evidence pertinent to the said request or his eventual prosecution and without which the latter could not proceed. A subsequent opportunity to be heard is sufficient due process to the flight risk involved. responsibility arising out of the presidential power to conduct foreign relations and to implement treaties. mummify. extradition proceedings should be conducted with all deliberate speed to determine compliance with the Extradition Treaty and the Law. available during the hearings on the petition and the answer is the full chance to be heard and to enjoy fundamental fairness that is compatible with the summary nature of extradition. or to personally examine the affiants or witnesses. not a judicial. Notes: 10) At the bottom. and (b) there exist a special. If convinced that a prima facie case exists. potential extraditees may apply for bail. J. humanitarian or compelling circumstances. The grounds used by the highest court in the requesting state for the grant of bail therein may be considered. frustrate. delays and technicalities that may negate that purpose. The magistrate has discretion to require the petitioner to submit further documentation. Such conditions exist in Munoz’s case. Worse our country should not be converted into a dubious haven where fugitives and escapes can unreasonably delay. and while safeguarding basic individual rights. In extradition cases. the Executive Department of government has broad discretion in its duty and power of implementation. they have the burden of showing that (a) their is no flight risk and no danger to the community. However. The Hong Kong Magistrate’s Court issued a warrant for his arrest. CA declared the Order of Arrest null and void. under the principle of reciprocity as a special circumstance. which filed an application for the provisional arrest of MUÑOZ with RTC of Manila for and in behalf of the government of Hong Kong. Due process does not always call for a prior opportunity to be heard. mock. It cannot be denied that this is sufficient impetus for him to flee the country as soon as the opportunity to do so arises. the transmission by the Hong Kong DOJ of the request for respondent’s provisional arrest and the accompanying documents. incarceration. It is. particulars of his birth and address. was set to be heard by the Court of First Instance of Hong Kong on September 17.59 PUBLIC INTERNATIONAL LAW 2008 At the time the request for provisional arrest was made. as they are worded. There is naturally a great likelihood of flight by criminals who get an intimation of the pending request for their extradition. for each count of which. That the enumeration does not specify that these documents must be authenticated copies. but human to fear a lengthy. Respondent is about to leave the protective sanctuary of his mother state to face criminal charges in another jurisdiction. This may be gleaned from the fact that while Article 11(1) does not require the accompanying documents of a request for provisional arrest to be authenticated. it has also not possessed of sufficient resources to facilitate an escape from this jurisdiction. his mother finally expired at the Cardinal Santos Hospital in Madaluyong City last December 5. even our own Extradition Law (PD 1069) allows the transmission of a request for provisional arrest via telegraph. However. 1999. the Court stresses that it is not ruling that the private respondent has no right to due process at all throughout the length and breath of the extrajudicial proceedings. the provisions of PD 1069 and the RP-Hong Kong Extradition Agreement. nor when the warrant for his arrest was issued by the Hong Kong ICAC in August 1997. a summary of the facts of the case against him. by respondent’s own admission. and would motivate respondent to flee the Philippines before the request for extradition could be made. is not only time-consuming but also leakage-prone. The Hong Kong DOJ was concerned that the pending request for the extradition of the respondent would be disclosed to the latter during the said proceedings. by fax machine. a statement of the intention to request his provisional arrest and the reason therefor. a copy of the warrant of arrest against respondent. as follows: (1) an indication of the intention to request the surrender of the person sought. There is no requirement for the authentication of a request for provisional arrest and its accompanying documents. Article 9 of the same Extradition Agreement makes authentication a requisite for admission in evidence of any document accompanying a request for surrender or extradition. (2) the text of a warrant of arrest or judgement of conviction against that person. respondent’s pending application for the discharge of a restraint order over certain assets held in relation to the offenses with which he is being charged. the gravity of the imposable penalty upon an accused is a factor to consider in determining the likelihood that the accused will abscond if allowed provisional liberty. 1999. There is also the fact that respondent is charged with seven (7) counts of accepting an advantage as an agent and seven (7) counts of conspiracy to defraud. Therefore. and transmitting them through diplomatic channels. he may be punished with seven (7) and fourteen (14) years imprisonment. Undoubtedly. more than serves this purpose of expediency. Thus. serve the purpose sought to be achieved by treaty stipulations for provisional arrest. Procedural due process requires a determination of what process is due when it is due and the degree of what is due.24 The request for provisional arrest of respondent and its accompanying document are valid despite lack of authentication. it is an accepted practice for the requesting state to rush its request in the form of a telex or diplomatic cable. namely. is not a mere omission of law. In other words. Respondent also avers that his mother’s impending death makes it impossible for him to leave the country. and (4) such further information as would justify the issue of a warrant of arrest had the offense been committed or the person convicted within the jurisdiction of the requested party. if not a lifetime. To solve this problem. Stated otherwise. In tilting the balance in favor of the interests of the State. (3) a statement of penalty for that offense. after all. In the advent of modern technology. the telegraph or cable have been conveniently replaced by the facsimile machine. a prior determination should be made as to whether procedural protections are at all due and when they are due. The process of preparing a formal request for extradition and its accompanying documents. speedier initial steps in the form of treaty stipulations for provisional arrest were formulated. The pertinent provision of the RPHong Kong Extradition Agreement enumerates the documents that must accompany the request. which in turn depends on the extent to which an individual will be condemned to suffer Notes: . the practically of the use of which in conceded. if found guilty. is not a guarantee that he will no flee now that proceedings for his extradition are well on the way. respectively. Furthermore. authentication is required for the request for surrender or extradition but not for the request for provisional arrest. That respondent did not flee despite the investigation conducted by the Central bank and the NBI way back in 1994. It said that while our extradition law does not provide for the grant of bail to an extraditee. 153675). Hong Kong alleged that both Orders were issued by the judge with grave abuse of discretion amounting to lack or excess of jurisdiction as there is no provision in the Constitution granting bail to a potential extraditee. A potential extraditee may be granted bail on the basis of clear and convincing evidence that the person is not a flight risk and will abide with PUBLIC INTERNATIONAL LAW 2008 all the orders and processes of the extradition court. penalized by the common law of Hong Kong. GOVERNMENT OF HONG KONG SPECIAL ADMINISTRATIVE REGION V. 9 (1) (a) of the Prevention of Bribery Ordinance. 153675. where these rights are guaranteed. the Court also remanded to the Manila RTC. In sum. therefore.However. There is no denial of due process as long as fundamental fairness is assured a party. No Less compelling at that stage of the extradition proceedings is the need to be more deferential to the judgement of a co-equal branch of the governments. liberty.” in violation of sec. there is no provision prohibiting him or her from filing a motion for bail. 201 of Hong Kong. the trial court should order the cancellation of his bail bond and his immediate detention. April 19. which has been endowed by our Constitution with greater power over matters involving our foreign relations. and thereafter. As aforesaid. He also faces seven counts of the offense of conspiracy to defraud. Muñoz was charged before the Hong Kong Court with three counts of the offense of “accepting an advantage as agent. “The time-honored principle of pacta sunt servanda demands that the Philippines honor its obligations under the Extradition Treaty…. a right under the Constitution. 2002 Order denying the motion to vacate the said Order filed by the Government of Hong Kong Special Administrative Region. provided that a certain standard for the grant is satisfactorily met. AND MUÑOZ. to which the Philippines is a party. it does not necessarily mean that in keeping with its treaty obligations. the Philippines should diminish a potential extraditee’s rights to life. We should not. the Court saw the need to reexamine its ruling in Government of United States of America v. not only by our Constitution. 2007 Bail Can Be Granted to Potential Extraditee on Basis of Clear and Convincing Evidence In its petition. More so. represented by the Philippine Department of Justice. Hong Kong sought the nullification of the Manila RTC’s December 20. Jr. Judge Purganan which limited the exercise of the right to bail to criminal proceedings. P. Thus held the Supreme Court in dismissing the petition of the Government of Hong Kong Special Administrative Region to nullify two orders by a Manila Regional Trial Court (RTC) allowing a potential extraditee to post bail. Citing the various international treaties giving recognition and protection to human rights. The time for the extraditee to know the basis of the request for his extradition is merely moved to the filing in court of the formal petition for extradition. Branch 8 to determine whether Juan Antonio Muñoz is entitled to bail on the basis of “clear and convincing evidence.” If Muñoz is not entitled to such. 2001 Order allowing Muñoz to post bail. this balance of interests is not a static but a moving balance which can be adjusted as the extradition process moves from the administrative stage to the execution stage depending on factors that will come into play. The extradites right to know is momentarily withheld during the evaluation stage of the extradition process to accommodate the more compelling interest of the State to prevent escape of potential extradites which can be precipitated by premature which can be precipitated by premature information of the basis of the request for his extradition.’ We have explained why an extraditee has not right to notice and hearing during the evaluation stage of the extradition process. deprive an extraditee of his right to apply for bail. Judge Olalia. the Executive. JR. is “under obligation to make available to every person under detention such remedies which safeguard Notes: . JUDGE OLALIA. and Muñoz (GR No. and April 10. In a unanimous decision penned by Justice Angelina Sandoval-Gutierrez in Government of Hong Kong v. conduct the extradition proceedings with dispatch. RP. we rule that the temporary hold on private respondent’s privilege of notice and hearing is a soft retrains on his right to due process which will not deprive him of fundamental fairness should he decide to resist the request for his extradition to the United States. Cap. being a signatory to the 1996 UN General Assembly which adopted the International Covenant on Civil and Political Rights. GR No. and due process.” the Court said. but also by international conventions. Needless to state.D. 1069 xxx affords an extraditee sufficient opportunity to meet the evidence against him once the petition is filed in court.60 grievous loss. outside the country of habitual residence. it is just a privilege granted by a state to allow an alien escaping from the persecution of his country for political reasons to remain and to grant him asylum. a refugee a stateless person. to the frontiers of territories where his life or freedom would be threatened. both are administrative proceeding where the innocence or guilt of the person detained is not in issue. or be called flotsam and res nullius. who. but one that is merely administrative in character. The right of asylum is not a right possessed by an alien to demand that a state protect him and grant him asylum. (Bar) A: The right of asylum is the competence of every state inferred from its territorial supremacy to allow a prosecuted alien to enter and to remain on its territory under its protection and thereby grant asylum to him. if he has no nationality. Asylum and Refugees A refugee is any person who is outside the country of his nationality or the country of his former habitual residence because he has or had well founded fear of persecution by reason of his race. Its significance is municipal and not international. or. Rempillo (SC website) PUBLIC INTERNATIONAL LAW 2008 unable or. by international laws. considering that the Universal Declaration of Human Rights applies to deportation cases. being persecuted in his home State. or for over two years without having been convicted of any crime. “If bail can be granted in deportation cases. Citizenship Nationality is the membership in a political community with all its concomitant rights and obligations. Q: Explain the right of asylum in international law. 3 Essential Elements to be considered a Refugee: 1) The person is outside the country of his nationality. The RP and Hong Kong signed in 1995 an extradition treaty which became effective in 1997. Notes: The Right of Asylum Every foreign State can be at least a provisional asylum for any individual. After all. Only a person who is granted asylum by another state can apply for refugee status.” said the Court. nationality or political opinion and is Non-Refoulment Principle Non-refoulment non-contracting state expel or return (refouler) a refugee. 1999 to December 20. Likewise. religion. At present. which he is also obliged to follow. obliged to refuse admission into its territory to such a fugitive or in case he has been admitted. Citizenship has a more exclusive meaning in that it applies only to certain members of the state accorded more privileges than the rest of the people who owe it allegiance. It is the tie that binds an individual to his state. 2) The person lacks national protection. It added that “extradition is not a trial to determine the guilt or innocence of potential extraditee. or in the case of stateless persons. in any manner whatsoever. 1 Is a refugee is included in the term stateless person or is it the other way around? Suggested Answer: Analyze the elements before one could be considered a refugee. we see no justification why it should not also be allowed in extradition cases. he can be compared to a vessel on the open sea not sailing under the flag of any state. Q: Sandoval’s Open Question No. to expel him or deliver him up to the prosecuting state. (Article 33 of the Convention Relating to the Status of Refugees) The Principle of the non-refoulment was declared to be a generally accepted principle by the Convention relating to the status of stateless persons. Nationality v. Nationality is Important in Int’l Law It is important because an individual can ordinarily participate in international relations only through the instrumentality of the state to which he belongs. because of such fear. for it is not punishment for a crime. 2001. The second element makes. 3) The person fears persecution in his own country. even though such punishment may follow extradition. there is no reason why it cannot be invoked in extradition cases. no state is. is unwilling to avail himself of the protection of the government of the country of his nationality. to return to the country of his former habitual residence. It further said that even if a potential extradite is a criminal.61 their fundamental right to liberty. In the absence of any international treaty stipulating the contrary. The Court noted that Munoz had been detained from September 23. an extradition proceeding is not by its nature criminal. from which he can claim protection from the laws.” the Court said. By Jay B. goes to another State. as when his government asserts a claim on . Nor is it a full-blown civil action. thus the refugee treaties imply the principle of asylum. Because a refugee approximates a stateless person. for the state. the defendant in this case can invoke his rights against the Holy See not under the Municipal Law but under International Law through his government. b) Access to the courts. Under the principle of effective nationality. Karpov finally retained his title of a close 6 to 5 win. DOCTRINE OF EFFECTIVE NATIONALITY Within a third state. If this happens. such loss must be conditional upon possession or acquisition of another nationality. The Convention also provides for the issuance of identity papers and travel documents to the stateless persons. which he attributes as the main case of his defeat. a stateless resident of Switzerland. After 32 grueling games were played in Baguio city. ii. which will espouse his cause of action in his behalf. c) Rationing of products in short supply. protection or recourse under the Law of Nations? Explain. Under the Convention in Relation to the Status of Stateless Persons. No state can intervene or complain in behalf of the stateless person for an international delinquency committed by another state in inflicting injury upon him. was the challenger to the world chess title held by Russian Anatoly Karpov. the third state shall recognized conclusively in its territory either the nationality of the country in which he is habitually and principally present or the nationality of the country with which he appears to be in fact most closely connected. Notes: The Law on International Obligations Sources of International Obligations The Law of Treaties Treaty Defined 2 Kinds of Treaties . This remedy would not be available to a stateless person who will have no state with international personality to intercede for him under the laws of nations. d) Elementary education. Switzerland even if she so desires.62 his behalf for injuries suffered by him in foreign jurisdiction. a person having more than one nationality shall be treated as if he had only one. Nationality is the basis of the right of state to espouse such claim. Rosario. (1995 Bar) A: No. after renouncing his original nationality in order to be naturalized in another state. Statelessness Statelessness is the condition or status of an individual who is born without any nationality or who loses his nationality without retaining or acquiring another. He cannot be expelled by the state if he is lawfully in its territory except on grounds of national security or public order. if any. An example of the first case would be that of an individual born in a state where only the jus sanguinis is recognized to parents whose state observes only jus soli. is subsequently denaturalized and thereafter denied repatriation by his former country. Korchnoi protested no-payment of his prize money and alleged unfair treatment he received from the tournament organizers in the Philippines particularly in the 32nd crucial game. In this case. iii. that is. a) Freedom of religion. f) Labor legislation. Q: Is a stateless person entirely without right. in the case of Holy See vs. the Contracting States agree to accord nationality to persons born in their territory who would otherwise be stateless. the Contracting States agree to accord the stateless persons within their territories treatment at least as favorable as that accorded their nationals with respect to. He cannot avail himself of the protection and benefits of citizenship like securing for himself a passport or visa and personal documents. has International Law taken to prevent statelessness? (1995 Bar) A: In the Convention on the Conflict of Nationality Laws of 1930. as a consequence of marriage or termination of marriage. May he press for his right to the prize money against the Philippine government through the Swiss government? (1978 Bar) A: No. Q: What measures. and g) Social Security They also agree to accord them treatment not less favorable than that accorded to aliens generally in the same circumstances. his concern ceases to be a private one but becomes one for the public. Example. cannot espouse a diplomatic claim against the Philippines in behalf of Victor Korchnoi. PUBLIC INTERNATIONAL LAW 2008 Q: Victor Korchnoi. e) Public relief and assistance. The convention on the Reduction of Statelessness of 1961 provides that if the law of the Contracting States results in the loss of nationality. Korchnoi is not a Swiss national but a stateless person. Q: What are the consequences of statelessness? (1995 Bar) A: These are: i. Q: Who are stateless persons under International Law? (1995 Bar) A: They are those who are not considered as national by any state under the operation of its laws. The second case may be illustrated by an individual who. 2000. as defined by the Vienna Convention on the Law of Treaties. have pointed out that the names or titles of international agreements included under the general term treaty have little or no significance. 138570.R. agreement. unreasonable delay 5. Q: What is a "protocol de cloture"? Will it require concurrence by the Senate? Held: A final act. Executive Secretary ☀ The use of particular terminology has no legal significance in international law. No.” There are many other terms used for a treaty or international agreement. conventions. recommendations and other acts agreed upon and signed by the plenipotentiaries attending the conference. G. En Banc [Buena]) Protocol de Clôture A final act. Angara. It is not the treaty itself. All writers. 272 SCRA 18. treaties concluded between States Customary international law – e. whether embodied in a single instrument or in two or more related instruments. It is rather a summary of the proceedings of a protracted conference which may have taken place over several years. It will not require the concurrence of the Senate.g. sometimes called protocol de cloture. nationality of the claim 2. 1997 [Panganiban]) Treaty as main instrument “The treaty is the main instrument with which the society of States is equipped for the purpose of carrying out its multifarious transactions. Held: A treaty. statute. from Hugo Grotius onward. protocol. compromis d' arbitrage. It is rather a summary of the proceedings of a protracted conference which may have taken place over several years. The documents contained therein are deemed adopted without need for ratification. sometimes called protocol de cloture is an instrument which records the winding up of the proceedings of a diplomatic conference and usually includes a reproduction of the texts of treaties. waiver 4. recommendations and other acts agreed upon and signed by the plenipotentiaries attending the conference. exchange of notes. and whatever its particular designation. exhaustion of local remedies 3. the doctrine of rebus sic stantibus A. conventions. improper behavior by the injured alien Methods of Pressing Claims Nature and Measure of Damages ¯°º°¯ Sources: PUBLIC INTERNATIONAL LAW 2008 Ronaldo Zamora. It is not the treaty itself. some of which are: act. convention.” LORD McNAIR Synonymous words a) Convention b) Pact c) Protocol d) Agreement e) Arrangement f) Accord g) Final Act h) General Act i) Exchange of Notes Notes: 1) 2) International agreements – e. declaration. Certain terms are useful.” (BAYAN [Bagong Alyansang Makabayan] v. May 2.63 Parties Requisites for Validity Peremptory Norm Process of Treaty Making Principle of Alternat Subject Matters of Treaties Subject Matters of Executive Agreements Most Favored Nation Clause Pacta Sunt Servanda Rebus Sic Stantibus Effect of Territorial Changes Interpretation of Treaties Termination of Treaties State Responsibility for Injury to Aliens Doctrine of State Responsibility Conditions for Enforcement of Claim 1. Oct. charter and modus vivendi. THE LAW OF TREATIES Treaty Defined Q: What is a Treaty? Discuss. Matters usually dealt with by treaties: a) lease of naval bases b) the sale or cession of territory c) the regulation of conduct of hostilities d) the termination of war e) the formation of alliances f) the regulation of commercial relations g) the settling of claims . is an instrument which records the winding up of the proceedings of a diplomatic conference and usually includes a reproduction of the texts of treaties. concordat. is “an international instrument concluded between States in written form and governed by international law. (Tanada v. 10. or to the meanings which may be given to them in the internal law of the State. but they furnish little more than mere description Article 2(2) of the Vienna Convention provides that “the provisions of paragraph 1 regarding the use of terms in the present Convention are without prejudice to the use of those terms. pact.g. Exceptions: a) If the immorality. Legality of Object Rule: Immorality. or b) When it is limited by some other international arrangements respecting some matters. b) If it does not contravene or depart from an absolute or imperative rule or prohibition of international law. the erring State must as soon as possible or within the time given in the treaty. Thus. e. Agreements between State and individuals or entities other than States DO NOT come within the category of treaties. jus cogens Q: Explain. withdraw or correct its consent. using example.g. PEREMPTORY NORM A norm generally accepted by the international community of States as a whole as a norm from which no derogation is permitted and which can be modified only by a subsequent norm of general international law having the same character. e. Prescription – filing of protest after the lapse of allowable period within which the same may be entertained. it is the Head of State who possesses the treatymaking power to be concurred in by the legislative branch. intimidation. Consent How Given a) through a signature b) exchange of instruments c) ratification d) acceptance e) approval or accession.g. e. coercion. the treaty would be VOIDABLE. c) When it has received benefits or has exercised its rights under the subject treaty without expressly reserving its non-liability or without interposing other valid reasons for receiving or exercising it. e. the State is deemed to have ratified its consent. jus dispositivum. Exceptions: . Notes: Remedy: Where the consent of a party has been given in error or induced through fraud on the part of the other party. h) a) PUBLIC INTERNATIONAL LAW 2008 b) c) Ratification – waiving the right to withdraw from the treaty and declaring its consent thereon as valid. or f) by other means so agreed. illegality or impossibility of purpose or obligations makes a treaty null and void. the 3) Reality of Consent Rule: The plenipotentiaries of States or the State itself must possess the capacity to consent which consent is given in a manner that is voluntary and free from fear. illegality or impossibility does not run counter to a universally recognized peremptory norm of international law but only against a remote and minor norm.g. jus cogens in international law.g. force.exercising its rights and respecting the obligations in the treaty notwithstanding knowledge of facts that vitiate its consent and exercises them without protest. Exceptions: a) When it limits itself. or corruption. As a rule. PARTIES Rule: Only States may enter into treaties or international agreements. Exceptions: a) When it is in estoppel b) When it has performed acts validating or curing the defects in competence. Thus. (1991 Bar) A: Jus cogens is a peremptory norm of general international law accepted and recognized by the international community as a whole. Exceptions: States may enter into treaties or international agreements with: a) International Organizations b) Belligerent States 4 Essentials of Validity 1) Capacity of parties Rule: Every State possesses capacity to conclude treaties as an attribute of its sovereignty. Estoppel . 4) 2) Competence of particular organs concluding the treaty Rule: The municipal law of the State concerned shall determine what organ may conclude a treaty.64 the establishment of international organizations 2 Kinds of Treaties a) traites-lois – law making treaties b) traits-contrats – contract treaties 1969 Convention on the Law of Treaties Adopted by the Conference of the Law of Treaties (Vienna Convention). 1960. a treaty by which a State agrees with another to appropriate a portion of the high seas. Entered into force on January 27. Also. It is the act of ratification that is required to make a treaty binding. ☀ A treaty may provide that it shall not be valid even ratified but shall be valid only after the exchange or deposit of ratification has transpired. have been allowed by its terms to sign it later by a process known as accession. The consent of the State to be bound by a treaty is expressed by ratification when: (a) the treaty provides for such ratification. Principle of Alternat According to this principle. Art. raises the question of nullity. INCONSISTENCY Inconsistency raises the problem of conflict of obligations. or was expressed during the negotiation. Exceptions: a) the treaty provides that signature shall have such effect. orally agreed treaties are a rarity. including not only the original signatories but also other states. By ratifying a treaty signed in its behalf. through which the formal acceptance of the treaty is proclaimed. although they may not have participated in the negotiation of the agreement.65 prohibition against the use of force in dealing with States. However. Notes: Ratification The act by which the provisions of a treaty are formally confirmed and approved by a State. ☀ There is no moral duty on the part of the States to ratify a treaty notwithstanding that its plenipotentiaries have signed the same. or the intention of the State to give that effect to the signature appears from the full powers of its representative or was expressed during the negotiations. accedes to it. on the other hand. Held: Ratification is generally held to be an executive act.g. (c) the representative of the State has signed the treaty subject to ratification. e. the order of the naming of the parties. the practice is usually to arrange the names alphabetically in English or in French. Oral treaties are NOT prohibited. Significance of Signature Rule: The act of signature has little legal significance except as a means of authenticating the text of the treaty. however. 103 of the UN Charter provides that in the event of conflict between the obligations of the Members under the UN Charter and their obligations under any international agreement. Effect of Form on Validity There is no rule that treaties should be in written form. undertaken by the head of state or of the government. whether embodied in a singe instrument or in two or more related instruments and whatever its particular designation (is). b) c) PUBLIC INTERNATIONAL LAW 2008 it is otherwise established that the negotiating States were agreed that signatures should have that effect. ★ However.R. 10. ☀ State may ratify a treaty only when it is a signatory to it. with respect to treaties with many parties. This step. 2000. treaties are prepared and adopted by means of international diplomatic conferences. their obligations under the UN Charter shall prevail. Non-parties are usually not bound under the maxim of pacta tertiis nec noceat nec prosunt. or (d) the intention of the State to sign the treaty subject to ratification appears from the full powers of its representative. 138570. should not be taken lightly. defines a “treaty” as “an international agreement concluded between States in written form and governed by international law.” PROCESS OF TREATY-MAKING Usual Steps Taken 1) Negotiation of parties 2) Signature of the agreed text 3) Ratification or accession made by the treaty-making organs of States concerned 4) Exchange or deposit of the instruments of ratification or accession. G. as the case may be. (b) it is otherwise established that the negotiating States agreed that ratification should be required. INCOMPATIBILITY v. a State expresses its willingness to be bound by the provisions of such treaty. who has NOT SIGNED a treaty. Q: What is ratification? Discuss its function in the treaty-making process. a large number of multilateral conventions have been adopted by international organizations such as the General Assemble of the UN. . (BAYAN [Bagong Alyansang Makabayan] v. Binding Effects of a Treaty As a rule. A State may provide in its domestic legislation the process of ratification of a treaty. No. Executive Secretary Ronaldo Zamora. however. a treaty is binding only on the contracting parties. Note: The Vienna Convention. At present. Incompatibility. which. Oct. En Banc [Buena]) Accession or Adherence When a State. and of the signatures of the plenipotentiaries is varied so that each party is named and its plenipotentiary signs first in the coy of the instrument to be kept by it. According to Commissioner of Customs v. 3 S 351 [1961]. Constitution All exiting treaties or international agreements which have not been ratified shall not be renewed or extended without the concurrence of at least 2/3 of ALL the Members of the Senate. 2000. Q: Discuss the binding effect of treaties and executive agreements in international law. A.XVIII. which.R. Parties to apparently unrelated treaties may also be linked by the mostfavored nation clause. we have recognized the binding effect of executive agreements even without the concurrence of the Senate or Congress. Constitution The President may contract or guarantee foreign loans on behalf of the RP with the prior concurrence of the Monetary Board. foreign military bases. The treaty itself may expressly extend its benefits to non-signatory states. §20. (BAYAN [Bagong Alyansang Makabayan] v. there is no difference between treaties and executive agreements in their binding effect upon states concerned. ratified by a majority of the votes cast by the people in a national referendum held for that purpose. En Banc [Buena]) Q: An Executive Agreement was executed between the Philippines and a neighboring State. However. G. it DOES NOT INCLUDE the temporary presence in the Philippines of foreign troops for the purpose of a combined military exercise. submit to the Congress a complete report of its decisions on applications for loans to be contracted or guaranteed by the Government or governmentowned and controlled corporations which would have the effect of increasing the foreign debt. A: 1. §21. 356-357 [1961]). 138570. G. Constitution After the expiration in 1991 of the Agreement between the RP and the USA concerning the Military Bases. " (BAYAN [Bagong Alyansang Makabayan] v. A. 2. §4. 2000. En Banc [Buena]) Q: Does the Philippines recognize the binding effect of executive agreements even without the concurrence of the Senate or Congress? Held: In our jurisdiction. or facilities shall not be allowed in the Philippines except under a treaty duly concurred in by the Senate and. In Commissioner of Customs v. as such is enforceable on all civilized states because of their membership in the family of nations.XVIII. the UN shall ensure that non-member States act in accordance with the principles of the Charter so far as may be necessary for the maintenance of international peace and security. NOTE: This section prohibits. Executive Secretary Ronaldo Zamora. trademark and copyright protection. patent rights. 10. in the absence of a treaty. International law continues to make no distinction between treaties and executive agreements: they are equally binding obligations upon nations. 138570. we had occasion to pronounce: “x x x the right of the Executive to enter into binding agreements without the necessity of subsequent Congressional approval has been confirmed by long usage. 4. when the Congress so requires. 10. Oct. 1987 Phil. §25. Under Article 103.66 PUBLIC INTERNATIONAL LAW 2008 Q: Enumerate instances when a third State who is non-signatory may be bound by a treaty. Oct. When a treaty is a mere formal expression of customary international law. the Executive Agreement is binding. the stationing of troops and facilities of foreign countries in the Philippines. 1987 Phil. declared. most-favored-nation rights. No. the holding of combined military exercise is connected with defense. Eastern Sea Trading (3 SCRA 351. from the standpoint of Philippine law. obligations of member-states shall prevail in case of conflict with any other international agreement including those concluded with non-members. Is an Executive Agreement binding from the standpoints a) of Philippine law and b) of international law? Explain. 1987 Phil. 1987 Phil. that the agreement was both unwise and against the best interest of the country. A. and containing other matters as may be provided by law. 3. within 30 days from the end of every quarter of the calendar year. the President can enter into an Notes: . as long as the functionaries have remained within their powers. Besides. From the earliest days of our history we have entered into executive agreements covering such subjects as commercial and consular relations.VII. No. A. The validity of these has never been seriously questioned by our courts. troops. (2003 Bar) A: a) YES. The MB shall. Under Article 2 of its charter.R. by a unanimous vote. Eastern Sea Trading. Constitution No treaty or international agreement shall be valid and effective unless concurred in by at least 2/3 of ALL the Members of the Senate. Held: [I]n international law. postal and navigation arrangements and the settlement of claims. and subject to such limitations as may be provided by law. which is a sovereign function. The Senate of the Philippines took it upon itself to procure a certified true copy of the Executive Agreement and after deliberating on it. and recognized as a treaty by the other contracting State.VII. Executive Secretary Ronaldo Zamora. Under Section 20 Article VII of the Constitution. What would you advice them to do? Give your reasons. only the prior concurrence of the Monetary Board is required for the President to contract foreign loans on behalf of the Republic of the Philippines. to store nuclear weapons at Subic and at Clark Field. asked that the agreement be submitted to it for ratification. paragraph 2 states that judicial power includes the duty of courts of justice to “determine whether or not there has been a grave abuse of discretion amounting to lack or excess of jurisdiction on the part of any branch or instrumentality of the government. it is also binding from the standpoint of international law. The Secretary of Public Works and Highways did not comply with the request of the Senate. in international law executive agreements are equally binding as treaties uon the States who are parties to them. Section 21. the President is not bound to submit the agreement to the Senate for ratification. and believing that it would be good for the country. The Senate. (1994 Bar) a) Under the Constitution. therefore. Q: The President authorized the Secretary of Public Works and Highways to negotiate and sign a loan agreement with the German Government for the construction of a dam. it is not likely to be submitted to the Senate for ratification as required in Article VII. As held in Bayan V. However. “treaties and executive agreement are alike in that both constitute equally binding obligations upon the Notes: . no justiciable controversy can be framed to justify judicial review. b) An undertaking on the part of the American government to implement immediately the minMarshall plan for the country involving ten billion US dollars in aids and concessional loans. by a resolution. a treaty or international agreement must be concurred in by at least 2/3 of all members of the senate. On the other hand. The Nuclear Free Philippines Coalition comes to you for advice on how they could legally prevent the same agreement entered into by the President with the US government from going into effect. in consideration of: a) A yearly rental of one billion US dollars. statutes. whether it is indicated as a Treaty. Zamora. From the standpoint of international law. when hostile military forces threaten the sea-lanes from the Persian Gulf to the Pacific. what is the role of the Senate in the conduct of foreign affairs? b) Is the president bound to submit the agreement to the Senate for ratification? A: a) The Senate plays a role in the conduct of foreign affairs. the distinction is purely municipal and has no international significance. Still it is considered a treaty and governed by the international law of treaties. and in case of vital military need.67 Executive Agreement WITHOUT the necessity of concurrence by the Senate. payable to Philippine government in advance. at this stage. I would therefore advice the Nuclear Free Philippines Coalition to resort to the media to launch a campaign against Agreement Subject Matter of Treaties 1) Political Issues 2) Changes in National Policies 3) Involve International Agreements of a Permanent Character Subject Matter of EAs 1) Have transitory effectivity 2) Adjustment of details carrying out wellestablished national policies and traditions 3) Arrangements of temporary nature 4) Implementation of treaties. because of the requirement in Section 21 Article VII of the Constitution that to be valid and effective. b) No. the President agreed to allow American nuclear vessels to stay for short visits at Subic. Q: In accordance with the opinion of the Secretary of Justice. b) YES. and c) An undertaking to help persuade American banks to condone interests and other charges on the country’s outstanding loans. whatever may be the designation of a written agreement between States. albeit involving the Executive Branch of the government during the martial law period. PUBLIC INTERNATIONAL LAW 2008 In return. A vital military need comes. It was inserted in the Constitution to prevent courts from making use of the doctrine to avoid what otherwise are justiciable controversies. While Article VIII. (Bar) A: If the agreement is not in the form of treaty. Nor a judicial review is feasible at this stage because there is no justiciable controversy. the President enters into an agreement with the Americans for an extension for another five (5) years of their stay at their military bases in the Philippines. well established policies. It may not. Convention or Executive Agreement is not legally significant. under the agreement. 342 S 449 [2000]. Additionally. under Article 2(1)(a) of the Vienna Convention on the Law of Treaties. be opposed in that branch of the government.” it is clear that this provision does not do away with the political question doctrine. Section 1. Q: How does a treaty differ from executive agreement? A: An executive agreement is not a treaty in so far as its ratification may not be required under the Constitution. However. however phrased or named. 75. Reservations A unilateral statement. it is only a matter of policy and the same is governed by their respective Municipal Law. In international law. Objected Reservations Parties to the treaty may object to the reservations of a State entering the treaty. however. UN Charter 1. In the absence of such stipulation. The most-favored-nation clause may be defined. as a pledge by a contracting party to a treaty to grant to the other party treatment not less favorable than that which has been or may be granted to the “most favored” among other countries. approving. The Senate cannot delegate its power to concur to treaties ratified by the President. 1939) An executive agreement is NOT a treaty. Notes: Entry into Force Means the date of effectivity of a treaty as provided in the stipulations of the parties. Q: Is VFA a treaty or a mere executive agreement? A: In the case of Bayan vs. it is deemed in force as soon as the consent of ALL the parties are established. the President alone can negotiate treaties and Congress is powerless to intrude into this. Q: What is the implication if only the senate of the Philippines concur but not the senate of USA? A: None. consent and concurrence to treaties entered into by the President.68 nations. MOST-FAVORED-NATION CLAUSE Q: What is the “most-favored-nation” clause? What is its purpose? A: 1. VFA was considered a treaty because the Senate concurred in via 2/3 votes of all its members. INCORPORATION CLAUSE. ★ The treaty.1 of this Article may invoke that treaty or agreement before any organ of the UN. . there is NO absolute rule that treaties are self-executing within the sphere of municipal law. No party to any such treaty or international agreement which has not been registered in accordance with the provisions of para. Although the Senate has the power to concur in treaties. its advice. 2. 39 Columbia Law Review. in general. if the matter involves a treaty or an executive agreement. whereby it purports to exclude or modify the legal effect of certain provisions of the treaty in their application to that State. 1234 was passed creating a joint legislative-executive commission to give on behalf of the Senate. Zamora. p. Some municipal laws require further steps such as publication and promulgation before it can produce legal effect. Is the bill constitutional? (1996 Bar) A: NO. The bill contains the guidelines to be followed by the commission in the discharge of its functions. particularly in entering into treaties and international agreements? (1996 Bar) A: NO. but not all. the HR may pass a resolution expressing its views on the matter. when signing. Q: Senate Bill No. concurrence by two-thirds vote (2/3) of all the members of the Senate is not necessary for it to become binding and effective. remains valid although not registered and not published in the UN. PUBLIC INTERNATIONAL LAW 2008 Form and Time of Reservation Written statement or declaration recorded at the time of signing or ratifying or acceding to the treaty. ratifying. REGISTRATION & PUBLICATION Article 102. it is merely an executive agreement. The clause has been commonly included in treaties of commercial nature. objects to its reservations and such reservations are not contrary to the object and purpose of said convention. However. the bill is not constitutional. Q: Can the House of Representatives take active part in the conduct of foreign relations. it selfexecutes from the time of its entry into force.” (FB Sayre. As held in US v. When Reservation cannot be made a) If the treaty itself provides that NO reservation shall be admissible. or b) the treaty allows only specified reservations which do not include the reservation in question. made by a State. Q: Are Treaties Self-Executing? A: Qualified answer. in the Philippines. or c) the reservation is incompatible with the object and purpose of the treaty. A 1951 Advisory Opinion of the ICJ held that a reserving State may be a party to a treaty notwithstanding that one or more parties to the convention. Every treaty and every international agreement entered into by any Member of the UN after the present Charter comes into force shall as soon as possible be registered with the Secretariat and published by it. or acceding to a treaty. Curtiss Wright Export Corporation 299 US 304. But in the point of view of the US Government. treaties are part of the law of the land. ★ Nevertheless. accepting. it is the President alone who can act as representative of the nation in the conduct of foreign affairs. As such. 141-142) 2. the concessional tax rate of 10 percent provided for in the RP-Germany Tax Treaty should apply only if the taxes imposed upon royalties in the RP-US Tax Treaty and in the RP-Germany Tax Treaty are paid PUBLIC INTERNATIONAL LAW 2008 under similar circumstances. which is the counterpart provision with respect to relief for double taxation. 309 SCRA 87. a non-resident foreign corporation based in the USA. Q: What is the essence of the principle behind the "most-favored-nation" clause as applied to tax treaties? Held: The essence of the principle is to allow the taxpayer in one state to avail of more liberal provisions granted in another tax treaty to which the country of residence of such taxpayer is also a party provided that the subject matter of taxation x x x is the same as that in the tax treaty under which the taxpayer is liable. June 25.C. b) Conditional – advantages are specified and limited not universal.S. Johnson and Son.. It held: Given the purpose underlying tax treaties and the rationale for the most favored nation clause. (Salonga & Yap. Inc. namely. with the BIR for refund of overpaid withholding tax on royalties pursuant to the most-favored-nation clause of the RP-US Tax Treaty in relation to the RP-West Germany Tax Treaty. Johnson and Son. The similarity in the circumstances of payment of taxes is a condition for the enjoyment of most favored nation treatment precisely to underscore the need for equality of treatment. One of the oldest and most fundamental rules of international law. According to the clause in its unconditional form. X x x X x x The entitlement of the 10% rate by U. The most favored nation clause is intended to establish the principle of equality of international treatment by providing that the citizens or subjects of the contracting nations may enjoy the privileges accorded by either party to those of the most favored nation. firms despite the absence of matching credit (20% for royalties) would derogate from the design behind the most favored nation clause to grant equality of international treatment since the tax burden laid upon the income of the investor is not the same in the two countries. Inc. 5th Edition. 1999. Inc.69 There are generally two types of most-favorednation clause. Johnson and Son. JOHNSON & SON. The purpose of a most favored nation clause is to grant to the contracting party treatment not less favorable than that which has been or may be granted to the "most favored" among other countries. CIR V. S. Article 24 of the RP-Germany Tax Treaty x x x expressly allows crediting against German income and corporation tax of 20% of the gross amount of royalties paid under the law of the Philippines.. 1992.C. In Commissioner of Internal Revenue v. Notes: . It usually applies to commercial transactions such as international trade and investments. Johnson and Son. [Gonzaga-Reyes]) Q: Explain the meaning of the concept of “most favored nation” treatment? (1997 Bar) A: The most favored nation treatment is that granted by one country to another not less favorable than that which has been or may be granted to the most favored among other countries.C. Inc. 107-108. 1999. June 25.. 309 SCRA 87.. On the other hand. INC. 3rd Div.C. pp. the SC did not grant the claim filed by S. Article 23 of the RP-US Tax Treaty. S. 2 Types a) Unconditional –. does not provide for similar crediting of 20% of the gross amount of royalties paid. This would mean that private respondent (S. The most favored nation clause is intended to establish the principle of equality of international treatment by providing that the citizens or subjects of the contracting nations may enjoy the privileges accorded by either party to those of the most favored nation (Commissioner of Internal Revenue v.) must prove that the RP-US Tax Treaty grants similar tax reliefs to residents of the United States in respect of the taxes imposable upon royalties earned from sources within the Philippines as those allowed to their German counterparts under the RP-Germany Tax Treaty. (1999) The purpose of a most favored nation clause is to grant to the contracting party treatment not less favorable than that which has been or may be granted to the "most favored" among other countries. conditional and unconditional. The RP-US and the RP-West Germany Tax Treaties do not contain similar provisions on tax crediting. PACTA SUNT SERVANDA (PSS) (AGREEMENT MUST BE KEPT) Means that treaties must be performed in good faith. Public International Law. cited in Freidmann. Pugh. 1997 [Panganiban]) Influences to ensure observance to PSS a) national self-interest b) a sense of duty c) respect for promises solemnly given d) desire to avoid the obloquy attached to breach of contracts ▪ Breach involves the obligation to make reparations. under this doctrine.I. 29 A. REBUS SIC STANTIBUS (RSS) (THINGS REMAINING AS THEY ARE) This doctrine involves the legal effect of change in conditions underlying the purposes of a treaty. ROBERTSON (1986) PUBLIC INTERNATIONAL LAW 2008 "The obligation to fulfill in good faith a treaty engagement requires that the stipulations be observed in their spirit as well as according to their letter and that what has been promised be performed without evasion. ANGARA (1997) One of the oldest and most fundamental rules in international law is pacta sunt servanda international agreements must be performed in good faith. LANTION (2000) The rule of pacta sunt servanda.. Held: One of the oldest and most fundamental rules in international law is pacta sunt servanda – international agreements must be performed in good faith.. at war with the principle of international morality. one of the oldest and most fundamental maxims of international law. AGUSTIN V. The concept of pacta sunt servanda stands in the way of such an attitude.J.L. Lisstzyn." Under the doctrine of incorporation. jurists. The Meaning and Range of the Norm (Pacta Sunt Servanda. rules of international law form part of the law of the land and no further legislative action is needed to make such rules applicable in the domestic sphere (citing Salonga & Yap. with a statement of the reasons why compliance with the treaty is no longer required. International Law (1969) 329). and adheres to the policy of peace. 180 (1945). the ruling becomes an anacoluthon and a persiflage. OF JUSTICE V." (citing Kunz. There is. 1992 ed. Does it operate automatically to render a treaty inoperative? Held: According to Jessup. p. usually made by the head of state. Public International Law. honestly and to the best of the ability of the party which made the promise. There is a necessity for a formal act of rejection. TAÑADA V. and tribunals are varied in the application of this doctrine. The observance of our country's legal duties under a treaty is also compelled by Section 2. May 2. no necessity to state this rule of reparation in the treaty itself because they are indispensable complement of failure to comply to one’s obligations. the doctrine constitutes an attempt to formulate a legal principle which would justify non-performance of a treaty obligation if the conditions with relation to which the parties contracted have changed so materially and so unexpectedly as to create a situation in which the exaction of performance would be unreasonable. Also. A state which has contracted valid international obligations is bound to make in its legislations such modifications as may be necessary to ensure the fulfillment of the obligations undertaken. however. cooperation and amity with all nations. "A treaty engagement is not a mere moral obligation but creates a legally binding obligation on the parties x x x. (Santos III v. “A treaty engagement is not a mere moral obligation but creates a legally binding obligation on the parties x x x. CIR V. A majority. Angara. justice. Simply stated.70 Q: Explain the “pacta sunt servanda” rule.e. Somehow. hold that “the obligation of a treaty terminates when a change occurs in circumstances which existed at the time of the conclusion of the treaty and whose continuance formed.” The change must be vital or fundamental." SEC. 12). Authors. A state which has contracted valid international obligations is bound to make in its legislations such modifications as may be necessary to ensure the fulfillment of the obligations undertaken.” (Tanada v. EDU (1979) t is not for this country to repudiate a commitment to which it had pledged its word. Explain the "rebus sic stantibus" rule (i. adopts the generally accepted principles of international law as part of the law of the land. a treaty terminates if the performance of obligations thereof will injure fundamental rights or interests of any one of the parties. the disappearance of the foundation upon which it rests. things remaining as they are). Notes: . moreover. Article II of the Constitution which provides that "[t]he Philippines renounces war as an instrument of national policy. The key element of this doctrine is the vital change in the condition of the contracting parties that they could not have foreseen at the time the treaty was concluded. freedom. which is. a condition of the continuing validity of the treaty. equality. however. 272 SCRA 18. according to the intention or will of the parties. The doctrine of rebus sic stantibus does not operate automatically to render the treaty inoperative. or subterfuge. requires the parties to a treaty to keep their agreement therein in good faith. is NOT a function of the courts but of the other branches of government. The parties to the contract must be presumed to have assumed the risks of unfavorable developments. b) a new State can be a party to an existing treaty between the predecessor State and another State only if the other State and the new State both agree. 1992) Limitations to RSS a) It applies only to treaties of indefinite duration. 1267. and once these conditions cease to exist. When the service has become so difficult as to be manifestly beyond the . the obligor may also be released therefrom.71 Northwest Orient Airlines. PUBLIC INTERNATIONAL LAW 2008 contemplation of the parties. is NOT. NO TECHNICAL RULES. in whole or in part. b) The vital change must have been unforeseen or unforeseeable and should have not been caused by the party invoking the doctrine. and d) It cannot operate retroactively upon the provisions of a treaty already executed prior to the change in circumstances. it has to notify the depository that it regards itself as a succeeding party to the treaty. but if it wants to do so. Rules Governing Termination of RSS a) a fundamental change (FC) must have occurred with respect to circumstances existing at the time of the conclusion of the treaty. whether on the ground of rebus sic stantibus or pursuant to Article 39. equity and common sense to the text for the purpose of discovering its meaning. b) the existence of those circumstances constituted the basis of the consent of the parties to be bound by the treaty. June 23. e. CA (1997) The principle of rebus sic stantibus neither fits in with the facts of the case. may be implied from the conduct of both States. but its own treaties becomes applicable to the newly acquired territory. There are. CANONS OF INTERPRETATION Generally regarded by publicists as applicable to treaties consist largely of the application of principles of logic. and c) the change has radically transformed the extent of the obligations still to be performed under the treaty. the contract also ceases to exist. an absolute application of the principle of rebus sic stantibus. The courts are concerned only with the interpretation and application of laws and treaties in force and not with their wisdom or efficacy. This theory is said to be the basis of Article 1267 of the Civil Code. New States Formed Through Secession or Disintegration Succeeds AUTOMATICALLY to most of the predecessor’s treaties applicable to the territory that has seceded or disintegrated. Such. it does not succeed to the predecessor State’s treaties.g. PNCC V. Interpretation of Treaties A treaty shall be interpreted in good faith in accordance with the ordinary meaning to be given to the terms of the treaty in their context and in the light of its object and purpose. however. rejection of the treaty. New States Formed Through Decolonization a) a new State is under NO obligation to succeed to the old State as a party to a multilateral treaty. the parties stipulate in the light of certain prevailing conditions. Under this theory. Notes: ☀ “Clean Slate” Doctrine – Under this doctrine. however. c) It must be invoked within reasonable time. When FC cannot be invoked a) if the treaty establishes a boundary b) if the FC is the result of the breach by the party invoking it of an obligation owed to any other party to the treaty. SANTOS V. however. ▪ When an existing State acquires a territory. which would endanger the security of contractual relations. 210 SCRA 256. seceding or disintegrating States DOES NOT make succession to an existing treaty automatic. The conclusion and renunciation of treaties is the prerogative of the political departments and may not be usurped by the judiciary. which provides: “ART. It is therefore only in absolutely exceptional changes of circumstances that equity demands assistance for the debtor EFFECT OF TERRITORIAL CHANGES (1978 CONVENTION ON SUCCESSION OF STATES IN RESPECT TO TREATIES) Dispositive Treaties These are treaties which deal with rights over territory and are deemed to run with the land and are not affected by changes of sovereignty. which enunciates the doctrine of unforeseen events. NORTHWEST AIRLINES (1992) Obviously. treaties dealing with boundaries between States. This is a political act.” This article. ★ When acts of violence occur therein. A treaty may be authoritatively interpreted: a) by interpretation given by the treaty itself b) by mutual agreement or c) through international court arbitration PUBLIC INTERNATIONAL LAW 2008 State may expel aliens within its territory. is NOT BINDING to the other party unless the latter accepts it. This is subject to the “Non-Refoulement Principle. No interpretation is needed when the text is clear and unambiguous. Subjected to restrictions not usually imposed against transient aliens. . ★ The interpretation of one State. Moreover. These works are examined for the purpose of ascertaining the intention of the parties. in accordance with international law. j) Severance of diplomatic or consular relations.aliens’ rights are not at par with citizens’ as regards political or civil rights. As a State cannot refuse to receive such of its subjects as are expelled from abroad. i) War between the parties – war does not abrogate ipso facto all treaties between the belligerents. h) Doctrine of RSS.” Notes: ★ ★ ★ Reconduction It means the forcible conveying of aliens. Exception: If the injury is not directly attributable to the receiving State and when it was proximately caused by the alien himself. or to enable the victim or his heirs to pursue civil remedies. RIGHT OF DENUNCIATION – the right to give notice of termination or withdrawal which must be exercised if provided for in the treaty itself or impliedly. punish the guilty. ★ Bases of Grant of Rights a) Principle of Reciprocity b) MFN treatment c) Nationality treatment – equality between nationals and aliens in certain matters. Rule: A State is responsible for the maintenance of law and order within its territory. l) Voidance of the treaty because of defects in its conclusion or incompatibility with international law or the UN Charter. e.g. the home State of such aliens as are reconducted has the obligation to receive them. Expulsion may be predicated on the ground that the presence of the alien in the territory will menace the security of the State. B. when the rights and obligations under the treaty would not devolve upon the State that may succeed to the extinct State. f) Conclusion of a subsequent inconsistent treaty between the same parties. STATE RESPONSIBILITY FOR INJURY TO ALIENS Rule: NO State is under obligation to admit aliens. quota system Q: Is the State liable for death and injury to aliens? A: NO.72 ★ TRAVAUX PREPARATOIRES Preparatory works as a method of historical interpretation of a treaty. This flows from sovereignty. b) In bipartite treaties. Exception: If there is a treaty stipulation imposing that duty. the extinction of one of the parties terminates the treaty. d) 1948 UDHR and other treaties DOCTRINE OF STATE RESPONSIBILITY A State is under obligation to make reparation to another State for the failure to fulfill its primary obligation to afford. k) Emergence of a new peremptory norm contrary to the existing treaty. ★ Limitations . a) Transient b) Domiciled/Residents – domicile creates a sort of qualified or temporary allegiance. c) Mutual agreement of ALL the parties. investigate the case. unless it participates directly or is remiss or negligent in taking measures to prevent injury. g) Violation of the treaty. it may be said that the State is indirectly responsible. the proper protection due to an alien who is a national of the latter State. Position of Aliens After Reception When aliens are received. d) Denunciation of the treaty by one of the parties. ★ State may subject admission of aliens to certain legal conditions. TERMINATION OF TREATIES Most Common Causes: a) Termination of the treaty or withdrawal of a party in accordance with the terms of the treaty. the State cannot be regarded as an absolute insurer of the morality and behavior of all persons within its jurisdiction. even according to its municipal laws and given by its authorized organs within the State. they are subject to the municipal laws of the receiving State. e) Supervening impossibility of performance. on the other hand. ART. of the nationalities which any such person possesses. HAGUE CONVENTION OF 1903. distribution and exchange without paying compensation. * ☀ These two doctrines are used interchangeably by authors and commentators without any effort to make a distinction between the two. ★ Developing countries. Doctrine of Genuine Link The bond of nationality must be real and effective in order that a State may claim a person as its national for the purpose of affording him diplomatic protection. b) gross deficiency in the administration of judicial or remedial process. Without prejudice to the application of its law in matters of personal status and of any convention in force. and the law does not lightly hold a State responsible for error committed by the courts. Denial of Justice This term has been restrictively construed as an injury committed by a court of justice. Acts or Omissions Imputable to the State It is necessary to distinguish acts of private individuals and those of government officials and organs. NOTTEBOHN CASE 1955 ICJ * Doctrine of Effective Nationality When a person who has more than one nationality is within a third State. maintain that States may expropriate the means of production. to the end that travel. Why is there no denial of justice unless misconduct is extremely gross? – The reason is that the independence of the courts is an accepted canon of democratic government.73 PUBLIC INTERNATIONAL LAW 2008 Function To provide. a third State shall. It may be treated alike. Minimum International Standard (MIS) NO PRECISE DEFINITION The treatment of an alien. adequate and effective. hoping to attract foreign investments. to bad faith. obstruction or denial of access of courts. 5. in order to constitute an international delinquency. recognize exclusively in its territory either the nationality of the country in which he is habitually and principally resident or the nationality of the Notes: . Essential Elements: 1) an act or omission in violation of international law 2) which is imputable to the State 3) which results in injury to the claimant either directly or indirectly through damage to a national. to willful neglect of duty or to an insufficiency of governmental action so far short of international standards that every reasonable and impartial man would readily recognize its insufficiency. 5. should amount to an outrage. are inclined to accept Western view. he shall be treated as if had only one – either the nationality of the country which he is habitually and principally a resident or the nationality of the country with which in the circumstances he appears to be most closely connected – without prejudice to the application of its (3rd State’s) law in matters of personal status and of any convention in force. adequate protection for the stranger. NEER’S CASE. or d) a manifestly unjust judgment. ★ Communist countries. the State is in reality asserting its own right. USMEXICAN CLAIMS COMMISSION Expropriation of Foreign-Owned Property Western countries maintain that MIS requires: a) expropriation must be for a public purpose. b) it must be accompanied by payment of compensation for the full value of the property that is prompt. Within a third State a person having more than one nationality shall be treated as if he had only one. by resorting to diplomatic actions on his behalf. c) failure to provide those guarantees usually considered indispensable to the proper administration of justice. trade and intercourse may be facilitated. however. There is denial of justice when there is: a) unwarranted delay. in the general world interest. CONDITIONS FOR ENFORCEMENT OF CLAIMS 1) nationality claim 2) exhaustion of local remedies 3) no waiver 4) no reasonable delay in filing the claim 5) no improper behavior by injured alien Nationality of claim In asserting the claims of its nationals. Q: What is the “doctrine of effective nationality” (genuine link doctrine)? Held: This principle is expressed in Article 5 of the Hague Convention of 1930 on the Conflict of Nationality Laws as follows: Art. It is the bond of nationality between the state and the individual which confers upon the State the right of diplomatic protection. 2) Those whose fathers or mothers are citizens of the Philippines. 4) Those who are naturalized in accordance with law. Q: Is the Calvo clause lawful? A: Insofar as it requires alien to exhaust the remedies available in the local state. if there be any. conformable the Sec. 23 June 1989 The Nottobohm Case is not relevant in the petition before us because it dealt with a conflict between the nationality laws of two states as decided by a third State. COMELEC 174 SCRA 245. jus soli (by place) 2) Naturalization a. that concerns the protection of refugees from being returned to places where their lives or freedoms could be threatened. b) When there are no remedies to exhaust. 1989) Non-Refoulement Principle Non-refoulement is a principle in international law. After some 200 were determined to not be a threat. even the US is not claiming Frivaldo as its national. (Source: Wikipedia) FRIVALDO v. non-refoulement refers to the generic repatriation of people. 174 SCRA 245. COMELEC. CALVO CLAUSE Named after an Argentinean lawyer and statesman who invented it stipulating that the alien agrees in advance not to seek diplomatic intervention.74 country with which in the circumstances he appears to be in fact most closely connected. waiver of individual does not preclude the State to pursue the claim. it may be enforced as a lawful stipulation. An example of the non-refoulement principle can be found in the 2007 issue of Israel jailing 320 refugees from the Darfur conflict in Western Sudan. 1987 Phil. ☀ disreg arded by international arbitral tribunals because the alien cannot waive a claim that does not belong to him but to his government. Exceptions: a) When the injury is inflicted directly by the State such as when its diplomats are attacked. legitimation d. option e. in fact. No third State is involved in the case at bar. AIV. Many of them were released to Israeli collective farms called kibbutzim and moshavim to work until the conflict subsides enough for their return. No waiver The claim belongs to the State and not to the individual. regardless of other nationality laws. We can decide this question alone as sovereign of our own territory. Due to laws erected for the protection of Israel from the anti-Semitic atmosphere in the region. Exhaustion of Local Remedies Rule: The alien himself must have first exhausted the remedies provided by the municipal law. 1 of the Hague Convention (1903) which provides: “it is for each State to determine under its laws who are its nationals. specifically refugee law. usual repatriation guidelines could not be followed in part due to nonrefoulement principles. it may not be interpreted to deprive the alien’s state of the right to protect or Notes: . 3) Those who elect Philippine citizenship pursuant to the provisions of the Constitution of 1935. marriage c. (Frivaldo v. refugees fleeing to Israel in avoidance of the Darfur conflict were jailed in the interest of national security. appointment as PUBLIC INTERNATIONAL LAW 2008 government official 3) Resumption or Repatriation – recovery of the original nationality upon fulfillment of certain conditions. The sole question presented to us is WON Frivaldo is a citizen of the Philipines under our own laws. 5 Modes of Losing Nationality 1) Release 2) Deprivation 3) Expiration 4) Renunciation 5) Substitution §1. which applies to those who can prove a well-grounded fear of persecution based on membership in a social group or class of persons. acquisition of domicile f. June 23. c) The application for remedies would result in no redress. jus sanguinis (by blood) b. Constitution The following are citizens of the Philippines: 1) Those who are citizens of the Philippines at the time of the adoption of the Constitution. However. Thus. generally refugees into war zones and other disaster areas. naturalization proceedings b.” 3 Modes of Acquiring Nationality 1) Birth a. Unlike political asylum. The mere denial of the existence of a dispute does not prove its non-existence because disputes are matters for objective determination. It may refer to the intrinsic validity of the laws passed by the state or to the manner in which such laws are administered and enforced. YES.75 vindicate his interests in case they are injured by local state. Good Offices 3. (PCIJ on STATUS OF EASTERN CARELIA. or. So to would one calling for the arbitrary punishment of accused persons without compliance with the usual requisites of due process. be compelled to submit its disputes with other States either to mediation or arbitration. No cash or other valuable property taken from the American businessman was recovered. Pacific Settlement of International Disputes Nature International Dispute Defined Optional Clause Types 1. (1995 Bar) A: 1. Conciliation 6. 2. In an action for indemnity filed by the US Government in behalf of the businessman for injuries and losses in cash and property. In this case.) Dispute – is a disagreement on a point of law or fact. ▪ The charging of one State and the denial of another of the dispute as charged. if he has lost his life. What is the International standard of justice? It is defined as the standard of the reasonable state and calls for compliance with the ordinary norms of official conduct observed in civilized jurisdictions. on the loss caused by the death to his dependents. Is the contention of the Cambodian Government correct? Explain. it can not be held responsible for the acts of the rebels for the rebels are not their agents and their acts were done without its volition. No improper behavior by injured alien. Within minutes two truckloads of government troops arrived prompting the rebels to withdraw. Government troopers immediately launched pursuit operations and killed several rebels. Victorious rebel movements are responsible for the illegal acts of their forces n the course of the rebellion. Q: What is the principle of attribution? (1992 Bar) A: The acts of private citizens or groups cannot themselves constitute a violation by the Philippines if said acts cannot be legally attributed to the Philippines as a State. replacing the lawful Government that was toppled. a law imposing death penalty for a petty theft would fall short of the international standard.” but only after the State-parties agree thereto. YES. the PUBLIC INTERNATIONAL LAW 2008 Cambodian Government contended that under International Law it was not responsible for acts of the rebels. 1. the government troopers immediately pursued the rebels and killed several of them. Judicial Settlement ¯°º°¯ Nature It is well established in international law that no State can. 2. or to any other kind of pacific settlement (PS). without its consent. Unless it clearly appears that the Cambodian government has failed to use promptly and with appropriate force its constituted authority. International Dispute – if the dispute arises between two or more States. For example. Mediation 4. He who comes to court for redress must come with clean hands. Methods of Pressing Claims 1) Diplomatic Intervention 2) International judicial settlement – The ICJ is authorized to assume jurisdiction to determine “the nature or extent of the reparation to be made for the breach of an international obligation. Enquiry 5. a conflict of legal views or interests between two persons. Nature and Measure of Damages Reparation may consist of restitution: a) in kind b) specific performance c) apology d) punishment of the guilty e) pecuniary compensation f) or the combination of the above Measure – estimate of the loss caused to the injured individual. Q: In a raid conducted by rebels in a Cambodian town. Arbitration 7. The acts of the rebels are imputable to them when they assume as duly constituted authorities of the State. creates an international dispute as “there has thus Notes: . an American businessman who has been a long-time resident of the place was caught by the rebels and robbed of his cash and other valuable personal belongings. may the new government be held responsible for the injuries or losses suffered by the American businessman? Explain. Suppose the rebellion is successful and a new government gained control of the entire State. Negotiation 2. on the other hand. II. Good Offices An attempt of a third party to bring together the disputing States to effect a settlement of their disputes. This is the very essence of diplomacy. Good Offices In good offices. however. the third party mediates and is the more active one. The chief and most common method of settling international disputes. iv. have no binding character. usually consisting of persons designated by agreement between the parties to the conflict. the main object is to establish the facts. The existence of any fact which. Optional Clause [OPTIONAL JURISDICTION CLAUSE] The following are deemed legal disputes: 1. the existence of any fact which. interpretation of a treaty. offers his advice and in general attempts to conciliate differences. Negotiation The legal and orderly administrative process by which governments. Conciliation This is the process of settling disputes by referring them to commissions or other international bodies. Notes: ☀ Princ iple of Free Determination – this principle applies to the competence of the arbitral . ii. if established. VI. the parties seek a solution of their differences by direct exchange of views between themselves. and 4. for a settlement. Tender of good office PUBLIC INTERNATIONAL LAW 2008 A tender of good office may be made by: a) Third State b) international organs such as the UN. or c) Individuals or eminent citizens of a third State. if established. 2. Arbitration This is a procedure for the settlement of disputes between States by a binding award on the basis of law and as the result of an undertaking voluntarily accepted.76 arisen a situation in which the two sides hold clearly opposite views concerning the questions of the performance or nonperformance of their treaty obligations. Interpretation of a treaty. Mediation v. Mediation This is the action of a third party in bringing the parties to a dispute together and helping them in a more or less informal way to find a basis for the settlement of their dispute. Enquiry – in enquiry. the main object is not only to elucidate the facts but to bring the parties to an agreement. A situation. III. ▪ Object of Enquiry . for he proposes solution. OPPENHEIM ▪ Conciliation v.” ICJ Reports 1950 Legal Dispute – the following are deemed constitutive of a legal dispute: i. Enquiry Enquiry is the establishment of the facts involved in a dispute and the clarification of the issues in order that their elucidation might contribute to its settlement. In mediation. 3. is a state of affairs which has not yet assumed the nature of conflict between the parties but which may. By this method. Situation A dispute can properly be considered as a disagreement on a matter at issue between two or more States which has reached a stage at which the parties have formulated claims and counterclaims sufficiently definite to be passed upon by a court or other body set up for the purpose of pacific settlement. would constitute a breach of an international obligation. adjust and settle their differences. V. though not necessarily. the nature or extent of the reparation to be made for the breach of an international obligation. come to have that character. in the exercise of their unquestionable powers. which. The nature or extent of the reparation to be made for the breach of an international obligation.to ascertain the facts underlying a dispute and thereby prepare the way for a negotiated adjustment or settlement of the dispute. whose task is to elucidate the facts and make a report containing proposals. Any question of international law. iii. would constitute a breach of an international obligation. the Court must conclude that international disputes have arisen. the third party tendering good offices has no further functions to perform. Dispute v. This is NOT to be regarded as an unfriendly act. by contrast. TYPES OF Pacific Settlement I. Confronted with such a situation. any question of international law. once the parties have been brought together. In conciliation. ▪ Basis – it rests on the theory that certain disputes could be settled if the facts of the case were established. IV. conduct their relations with one another and discuss. the law to be applied and the procedure to be followed. it presupposes. c) venue. law – there exists no obligation to maintain diplomatic intercourse with other States. It is resorted to by States usually in cases of unfair treatment of their citizens abroad. It does not involve the use of force. but not international illegal act of one State against another in retaliation for the latter’s unfriendly or inequitable conduct. directly or indirectly. ☀ States are under no legal obligation to arbitrate their disputes. for the consequences of the illegal acts of another State. but not the severance of consular relations. VII. b) to influence the offending State to remedy the consequences of some unfriendly or illegal act. at least. States resorting to retorsion retaliate by acts of the same or similar kind as those complained of. therefore. Judicial Settlement This means settlement by a permanent international court of justice. Forcible Measures Short of War Severance of Diplomatic Relations Retorsion Reprisals Embargo Boycott Non-intercourse Pacific Blockade Collective Measures under the Charter ¯°º°¯ I. d) expenses. and c) That acts of reprisals must not be excessive. ☀ comp romis d’ arbitrage – the agreement to arbitrate. Notes: ☀ Choic e of Arbitrators – the arbitrators should be either freely selected by the parties or. PUBLIC INTERNATIONAL LAW 2008 possible and that sterner measures might possibly follow. Severance of Diplomatic Relations Severance may take place: a) to mark severe disapproval of a State’s conduct. II. No breach in int’l. Reprisals Retorsion . It involves withdrawal of diplomatic representation. without success. Arbitration proceedings may be similar to the functions and process of judicial settlement but the arbitral tribunal is NOT a permanent body as compared to the body referred to in this type of PS. III. the parties should have been given the opportunity of a free choice of arbitrators. f) rules of procedure. 2 Kinds of Reprisals: a) Reprisal as a form of self-help – is resorted to for the purpose of settling a dispute or redressing a grievance without going to war.77 tribunal. and g) the law to be applied. Reprisals Any kind of forcible or coercive measures whereby one State seeks to exercise a deterrent effect or to obtain redress or satisfaction. Suspension of Relations– has been used to denote a less drastic step than complete severance of diplomatic ties. to obtain redress from the delinquents State for the consequences of its illegal conduct. b) the method of selecting arbitrators and their number. b) that prior to recourse to reprisals an adequate attempt must have been made. which has refused to make amends for such illegal conduct. Contains the following: a) the questions to be settled. c) to serve notice on the other State that the issue between them has reached a point where normal diplomatic intercourse is no longer b) Reprisal taken by belligerents in the course of war – the purpose of the latter kind of reprisals is to compel a belligerent to observe or desist from violating the laws of warfare. severance of an existing relation does not tantamount to breach of international law. It is the charter of the arbitral tribunal. the existence of a state of war between the parties concerned. thus. e) the arbitral award. in accordance with judicial methods. Criteria for Legitimacy a) that the State against which reprisals are taken must have been guilty of a breach of international law. consequently no state of war exists between the State resorting to reprisals and the State against whom such acts are directed. Retorsion Consists of an unfriendly. VIII. a breach of the peace. or even within the territorial waters of the offending State. It may only be used collectively by or on behalf of the UN as an enforcement action under Article 41 of the UN Charter. that there exists a “threat to peace. under Article 39.78 Consists of acts which would ordinarily be illegal. ☀ Blockade may no longer be resorted to by States Members as a measure of self-help. UN Charter The SC may decide what measures not involving the use of armed forces are to be employed to give effect to its decisions. ☀ Vessels sequestered are not considered condemned or confiscated. Consists of retaliatory conduct which is legitimate or is not in violation of international law. Non-intercourse Consists of suspension of ALL commercial intercourse with a State. Boycott A comparatively modern form of reprisal which consists of a concerted suspension of trade and business relations with the nationals of the offending State. THE CUBAN QUARANTINE. authorizing them to perform acts of self-help against the offending State or its nationals for the purpose of obtaining satisfaction for the wrong sustained. It envisages the employment.” Article 41. A complete or partial interruption of economic relations with the offending State as a form of enforcement measure. Quarantine [See movie “Thirteen Days”] The right to stop and search vessels of third States suspected of carrying specified cargo to the “quarantined” State has been asserted by the blockading State. but must be returned when the delinquent State makes the necessary reparation. IV. These may include complete or partial interruption of: Civic or Pacific Embargo A form of embargo employed by a State to its own vessels within its national domain or of resources which otherwise might find their way into foreign territory. of compulsive measures to maintain or restore peace. V. and it may call upon the Members of the UN to apply such measures. Pacific Blockade A naval operation carried out in time of peace whereby a State prevents access to or exit from particular ports or portions of the coast of another State for the purpose of compelling the latter to yield to certain demands made upon it by the blockading State. if necessary. This may be: . the practice was extended to such vessels also as were seized in the high seas. These measures may or may not involve the use of armed forces. Later. The enforcement provisions of the Charter are brought into play only in the event that the SC determines. Collective Embargo Embargo by a group of States directed against an offending State. Embargo (Sequestration / Hostile Embargo) This is originally a form of reprisal consisting of forcible detention of the vessels of the offending State or of its nationals which happened to be lying in the ports of the injured or aggrieved State. VII. ☀ Third States do not acquire the status of neutrals because there is no belligerency between the blockader and the State. or an act of aggression. Acts which give rise to retorsion though obnoxious do not amount to an international delinquency. Collective Measures under the Charter A system of peace enforcement under the UN Charter. a) b) PUBLIC INTERNATIONAL LAW 2008 collective embargo on import or export of narcotic drugs collective embargo by way of enforcement action under the UN Charter Notes: Generally resorted to by a State in consequence of an act or omission of another State which under international law constitutes an international delinquency. Forms of Reprisals a) military occupation b) display of force c) naval bombardment d) seizure of ships at sea e) seizure of properties of nationals of the delinquent State f) freezing of assets of its citizens g) embargo h) boycott i) pacific blockade Letters Of Marque or Special Reprisals Act of a State granting their subjects who could not obtain redress for injury suffered abroad. VI. sea. postal. 2007 by Associate Justice Adolfo S. or at any rate frightfully inadequate. or land forces of Members of the UN. herald. consisting of individuals who are armed. not just humanitarian. It regulates the conduct of actual conflict (jus in bello) as distinguished from laws providing for the instances of the lawful resort to force (jus ad bellum). Such action may include: a) demonstrations b) blockade and c) other operations by air. religion and farsighted policy. It is a functional and utilitarian body of laws. is no longer permitted at present time. The Laws of War Definition of War Legality of War Rules of Warfare Sanctions of the Laws of War Commencement and Termination of War Effects of Outbreak of War Conduct of Warfare ¯°º°¯ War INGRID DETTER DE LUPIS A sustained struggle by armed forces of a certain intensity between groups of certain size. and severance to the diplomatic relations. It is part of International Criminal Law and deals with breaches of international rules on the laws of armed conflict entailing the personal liability of the individuals concerned. International Humanitarian Law (IHL) These are the laws of armed conflict. telegraphic. Rules of War Obsolete The radical change in the character of war. Temperamenta of Warfare ☀ 1907 2nd Hague Conference – The contracting States recognized that hostilities between them ought not to commence without previous and unequivocal warning which might take the form of either: a) a declaration of war giving reasons. As Self-Defense – the use of force in self-defense is permitted only while the SC has not taken the necessary measures to maintain or restore international peace and security. as opposed to the responsibility of the State which is covered by Public International Law proper. UN Charter Should the SC consider that measures provided for in Article 41 would be inadequate or have proved to be inadequate. Nature of Enforcement Action under UN UN Forces must behave in a manner consistent with the purposes and ideals of the Organization and must obey the rules of war which represent a general international attempt to humanize armed conflict. The 2007 Metrobank Lecture on International Law. or land forces as may be necessary to maintain or restore international peace and security. war commences upon the commission of an . sea. Notes: Article 42. has rendered many of the traditional rules of warfare obsolete. both in scope and method. or in pursuance of a decision or recommendation of the SC to take forcible action against an aggressor. (IHL: A Field Guide to the Basics. radio. air. ★ The laws of war are not applicable to war alone in its technical sense. but to all armed conflicts. Sanctions of the laws of war Observance of the rules of warfare by belligerents is secured through several means recognized by international law: 1) reprisals 2) punishment of war crimes committed by enemy soldiers and other enemy subjects 3) protest lodged with the neutral powers 4) compensation ☀ The taking of hostages. sea. it may take such action by air. who wear distinctive insignia and who are subjected to military discipline under responsible command. Azcuna) COMMENCEMENT ☀ It was customary to notify an intended war by letters of defiance. animo belligerendi From the point of view of international law. and other means of communication. or preliminary warning by declaration or ultimatum.79 a) b) economic relations and of rail. 22 Nov. formerly considered a legitimate means of enforcing observance of the laws of war. It used to be called the laws of war. b) an ultimatum with a conditional declaration of war. Legality of War under UN The use of armed force is allowed under the UN Charter only in case of individual or collective selfdefense. PUBLIC INTERNATIONAL LAW 2008 Grotius advocated moderation in the conduct of hostilities for reasons of humanity. Q: What are some kinds of non-hostile intercourse between the belligerents? A: Among the kinds of non-hostile intercourse are flags of truce. appropriation of property is not allowed to be performed by the military occupant. Modern Practice To denote the doctrine that territory. status quo ante bellum Each of the belligerents is entitled to the territory and property which it HAD possession of at the commencement of the war. Legitimate Acts of Military Occupant Postliminium has no effects upon the acts of a military occupant during the occupation which under international law it is competent to perform e. Dictated Treaty This happens where the decisive victory of one of the belligerents leads it to impose its will on the other. Or a peace treaty thru a dictated treaty. hence. but upon return they recovered their former status. or a capitulation. by which each belligerent is regarded as legally entitled to such property as are actually in its possession at the time hostilities ceased. individuals and property. but is now understood to refer to a ceasefire with conditions attached. CAPITULATION It is the surrender of military troops. Suspension of Arms It is the temporary cessation of hostilities by agreement of the local commanders for such purposes as the gathering of the wounded and the burial of the dead. cartels. after having come under the authority of the enemy. Q: When is the principle of postliminium applied? (1979 Bar) b) by a treaty of peace – this is the usual method of terminating war. Imposed by the victor. TERMINATION a) by simple cessation of hostilities. ARMISTICE It is the suspension of all hostilities within a certain area (local) or in the entire region of the war (general) agreed upon by the belligerent governments. an armistice. . Postliminium (See movie: “The Gladiator”) A term borrowed from Roman Law concept which meant that persons or properties captured or seized and taken beyond (post) the boundary (limen) could be enslaved or appropriated. However. a cease-fire. War Anglo-American Rule Bound by a statement by the executive as to when a state of war is commenced. safeguards and license to trade. It may be a negotiated peace treaty.g. forts or districts in accordance with the rules of military honor. Q: What is the meaning or concept of uti possidetis? (1977 Bar) A: The problem concerning ownership of property which have changed hands during the course of the war are generally settled by the application of the rule of uti possidetis.80 act of force by one party done in animo belligerendi. c) PUBLIC INTERNATIONAL LAW 2008 by unilateral declaration – if the war results in the complete defeat or unconditional surrender of a belligerent the formal end of the war depends on the decision of the victor. without the conclusion of a formal treaty of peace – since no formal treaty of peace is concluded. End of War NAVARRO VS. BARREDO Termination of war when used in private contracts refers to the formal proclamation of peace by the US and not the cessation of hostilities between RP and Japan during the WWII. the ownership of the property reverts back after the military occupancy without payment of compensation. CEASEFIRE It is the unconditioned stoppage of hostilities by order of an international body like the Security Council for the purpose of employing peaceful means of settling the conflict. usually for the purpose of arranging terms of peace. Notes: uti possidetis Each belligerent is regarded as legally entitled to such property as are actually in its possession at the time hostilities ceased. a truce. revert to the authority of the original sovereign ipso facto upon retaking possession. Q: By what agreements may hostilities be suspended between the belligerents? A: Hostilities may be superceded by a suspension of arms. TRUCE Sometimes use interchangeably with armistice. collection of ordinary taxes. passports. safe-conduct. the problems concerning ownership of property which have changed hands during the course of the war are generally settled by the application of the rule of uti possidetis. On enemy properties 4. Some consider the enemy persons ex lege during the whole duration of the hostilities. On enemy property In general. (4) to provide facilities for religious. Rupture of diplomatic relations and termination of consular activities 2. (8) to make transfers only in a humane manner. it may be stated that States treat as void contracts which may give aid to the enemy or add to his resources.81 A: Where the territory of one belligerent state is occupied by the enemy during war. or 2) is controlled by individuals bearing enemy character. On enemy persons 3. war suspends the operation of the statute of limitations. (6) to permit a degree of communication with the outside world. (10) to release internees when the reasons for internment cease or when hostilities terminate. On trading and intercourse 5. In general. the legitimate government is ousted from authority. within wide limits. (7) the refrain from excessive or inhuman penal and disciplinary measures. When the belligerent occupation ceases to be effective. a right of action which has accrued to him before the war is deemed suspended for the duration of the war. (9) to record and duly certify deaths. and to inquire into deaths other than from natural causes. EFFECTS OF WAR OUTBREAK 1. together with all its laws. (2) to furnish adequate food and clothing (3) to provide family accommodations with due privacy and facilities. Notes: b) nationality test – this is the preferred continental practice. In the Philippines. On treaties Rupture of diplomatic relations / termination of consular activities The respective diplomatic envoys are allowed to leave for their home countries. intellectual and physical activities. the archives of the mission. and consular archives are usually left under the protection of another foreign envoy or consul of another State. by virtue of the jus postliminium. • public – confiscated • private – sequestered only and subject to return or reimbursement On trading and intercourse The practice of belligerents in modern wars of forbidding by legislation all intercourse with alien enemies. 1949 GENEVA CONVENTION Locus standi during occupation The practice of states are varied. when an enemy subject is unable to sue during war. subjects of a neutral State may be treated as enemies because of certain activities where they participate. resident or not. Determination of enemy character a) territorial test – enemy character depends on the residence or domicile of the person concerned PUBLIC INTERNATIONAL LAW 2008 Rules for interment of enemy aliens (1) to provide for the internees’ safety and welfare. War also brings about the cessation of consular activity. (5) to permit the use of their personal properties and financial resources. activities test – whether national or not. the authority of the legitimate government is automatically restored. On enemy persons International law leaves each belligerent free. Some allowed them to sue and be sued subject to so many exceptions. except as such as are permitted under license. c) d) e) . or necessitate intercourse or communication with enemy persons. territorial or commercial domicile test – in matters pertaining to economic warfare. Thus. The subjects of the belligerent are deemed enemy persons regardless of where they are. A corporation is regarded as enemy person if it: 1) is incorporated in an enemy teriroty. The main object of such laws was to prohibit transactions which would benefit the enemy or enemy persons. Further. goods belonging to enemy persons are considered enemy property. On contracts 6. On contracts International law leaves each belligerent free to regulate this matter by his own domestic law. to designate the persons whom it will treat as having enemy character. The official residence of the envoy. controlling interest test – this is the test as to corporations in addition to the place of incorporation test. 82 On treaties Modern view is that war does NOT ipso facto terminate all treaties between belligerents. they are not entitled to the status of prisoners of war. Hostilities conducted by armed bodies of men who do not form part of an organized army. such as treaties of alliance. from military forces for “personal gain. Spies – A soldier employing false pretenses or acts through clandestine means to gather information from the enemy. and all analogous liquids. When caught. having been recruited in another country. by means of regulated violence not forbidden by conventional or customary rules of war and with the least possible loss of lives. They are treated as lawful combatants provided that: a) they are commanded by a person responsible for his subordinates. b) they wear a fixed distinctive sign recognizable for his subordinates. Military Scouts are not spies. 5) The laying of “contact” mines 6) Explosives from balloons 3 Protocols on Restrictions Protocol I on Fragmentation Weapons Protocol II on Treacherous Weapons Protocol III on Incendiary Weapons Other Questionable weapons 1) Fuel explosive weapons that kill by air shock waves 2) Flame blast munitions that combine fuel air explosive effect with radiation in chemical fireball munitions. ☀ Treaties may contain provisions to the effect that it will remain in force notwithstanding the existence of war. Principle of Humanity [THE ETHICS OF WARFARE] Forbid the use of weapons which cause indiscriminate destruction or injury or inflict unnecessary pain or suffering. 2) Irregular Forces (IF) – also known as franctireurs consist of militia and voluntary corps. IF and Levee may be treated as prisoners of war under Protocol I of 1977. materials or devices 4) the use of bacteriological methods of warfare.” are not covered by protection. This principle does not prohibit espionage. and with commercial relations are deemed abrogated by the outbreak of war between the parties thereto. or other gases. 4) Levee en masse Takes place when the population spontaneously rises in mass to resist the invader. poisonous. and air force. Principle of Chivalry This principle requires the belligerents to give proper warning before launching a bombardment or prohibit the use of perfidy in the conduct of hostilities. as soon as possible. Military necessity 2. 3) Laser weapons which cause burns and blindness 4) Infrasound devices that cause damage to the central nervous system. Non-combatant members of the armed forces include: chaplains. and d) they conduct their operations in accordance with the laws and customs of war. time and money. Q: Who constitute combatants? A: They are the following: 1) Regular Forces (RF)– the army. Humanity 3. See this reviewer’s section on POW. If captured. . PUBLIC INTERNATIONAL LAW 2008 Guerilla warfare – considered as IF. They enjoy privileges due to armed forces. Restrictions on weapons Prohibited weapons: 1) explosive bullets 2) use of dum-dum bullets 3) employment of projectiles whose only object is diffusion of asphyxiating. ☀ Treaties dealing with political matters. army services and medical personnel. they are not to be regarded as prisoners of war. 3) Non-privileged Combatants (NPC) – individuals who take up arms or commit hostile acts against the enemy without belonging to the armed forces or forming part of the irregular forces. A soldier not wearing uniform during hostilities runs the risk of being treated as a spy and not entitled to prisoner of war status. Mercenaries – considered as NPC Those who. navy. Chivalry Doctrine of Military Necessity A belligerent is justified in resorting to all measures which are indispensable to bring about the complete submission of the enemy. c) they carry arms openly. NOTE: Only RF. Notes: CONDUCT OF WARFARE (See movie: “The Patriot”) 3 Basic Principles of IHL: 1. 6) members of the population of non-occupied territory who take up arms as a levee en masse against an invading army. churches and the like as shield from attack. 4) various categories of persons accompanying an army unit. war crimes and aggression. 8) Hospitals.83 LIMITATION ON TARGETS OF ATTACK Only military targets are subject to attack by the armed forces of a belligerent as a basic rule of warfare. Q: What are the core crimes in IHL? A: The core crimes in IHL are genocide.” A place free of combatants. 2) members of other militias or volunteer groups. crimes against humanity. Starvation Reprisals – are not reprisals as a form of selfhelp. Must only be treated as POW. These core crimes are specified in the Statues of the ICC (or the Rome Statute for an ICC) which describes them as the most serious crimes of concern to the international community as a whole.” even if any of the combatant powers do not recognize the existence 7) Parachutists – those who bail out from aircrafts in distress. 5) members of the crew of merchant vessels and civilian aircraft who do not benefit by more favorable treatment under any other provisions of internal law. 9) Food supplies and crops FORBIDDEN METHODS No Quarter – such orders implying that no survivors are to be left after an attack. the Suez Canal and Panama Canal. hospital ships and medical units – a clear marking or a Red Cross to show their status. Azcuna) 1949 Geneva Convention III The rules of POW applies to prisoners of war who are captured in a properly declared war or any other kind of “armed conflict. belligerent reprisals are of a completely different type. have permanently joined the civilian population. The 2007 Metrobank Lecture on International Law. dikes. These are acts of vengeance by a belligerent directed against groups of civilians or POWs in retaliation of or response to an attack by other civilians against the belligerent. EX: Aland Islands. Likewise. – Civilians and persons hors de combat – persons hors de combat are those who are either wounded or. certain places and objectives are not subject to attack. 22 Nov. 3) members of regular armed forces professing allegiance to a government or an authority not recognized by the capturing State. such as civilian members of military aircraft crew. 2007 by Associate Justice Adolfo S. the ICC Statute’s and definitions of the core crimes are authoritative statements for us since they are practically lifted from customary international law sources and from the Geneva Conventions of 1949 and other treaties to which we are parties. including those of organized resistance movements. the Spitzbergen. 5) 6) Dangerous installations dams. etc. as well as members of militias or volunteer corps forming part of such armed forces. instead. (IHL: A Field Guide to the Basics. g) Area bombing a) b) Notes: 2) Open towns – also known as “non defended locality. These crimes are within the jurisdiction of the ICC.. PRISONERS OF WAR (POW) The following persons captured must be treated as POW: 1) members of the armed forces. NOTE: Although the Philippines has signed but not yet ratified the Rome Statute establishing the ICC. 3) Cultural places of worship property and 4) Civil defense – includes personnel. Improper use of white flag Feigning surrender or pretending to have been wounded or to have a civilian status c) Using the uniform of the enemy d) Claiming neutral status e) Falsely flying the Red Cross flag f) Making hospitals. buildings and assets. for other reasons. subject to compliance with certain conditions. or nuclear electric plants. war correspondents. the Magellan Straits. clearly indicated by a blue triangle on an orange background distinctive sign. such as: PUBLIC INTERNATIONAL LAW 2008 1) Neutralized areas or zones – these are zones in the theater of operations established by special agreement between the belligerents for treatment of the wounded and civilians. Perfidy on treachery – this includes: . provided they are authorized to be with the army or unit. When is a Territory Deemed Under Military Occupation? Territory is deemed to be occupied when it is placed as a matter of fact under the authority of the hostile army. by means of a stand on the part of a state not to side with any of the parties at war A condition that applies in peace and war A status created by means of a treaty Notes: 4) They conduct their operations in accordance with the laws and custom of war. However. and PUBLIC INTERNATIONAL LAW 2008 the war continues. as far as possible in accordance with “the rules of assessment and incidence in force. Neutrality vs. Q: Can the belligerent occupant impose and collect taxes or contributions? A: YES. while . Neutralization (1988 Bar) Neutrality Neutralization Obtains only during war A status created under international law. NOTE: The belligerent occupant cannot compel the inhabitants to swear allegiance to him. DIRECTOR OF POSTS Belligerent occupation becomes an accomplished fact the moment the government of the invaded territory is rendered incapable of publicly exercising its authority and the invader is in a position to substitute and has substituted his own authority for that of the legitimate government of the occupied territory. guerilla warfare. TAN SE CHIANG v. 3) They carry arms openly. 3) a receipt must be given to each contributor. Rights & Duties of a Belligerent Occupant to continue orderly government to exercise control over the occupied territory and its inhabitants. dues and tolls. VALDEZ TAN KEH 75 Phil 371 His rights over the occupied territory are merely that of administration. annex the territory or set it up as an independent State. Under the Hague Regulations. 2) they can be imposed by written order of the Commander-in-Chief only. the occupant is empowered to collect taxes. Guerillas are entitled to be treated as prisoners of war provided they fulfill the following conditions: 1) They are commanded by a person responsible for his subordinates. (1982 Bar) When POW should be returned Upon cessation of war or hostilities. 4) the levy must be made as far as possible.” and he is bound to defray the “expenses of administration” out of the proceeds.84 of a state of war and even though these conflicts are “not of an international character. Conditions on levying taxes: 1) they must be for the needs of the army or local administration. 2) They have a fixed distinctive emblem recognizable at a distance. in contradistinction to requisitions which may be demanded by the Commander in a locality. is recognized. NOTE: Belligerent occupation is different from Military occupation. Under Article 4 of the 1949 Geneva Convention on Prisoners of War. such attitude creating rights and duties between the impartial States and the belligerents. Neutralization Rights and Duties of Neutrals and Belligerents Passage of Belligerent Warships Prohibition of Warlike Activities in Neutral Territory Neutral Asylum to Land and Naval Forces of Belligerent Right of Angary Blockade Contraband Unneutral Service Right of Visitation Neutrality An attitude of impartiality adopted by third States towards belligerents and recognized by the belligerents. Neutrality Neutrality Defined Neutrality v. Contributions – are money impositions on the inhabitants over and above such taxes. in accordance with the rules in existence and the assessment in force for taxes. hence he cannot.” Q: Is guerilla warfare recognized under International Law and may a captured guerilla demand treatment afforded a prisoner of war under the 1949 Geneva Convention? Explain. POWs facing criminal trial may be detained until the termination of the proceedings or punishment. CO KIM CHAN V. A: Yes. which consists in hostilities conducted in territory occupied by the enemy by armed bodies of men who do not form part of an organized army. and may be subjected to such restrictions as may be necessary. the neutral state may allow it as long as such repairs are absolutely necessary to render them seaworthy. and the neutral State shall leave such prisoners at liberty. Also. duty of prevention (positive) – places the neutral State under obligation to prevent its territory from becoming a base for hostile operations by one belligerent against the other. PROHIBITION OF WARLIKE ACTIVITIES IN NEUTRAL TERRITORY The Hague Convention No. a right of a neutral gives rise to a corresponding duty on the part of the belligerents. NEUTRAL ASYLUM TO LAND AND NAVAL FORCES OF BELLIGERENT POW’s who escape into neutral territory or are brought into neutral territory by enemy troops who themselves take refuge there shall become free ipso facto. PUBLIC INTERNATIONAL LAW 2008 maritime belt for the purpose of capturing enemy vessels as soon as they leave it. but if it allows them to remain in its territory. not repairs which would add in any way to their fighting force. unless the neutral state has prescribed otherwise in their municipal laws or unless the nature of repairs to be done or the stress of weather would require a longer time. RIGHT OF ANGARY A right of a belligerent to requisition and use. or even to destroy in case of necessity. except under certain circumstances. neutral property found in its territory.85 Brought about by a unilateral declaration by neutral state Cannot be effected by unilateral act only but must be recognized by other states. The power that guarantees its neutralization may be motivated either by balance of power considerations or by desire to make the state a buffer between the territories of the great powers. subject to certain conditions. 3 Conditions a. must be interned. and a right of a belligerent corresponds to a duty of the neutral. When the belligerent ship is detained by a neutral State. duty of acquiescence (passive) – requires a neutral to submit to acts of belligerents with respect to the commerce of its nationals if such acts are warranted under the law of nations. either in the ship itself or in another vessel or on land. the neutral State concerned has the right to take such measures as it deems necessary to render the ship incapable of putting to sea for the duration of the war. A state seeks neutralization where it is weak and does not wish to take an active part in international politics. however. the neutral State is not obliged to grant them asylum. belligerent warships cannot take shelter in a neutral port for any undue length of time in order to evade capture. The rule is that a prize may not be brought into a neutral port. to either belligerent in their war efforts. a state is said to be neutralized where its independence and integrity are guaranteed by an international convention on the condition that such state obligates itself never to take up arms against any other state. What are the characteristics of neutralized states? (1988 Bar) A: Whether simple or composite. 1) duty of abstention (negative) – should not give assistance. Neutral ports may not become places of asylum or permanent rendezvous for belligerent prizes. or enter into such international obligations as would indirectly involve it in war. XIII provides that “belligerents are forbidden to use neutral ports and waters as base of naval operations against their adversaries. 2) 3) PASSAGE OF BELLIGERENT WARSHIPS A neutral State may allow passage of belligerent warships through the maritime belt forming part of its territorial waters. in enemy territory or in the high seas. The maximum length of stay permissible is 24 hours. the officers and crew are likewise interned.” Thus. direct or indirect. Notes: Q: Switzerland and Austria are outstanding examples of neutralized states. What is prohibited is the passage upon its national rivers or canals. As regards fugitive soldiers. if they are compelled to land in neutral territory. are the canals which have become international waterways (such as the Suez Canal and the Panama Canal). In case a belligerent men-of-war refuses to leave neutral port in which it is not entitled to remain. Rights and Duties of Neutrals & Belligerents The nature of their rights are correlative. there must be an urgent need for the property in connection with the offensive or defensive war. except for self-defense. a neutral must prevent belligerent warships from cruising within its . The exception. although it is not forbidden to do so. Belligerent aircraft and their personnel. In the event that a neutral port or roadstead is used for repairs. it may assign them a place of residence so as to prevent them from rejoining their forces. that is. However. for the purpose of preventing ingress and egress of vessels or aircraft of all nations to and from the enemy coast or any part thereof. clothing. Doctrine of Ultimate Destination The liability of contraband to capture is determined not by their ostensible but by their real destination. must be brought before a Prize Court for trial. In the case of conditional contraband.86 b. and which are found by that belligerent on its way to assist the war operations or war effort of the enemy. Kinds of Contrabands a) absolute – goods which by their very nature are intended to be used in war. if it be needed. Consequences of contraband carriage Neutral States are not under obligation to prevent their subjects from carrying contraband to belligerents. A neutral vessel engaged in unneutral service may be captured by a belligerent and treated. Doctrine of Ultimate Consumption Goods intended for civilian use which may ultimately find their way to and be consumed by the belligerent forces are also liable to seizure on the way. CAPTURE Takes place if the cargo.g. carrying contraband or rendering unneutral service. etc. UNNEUTRAL SERVICE Denotes carriage by neutral vessels of certain persons and dispatches for the enemy and also the taking of direct part in the hostilities and doing a number of other acts for the enemy. it will still be considered as one continuous voyage provided it can be shown that its cargo will ultimately be delivered to a hostile destination. it is required that the goods be destined to the authorities or armed forces of the enemy. Hostile destination In case of absolute contraband it is necessary only to prove that the goods had as their destination any point within enemy or enemy-controlled territory. In both. CONTRABAND A term used to designate those goods which are susceptible of use in war and declared to be contraband by a belligerent. the property is within the territory or jurisdiction of the belligerent. fuel. but which are nevertheless of great value to a belligerent in the prosecution of the war. foodstuff. in general. NOTE: A neutral subject within the territory of a belligerent is not entitled to indemnity from either side against the loss of property occasioned by legitimate acts of war. TRIAL BEFORE A PRIZE COURT The captured vessel and cargo. but without compensation for delay and detention in the Prize Court. are liable to confiscation. whether they are attempting to break blockade. Only private or merchant vessels may be subjected to visit and search. the penalty for carriage of contraband would be confiscation of the contraband cargo. Neutral States have the duty to acquiesce in the suppression by belligerents of trade in contraband. compensation must be paid to the owner. STONE Requisites: a) susceptible of use in war b) destined for the use of a belligerent in its war effort. c. Even if the vessel stops at an intermediate neutral port. horses. or the vessel. and if this is found to be the case. or if grave suspicion requires further search which can only be undertaken in a port. e. to search neutral merchantmen for the purpose of ascertaining whether they really belong to the merchant marine of neutral States. b) conditional – goods which by their nature are not destined exclusively for use in war. the destination as of moment of seizure is critical. Doctrine of continuous voyage Goods which are destined to a neutral port cannot be regarded as contraband of war. BLOCKADE An operation of war carried out by belligerent seacraft or other means. Innocent cargo belonging to the same owner would also be subject to confiscation. or both. END Notes: . RIGHT OF VISITATION The right of belligerents (exercised only by men-ofwar and military aircraft of belligerents) to visit and. Doctrine of Infection PUBLIC INTERNATIONAL LAW 2008 Under the British and American practice. in the same way as neutral vessels captured for carriage of contraband. Innocent cargo belonging to another owner would be released. EDWIN REY SANDOVAL. COMPARATIVE TABLE OF PROHIBITED ACTS PROHIBITED ACTS OF A NEUTRAL STATE 1. THERE ARE DIFFERENT DISCUSSIONS WHICH WERE CULLED FROM AUTHORS ASIDE FROM ATTY. THIS IS PURELY FOR ACADEMIC PURPOSES AND IS STRICTLY NOT FOR SALE.87 PUBLIC INTERNATIONAL LAW 2008 WE SALUTE ATTY. LAWYERS. poor women in his city lost their access to affordable family planning programs. PROFESSORS. The City Mayor issues an Executive Order declaring that the city promotes responsible parenthood and upholds natural family planning. a. May the Commission on Human Rights order the Mayor to stop the implementation of the Executive Order? Explain. Is the Philippines in breach of any obligation under international law? Explain. LEGAL ENTHUSIASTS AND THE LIKE. Is the Executive Order in any way constitutionally infirm? Explain. If owned by the owner of the vessel confiscated/condemned CONSEQUENCES ON THE VESSEL CONSEQUENCES ON THE CARGO 2. b. including condoms. c. Private clinics! however. SANDOVAL’S LECTURES AND CASES SUCH AS SALONGA & YAP AND CRUZ. or the owner knew that the goods shipped . Notes: ACKNOWLEDGMENTS / ATTRIBUTIONS THIS IS A PRODUCT OF LIBERTAS ET IUSTICIA COMPILED BY ITS ACADEMICS COMMITTEE 20072008. THIS MATERIAL MAY ALSO BE OF GOOD USE UNDER OTHER PROFESSORS HANDLING THE SAME SUBJECT AS WELL AS THOSE TAKING REVIEW SUBJECT ON POLITICAL AND PUBLIC INTERNATIONAL LAW. If owned by a different owner Breach of Blockade Confiscated or brought to a prize court a) b) shall be confiscated IF: it consists of contrabands. He prohibits all hospitals operated by the city from prescribing the use of artificial methods of contraception. AND TO WHOM WE OFFER THIS MATERIAL WITH HUMILITY AND PRIDE. ALTHOUGH THIS IS MAINLY OUTLINED FOR PUBLIC INTERNATIONAL LAW CLASS UNDER ATTY. As a result. BARRISTERS. pills. intrauterine devices and surgical sterilization. WE ENCOURAGE THE FREE CIRCULATION OF THIS MATERIAL AMONGST THE RANKS OF STUDENTS. 2007 BAR. SANDOVAL FOR HIS NEVER FADING BRILLIANCE IN THE FIELD OF POLITICAL LAW. continue to render family planning counsel and devices to paying clients. Exception: When the cargo consists of both contrabands and innocent goods. it shall be confiscated (Doctrine of Infection). If owned by a different person. weight. Contraband cargo: confiscated. Performance of Unneutral Service Same as in Carriage of Contrabands Same as in Carriage of Contrabands . it (vessel) may only be confiscated if the contraband cargo is more than ½ of the total cargo by value. Innocent cargo: 1. Carriage of Contraband If owned by the owner of the vessel. it shall not be confiscated but it shall be released without compensation due to the delay of release and detention in the Prize Court.88 PUBLIC INTERNATIONAL LAW 2008 is going to a blockaded point and is going to be blockaded. Notes: General Rule: Shall be confiscated and seized. volume and freight. 2. a. Assume that in May 2005. received war reparations and. including the Philippines. this virus spread all over the world and caused $50 million in damage to property in the United States. Lawrence is a Filipino computer expert based in Manila who invented a virus that destroys all the files stored in a computer. b. under the 1951 San Francisco Peace Agreement -the legal instrument that ended the state of war between Japan and the Allied Forces -all the injured states. These women were either abducted or lured by false promises of jobs as cooks or waitresses. b. Name at least one basic principle or norm of international humanitarian law that was violated by the Japanese military in the treatment of the "comfort women. the Philippines adopted its own anti-hacker law. The Japanese government contends that the "comfort stations" were run as "onsite military brothels" (or prostitution houses) by private operators. Will that change your answer? 2007 BAR. waived all claims against Japan arising from the war.2007 BAR. and often suffered from severe beatings and venereal diseases. historians confirmed that during World War II. he was criminally charged before United States courts under their anti-hacker law. "comfort women" were forced into serving the Japanese military. There were many Filipina "comfort women. Assume that the extradition request was made after the Philippines adopted its anti-hacker legislation. . and eventually forced against their will to have sex with Japanese soldiers on a daily basis during the course of the war." a. Is the Philippines under an obligation to extradite Lawrence? State the applicable rule and its rationale. in return. However. In 1993. Assume that in July 2005. The United States has requested the Philippines to extradite him to US courts under the RP-US Extradition Treaty. and that in June 2005." The surviving Filipina "comfort women" demand that the Japanese government apologize and pay them compensation. Will that case prosper? c. and not by the Japanese military. to strengthen existing sanctions already provided against damage to property. Is that a valid defense? The surviving Filipina "comfort women" sue the Japanese government for damages before Philippine courts. This action might not be possible to undo. Are you sure you want to continue? We've moved you to where you read on your other device. Get the full title to continue reading from where you left off, or restart the preview.
https://www.scribd.com/document/85701356/Notes-in-Public-International-Law
CC-MAIN-2016-50
refinedweb
61,570
57.27
Fixing: a set ofdeclaration s in another namespace or class. Change in 7.3.3 namespace.udecl paragraph 3: In a using-declaration used as a member-declaration, the nested-name-specifier shall name a base class of the class being defined. If such a using-declaration names a constructor, the nested-name-specifier shall name a direct base class of the class being defined ; otherwise it for type B is invoked to initialize an object of a different type D (that is, when the constructor was inherited (7.3.3)), initialization proceeds as if a defaulted default constructor is. [ Example:struct B1 { B1(int, ...) { } }; struct B2 { B2(double) { } }; int get(); struct D1 : B1 { using B1::B1; // inherits B1(int, ...) int x; int y = get(); }; void test() { D1 d(2, 3, 4); // OK: B1 is initialized by calling B1(2, 3, 4), // then d.x is default-initialized (no initialization is performed), // then d.y is initialized by calling get() D1 e; // error: D1 has no default constructor } struct D2 : B2 { using B2::B2; B1 b; }; D2 f(1.0); // error: B1 has no default constructor struct W { W(int); }; struct X : virtual W { using W::W; X() = delete; }; struct Y : X { using X::X; }; struct Z : Y, virtual W { using Y::Y; }; Z z(0); // OK: initialization of Y does not invoke default constructor of X template<class T> struct Log : T { using T::T; // inherits all constructors from class T ~Log() { std::clog << "Destroying wrapper" << std::endl; } };Class template Log wraps any class and forwards all of its constructors, while writing a message to the standard log whenever an object of class Log is destroyed. ] - {}; P p(0); // OK: use M(0) to initialize N's base class, // use M() to initialize O: … ] Add a subclause to Annex C: Clause 12: Special member functions [special).
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0136r1.html
CC-MAIN-2019-47
refinedweb
307
57.1
table of contents - buster 4.16-2 - buster-backports 5.02-1~bpo10+1 - testing 5.03-1 - unstable 5.03-1 NAME¶readdir - read a directory SYNOPSIS¶ #include <dirent.h> struct dirent *readdir(DIR *dirp); DESCRIPTION¶The. RETURN VALUE¶. To distinguish end of stream and from an error, set errno to zero before calling readdir() and then check the value of errno if NULL is returned. ERRORS¶ - EBADF - Invalid directory stream descriptor dirp. ATTRIBUTES¶For an explanation of the terms used in this section, see attributes(7). In the current POSIX.1 specification (POSIX.1-2008), readdir() is not required to be thread-safe. However, in modern implementations (including the glibc implementation), concurrent calls to readdir() that specify different directory streams are thread-safe. In cases where multiple threads must read from the same directory stream, using readdir() with external synchronization is still preferable to the use of the deprecated readdir_r(3) function. It is expected that a future version of POSIX.1 will require that readdir() be thread-safe when concurrently employed on different directory streams. CONFORMING TO¶POSIX.1-2001, POSIX.1-2008, SVr4, 4.3BSD. NOTES¶AThe.
https://manpages.debian.org/buster-backports/manpages-dev/readdir.3.en.html
CC-MAIN-2019-47
refinedweb
191
53.47
== == The answer to your question depends upon the law in your state. If an individual files for bankruptcy most assets of the individual may be sold or otherwise disposed of in a Chapter 7 bankruptcy in to partially satisfy the debts of the individual. While an interest in an LLC is an asset of the individual, many states have statutes within their LLC Act which provide that an LLC interest may not be taken outright by a creditor, but rather a charging order will be issued. Typically this means that the individual who is the holder of the LLC interest will continue to be a member of the LLC and will continue to vote the LLC interest; however, any distributions which are made by the LLC to the individual would be paid to the creditor or creditors rather than to the individual due to the charging order. If YOU file than yes...and your interest/ownership of the stock in the LLC is an asset that may be used to pay your personal debts/liabilities. If the LLC files, than your personal assets aren't involved...of course your investment in the LLc will likely become worthless....and there will be an e review to make sure that self serving transactions weren't done. Finally, normally, until a business (the LLC) is well established, any loans/leases, etc someone makes to it tey require you to sign for personally too....so you would be personally liable for them anyway. LLC is Limited Liability Company. It's allowed by state statute. But the IRS doesn't recognize LLC as a classification for federal tax purposes. Under IRS Default Rules, a Limited Liability Company with at least two members is considered as a partnership. Form 8832 is Entity Classification Election. An LLC with two or more members would only have to file Form 8832 if the LLC didn't want to file as a partnership. As a partnership, the LLC would file Form 1065 (U.S. Return of Partnership Income). For more information, go to for Publication 541 (Partnerships) and Publication 3402 (Tax Issues for Limited Liability Companies). It depends. Unless the owners of the LLC elect to have it treated as a corporation, then an LLC which has at least two members is treated as a partnership and files a partnership tax return, Form 1065. If there is only one member of the LLC, then the IRS disregards the LLC as a separate tax reporting entity entirely. If the single member is an individual, then the member reports the LLC's income and deductions on the individual's person 1040, usually on Schedule C (for a business) or Schedule E (for real estate). If the single member of the LLC is a corporation, partnership or trust, it likewise files the information on its entity tax return (1120, 1120 S, 1065, 1041, etc...) If the members of the LLC file an election, the LLC may be treated as a corporation or an S corp. In that case, the LLC would file an appropriate return (Form 1120 or 1120 S). LLC (Limited Liability Company) is a type of business that's allowed by state statute. But LLC isn't recognized as a classification for federal tax purposes. This means that an LLC must file a tax return as a corporation, partnership, or sole proprietorship. An LLC with at least two members can choose to be classified as a corporation or as a partnership. If you choose corporation status, you must file Form 8832 (Entity Classification Election). You don't need to file Form 8832 if you're an LLC filing as a partnership. Corporations file Form 1120 (U.S. Corporation Income Tax Return). Partnerships file Form 1065 (U.S. Return of Partnership Income). Each partner's share of income, expenses, etc., is then entered on Schedule C (Profit or Loss from Businss). For more information, go to the IRS Small Business screen at. Select from the left column A-Z Index for Business to view/print the article, Limited Liability Company (LL.
https://www.answers.com/Q/If_you_have_an_LLC_and_file_chapter_7_can_they_take_your_part_of_the_LLC
CC-MAIN-2020-34
refinedweb
679
54.83
You need to sign in to do that Don't have an account? Assign Lookup Value based on Custom VF Object Picklist I have a need to create a Picklist based on a Custom Object, then based on the selection in the Picklist, update a Lookup Relationship field (Lookup__c). I have the Picklist code and the Visualforce page, but I cannot figure out how to update the Lookup field. The requirement is to update the Lookup field with the Id of the selection of the Picklist. Below are my code, can anyone help? Class public class enrollSave{ String mpi; public String getCoa() { return this.mpi; } public void setCoa(String s) { this.mpi = s; } public List<SelectOption> getCoas() { List<SelectOption> optionList = new List<SelectOption>(); optionList.add(new SelectOption('','- None -')); for (Custom_Object_A__c coa : [SELECT Name FROM Custom_Object_A__c ORDER BY Name]){ optionList.add(new SelectOption(coa.id,coa.Name)); } return optionList; } ApexPages.StandardController controller; public enrollSave(ApexPages.StandardController con){ controller = con; } public PageReference save() { controller.save(); return page.aeskenrollconfirm; } } Visualforce <apex:page <apex:form > <apex:pageBlock > <apex:pageblockSectionItem > <apex:outputLabel <apex:selectList <apex:selectOptions </apex:selectList> </apex:pageblockSectionItem> <apex:pageblockSectionItem > <apex:inputField </apex:pageblockSectionItem> </apex:pageBlockSection> <apex:pageblockButtons <apex:commandButton </apex:pageblockButtons> </apex:pageBlock> </apex:form> </apex:page> can you just include the Lookup field in the VF page? Why the "detour" via a picklist? Also, if you do not include the Lookup field in the VF page, t will not be included in the standardController query, which means the field will not be available for update. You would have to query it in your extension 1. You don't have a handle to the instance of the Custom_Object_A__c record that the page is dealing with. So if you define, in the constructor, a location Custom_Object_A__c instance: Custom_Object_A__c myObj = (Custom_Object_A__c)controller.getRecord(); then you will have a handle on that record an you can set: myObj.Lookup__c to the id you get back. Then the control.save() will save the myObj record with the new Lookup__c value. Hope it helps, Best, Steve. p.s. A Tip, in your getcoas code, first check to see if your OptionList is empty before you rebuild it. It doesn't look like you're trying to do anything dynamic in the query, so there's no reason to rebuild it every time you go back to the page. p.p.s. Instead of having a pageBlockSection on your page with non-rendered content (which might mess up your formatting), you could just do: <apex:outputPanel {!Lookup__c} </apex:outputPanel> Also, I am creating a new record and trying to set the Lookup by using the Picklist. I do not want the User to use the Lookup as I only want certain records available. Well, I would change this line: into public SafeKey_Enrollment__c skEnroll; and add skEnroll = (SafeKey_Enrollment__c)controller.getRecord(); after the controller=con; line in the constructor. Then change this line: myObj.Lookup = coa.id; to skEnrol.Lookup__c = coa.id; (Although I don't see where you're defining coa, perhaps you mean " ... = getCoa()", or " .... = mpi" ?) I totally agree with your recommendations, but the item I cannot seem to get to work is where the controller knows which selection the User has picked and then populating the Id of that selection to the Lookup field. I've looked all over and cannot find any examples of this. Forgive me for all the questions...as you can tell, I'm a beginner. Well, you have this code: which defines a String, and the public getters and setters. I might instead just do: public String coa {get; set;} and you have the Value parameter on the SelectList tag set as: <apex:selectlist So, when the user selects one of the selectOptions below, the Value of the selected one will be placed by the controller via the setcoa() call. Note that your controller isn't going to see that until you trigger some action which brings you back to the controller. I suggest you become familiar with the System.debug() call and use the Debug Logs or the System Log to start looking at what your controller is doing. For example, what are you getting in the "mpi" variable now when the user hits save. You should also throw try/catch blocks around your code in case something you're doing throws an exception. Best, Steve.
https://developer.salesforce.com/forums/?id=906F0000000963IIAQ
CC-MAIN-2022-40
refinedweb
725
56.66
need help writing a bowling program?hey guys i have instructions on writing this bowling program but i dont know where to start. Give... Help writing a date calculating code for existing codeHello guys, I have created a code for the following: How many days until my next birthday? Howeve... help making a loop to reiterate menu choices?where exactly would i put that loop? can you guys input it for me, please? help making a loop to reiterate menu choices?thank you so much!! help making a loop to reiterate menu choices?[code]#include <iostream> #include <string> #include <stdio.h> #define PI 3.141 using namespace std;... This user does not accept Private Messages
http://www.cplusplus.com/user/cocacola/
CC-MAIN-2014-42
refinedweb
115
71.51
Dave Leskovec <dlesko linux vnet ibm com> wrote: ... >>> +#ifndef _SIGNAL_H >>> +#include <signal.h> >>> +#endif >> >> In practice it's fine to include <signal.h> unconditionally, >> and even multiple times. Have you encountered a version of <signal.h> >> that may not be included twice? If so, it probably deserves a comment >> with the details. > > No, I don't have any special condition here. This is probably some past > conditioning resurfacing briefly. If I remember correctly, it had more to do > with compile efficiency rather than avoiding compile failures from multiple > inclusions. Then don't bother. gcc performs a handy optimization whereby it doesn't even open the header file the second (and subsequent) time it's included, as long as it's entire contents is wrapped in the usual sort of guard: #ifndef SYM #define SYM ... #endif
https://www.redhat.com/archives/libvir-list/2008-May/msg00020.html
CC-MAIN-2015-22
refinedweb
135
60.82
Test Driven Development with pytest Introduction. - Automated Testing - The pytest Module - What is Test-Driven Development? - Why use TDD to Create Applications? - Code Coverage - Unit Test vs Integration Tests - Basic Example: Calculating the Sum of Prime Numbers - Advanced Example: Writing an Inventory Manager - Conclusion Automated Testing Developers usually write code, compile it if necessary, and then run the code to see if it works. This is an example of manual testing. In this method we explore what features of the program work. If you would like to be thorough with your testing, you'll have to remember how to test the various outcomes of each feature. What if a new developer began to add features to the project, would you have to learn their features to test it as well? New features sometimes affect older features, are you going to manually check that all previous features still function when you added a new one? Manual testing can give us a quick boost in confidence to continue development. However, as our application grows it becomes exponentially harder and tedious to continuously test our code base manually. Automated testing shifts the burden of testing the code ourselves and keep tracking of the results, to maintaining scripts that do it for us. The scripts run modules of the code with inputs defined by the developer and compares the output with the expectations defined by the developer. The pytest Module Python's Standard Library comes with an automated testing framework - the unittest library. While the unittest library is feature-rich and effective at its task, we'll be using pytest as our weapon of choice in this article. Most developers find pytest easier to use than unittest. One simple reason is that pytest only requires functions to write tests, whereas the unittest module requires classes. For many new developers, requiring classes for tests can be a bit off-putting. pytest also includes many other features that we'll use later in this tutorial which are not present in the unittest module. What is Test-Driven Development? Test-Driven Development is a simple software development practice that instructs you or a team of coders to follow these tree steps to create software: - Write a test for a feature that fails - Write code to make the test pass - Refactor the code as needed This process is commonly referred to as the Red-Green-Refactor cycle: - You write an automated test for how the new code should behave and see it fail - Red - Write code in the application until your test passes - Green - Refactor the code to make it readable and efficient. There's no need to be worried that your refactoring will break the new feature, you simply need to rerun the test and ensure it passes. A feature is complete when we no longer need to write code for its tests to pass. Why use TDD to Create Applications? The common complaint of using TDD is that it takes too much time. As you become more efficient with writing tests, the time required by you to maintain them decreases. Furthermore, TDD provides the following benefits, which you can find worth the time tradeoff: - Writing tests require that you know the inputs and output to make the feature work - TDD forces us to think about the application interface before we start coding. - Increased confidence in codebase - By having automated tests for all features, developers feel more confident when developing new features. It becomes trivial to test the entire system to see if new changes broke what existed before. - TDD does not eliminate all bugs, but the likelihood of encountering them are lower - When trying to fix a bug, you can write a test for it to ensure it's fixed when done coding. - Tests can be used as further documentation. As we write the inputs and outputs of a feature, a developer can look at the test and see how the code's interface is meant to be used. Code Coverage Code coverage is a metric that measures the amount of source code that's covered by your test plan. 100% code coverage means that all the code you've written has been used by some test(s). Tools measure code coverage in many different ways, here are a few popular metrics: - Lines of code tested - How many defined functions are tested - How many branches ( ifstatements for example) are tested It's important that you know what metrics are used by your code coverage tool. As we make heavy use of pytest, we'll use the popular pytest-cov plugin to get code coverage. High code coverage does not mean that your application will have no bugs. It's more than likely that the code has not been tested for every possible scenario. Unit Test vs Integration Tests Unit tests are used to ensure an individual module behaves as expected, whereas integration tests ensure that a collection of modules interoperate as we expect them too. As we develop larger applications, we'll have to develop many components. While these individual components may each have their corresponding unit tests, we'll also want a way to ensure that these multiple components when used together fulfill our expectations. TDD requires that we begin by writing a single test that fails with the current code base, then work towards its completion. It doesn't specify that it has be a unit test, your first test can be an integration test if you'd like. When your first failing integration test is written, we can then start to develop each individual component. The integration test will fail until each component is built and passes their tests. When the integration test passes, if crafted correctly we would have met a user requirement for our system. Basic Example: Calculating the Sum of Prime Numbers The best way to understand TDD is to put it in to practice. We'll begin by writing a Python program that returns the sum of all numbers in a sequence that are prime numbers. We'll create two functions to do this, one that determines if a number is prime or not and another that adds the prime numbers from a given sequence of numbers. Create a directory called primes in a workspace of your choosing. Now add two files: primes.py, test_primes.py. The first file is where we'll write our program code, the second file is where our tests will be. pytest requires that our test files either begin with "test" or end with "test.py" (therefore, we could have also named our test file primes_test.py). Now in our primes directory, let's set up our virtual environment: $ python3 -m venv env # Create a virtual environment for our modules $ . env/bin/activate # Activate our virtual environment $ pip install --upgrade pip # Upgrade pip $ pip install pytest # Install pytest Testing the is_prime() Function A prime number is any natural number greater than 1 that is only divisible by 1 and itself. Our function should take a number and return True if it's prime and False otherwise. In our test_primes.py, let's add our first test case: def test_prime_low_number(): assert is_prime(1) == False The assert() statement is a keyword in Python (and in many other languages) that immediately throws an error if a condition fails. This keyword is useful while writing tests because it points to exactly what condition failed. If we enter 1or a number smaller than 1, then it can't be prime. Let's now run our test. Enter the following in your command line: $ pytest For verbose output you can run pytest -v. Ensure that you virtual environment is still active (you should see (env) at the beginning of the line in your terminal). You should notice output like this: def test_prime_low_number(): > assert is_prime(1) == False E NameError: name 'is_prime' is not defined test_primes.py:2: NameError ========================================================= 1 failed in 0.12 seconds ========================================================= It makes sense to get a NameError, we haven't created our function yet. This is the "red" aspect of the red-green-refactor cycle. pytest even logs failed tests in the color red if your shell is configured to show colors. Now let's add the code in our primes.py file to make this test pass: def is_prime(num): if num == 1: return False Note: It's generally good practice to keep your tests in separate files from your code. Aside from improved readability and separation of concerns as your codebase grows, it also keeps the developer of the test away from the internal workings of the code. Therefore, the tests use the application interfaces in the same way another developer would use it. Now let's run pytest once more. We should now see output like this: =========================================================== test session starts ============================================================ platform darwin -- Python 3.7.3, pytest-4.4.1, py-1.8.0, pluggy-0.9.0 rootdir: /Users/marcus/stackabuse/test-driven-development-with-pytest/primes plugins: cov-2.6.1 collected 1 item test_primes.py . [100%] ========================================================= 1 passed in 0.04 seconds ========================================================= Our first test passed! We know that 1 is not prime, but by definition 0 is not prime, nor is any negative number. We should refactor our application to reflect that and change is_prime() to: def is_prime(num): # Prime numbers must be greater than 1 if num < 2: return False If we run pytest again, our tests would still pass. Now let's add a test case for a prime number, in test_primes.py add the following after our first test case: def test_prime_prime_number(): assert is_prime(29) And let's run pytest to see this output: def test_prime_prime_number(): > assert is_prime(29) E assert None E + where None = is_prime(29) test_primes.py:9: AssertionError ============================================================= warnings summary ============================================================= test_primes.py::test_prime_prime_number /Users/marcus/stackabuse/test-driven-development-with-pytest/primes/test_primes.py:9: PytestWarning: asserting the value None, please use "assert is None" assert is_prime(29) -- Docs: ============================================== 1 failed, 1 passed, 1 warnings in 0.12 seconds ============================================== Note that the pytest command now runs the two tests we've written. The new case fails as we don't actually compute whether number is prime or not. The is_prime() function returns None as other functions do by default for any number greater than 1. The output still fails, or we see red from the output. Let's think about how we determine where a number is prime or not. The simplest method would be to loop from 2 until one less than the number, dividing the number by the current value of the iteration. To make this more efficient, we can check by dividing numbers between 2 and the square root of the number. If there's no remainder from the division, then it has a divisor that's neither 1 nor itself, and therefore not prime. If it does not find a divisor in the loop, then it must be prime. Let's update is_prime() with our new logic: import math def is_prime(num): # Prime numbers must be greater than 1 if num < 2: return False for n in range(2, math.floor(math.sqrt(num) + 1)): if num % n == 0: return False return True Now we run pytest to see if our test passes: =========================================================== test session starts ============================================================ platform darwin -- Python 3.7.3, pytest-4.4.1, py-1.8.0, pluggy-0.9.0 rootdir: /Users/marcus/stackabuse/test-driven-development-with-pytest/primes plugins: cov-2.6.1 collected 2 items test_primes.py .. [100%] ========================================================= 2 passed in 0.04 seconds ========================================================= It passes. We know that this function can get a prime number, and a low number. Let's add a test to ensure it returns False for a composite number greater than 1. In test_primes.py add the following test case below: def test_prime_composite_number(): assert is_prime(15) == False If we run pytest we'll see the following output: =========================================================== test session starts ============================================================ platform darwin -- Python 3.7.3, pytest-4.4.1, py-1.8.0, pluggy-0.9.0 rootdir: /Users/marcus/stackabuse/test-driven-development-with-pytest/primes plugins: cov-2.6.1 collected 3 items test_primes.py ... [100%] ========================================================= 3 passed in 0.04 seconds ========================================================= Testing sum_of_primes() As with is_prime(), let's think about the outcomes of this function. If the function is given an empty list, then the sum should be zero. That guarantees that our function should always return a value with valid input. After, we'll want to test that it only adds prime numbers in a list of numbers. Let's write our first failing test, add the following code at the end of test_primes.py: def test_sum_of_primes_empty_list(): assert sum_of_primes([]) == 0 If we run pytest we'll get the familiar NameError test failure, as we did not define the function yet. In our primes.py file let's add our new function that simply returns the sum of a given list: def sum_of_primes(nums): return sum(nums) Now running pytest would show that all tests pass. Our next test should ensure that only prime numbers are added. We'll mix prime and composite numbers and expect the function to only add the prime numbers: def test_sum_of_primes_mixed_list(): assert sum_of_primes([11, 15, 17, 18, 20, 100]) == 28 The prime numbers in the list we are testing are 11 and 17, which add up to 28. Running pytest to validate that the new test fails. Now let's modify our sum_of_primes() so that only prime numbers are added. We'll filter the prime numbers with a List Comprehension: def sum_of_primes(nums): return sum([x for x in nums if is_prime(x)]) As is routine, we run pytest to verify we fixed the failing test - everything passes. Once complete, let's check our code coverage: $ pytest --cov=primes For this package, our code coverage is 100%! If it wasn't, we can spend some time adding a few more tests to our code to ensure that our test plan is thorough. For example, if our is_prime() function was given a float value, would it throw an error? Our is_prime() method does not enforce the rule that a prime number must be a natural number, it only checks that it's greater than 1. Even though we have total code coverage, the feature being implemented may not work correctly in all situations. Advanced Example: Writing an Inventory Manager Now that we grasped the basics of TDD, let's dive deeper into some useful features of pytest which enable us to become more efficient at writing tests. Just like before in our basic example, inventory.py, and a test file, test_inventory.py, will be our main two files. Features and Test Planning A clothing and footwear store would like to move management of their items from paper to a new computer the owner bought. While the owner would like many features, she's content with software that could perform the following upcoming tasks immediately. - Record the 10 new Nike sneakers that she recently bought. Each is worth $50.00. - Add 5 more Adidas sweatpants that cost $70.00 each. - She's expecting a customer to buy 2 of the Nike sneakers - She's expecting another customer to buy 1 of the sweatpants. We can use these requirements to create our first integration test. Before we get to writing it, let's flesh out the smaller components a bit to figure out what would be our inputs and output, function signatures and other system design elements. Each item of stock will have a name, price and quantity. We'll be able to add new items, add stock to existing items and of course remove stock. When we instantiate an Inventory object, we'll want the user to provide a limit. The limit will have a default value of 100. Our first test would be to check the limit when instantiating an object. To ensure that we don't go over our limit, we'll need to keep track of the total_items counter. When initialized, this should be 0. We'll need to add 10 Nike sneakers and the 5 Adidas sweatpants to the system. We can create an add_new_stock() method that accepts a name, price, and quantity. We should test that we can add an item to our inventory object. We should not be able to add an item with a negative quantity, the method should raise an exception. We also should not be able to add any more items if we're at the our limit, that should also raise an exception. Customers will be buying these items soon after entry, so we'll need a remove_stock() method as well. This function would need the name of the stock and the quantity of items being removed. If the quantity being removed is negative or if it makes the total quantity for the stock below 0, then the method should raise an exception. Additionally, if the name provided is not found in our inventory, the method should raise an exception. First Tests Preparing to do our tests first has helped us design our system. Let's start by creating our first integration test: def test_buy_and_sell_nikes_adidas(): # Create inventory object inventory = Inventory() assert inventory.limit == 100 assert inventory.total_items == 0 # Add the new Nike sneakers inventory.add_new_stock('Nike Sneakers', 50.00, 10) assert inventory.total_items == 10 # Add the new Adidas sweatpants inventory.add_new_stock('Adidas Sweatpants', 70.00, 5) assert inventory.total_items == 15 # Remove 2 sneakers to sell to the first customer inventory.remove_stock('Nike Sneakers', 2) assert inventory.total_items == 13 # Remove 1 sweatpants to sell to the next customer inventory.remove_stock('Adidas Sweatpants', 1) assert inventory.total_items == 12 At every action we do an assertion on the state of the inventory. It's best to assert after an action is done, so when you're debugging you'll know the last step that was taken. Run pytest and it should fail with a NameError as no Inventory class is defined. Let's create our Inventory class, with a limit parameter that defaults to 100, starting with the unit tests: def test_default_inventory(): """Test that the default limit is 100""" inventory = Inventory() assert inventory.limit == 100 assert inventory.total_items == 0 And now, the class itself: class Inventory: def __init__(self, limit=100): self.limit = limit self.total_items = 0 Before we move on to the methods, we want to be sure that our object can be initialized with a custom limit, and it should be set correctly: def test_custom_inventory_limit(): """Test that we can set a custom limit""" inventory = Inventory(limit=25) assert inventory.limit == 25 assert inventory.total_items == 0 The integration continues to fail but this test passes. Fixtures Our first two tests required us to instantiate an Inventory object before we could begin. More than likely we'll have to do the same for all future tests. This is bit repetitious. We can use fixtures to help solve this problem. A fixture is a known and fixed state that tests are run against to ensure that results are repeatable. It's good practice for tests to run in isolation of each other. The results of one test case shouldn't affect the results of another test case. Let's create our first fixture, an Inventory object with no stock. test_inventory.py: import pytest @pytest.fixture def no_stock_inventory(): """Returns an empty inventory that can store 10 items""" return Inventory(10) Note the use of the pytest.fixture decorator. For testing purposes we can reduce the inventory limit to 10. Let's use this fixture to add a test for the add_new_stock() method: def test_add_new_stock_success(no_stock_inventory): no_stock_inventory.add_new_stock('Test Jacket', 10.00, 5) assert no_stock_inventory.total_items == 5 assert no_stock_inventory.stocks['Test Jacket']['price'] == 10.00 assert no_stock_inventory.stocks['Test Jacket']['quantity'] == 5 Observe that the name of the function is the argument of the test, they must be the same name for the fixture to be applied. Otherwise, you'd use it like a regular object. To ensure that the stock was added we have to test a bit more than the total items stored so far. Writing this test has forced us to consider how we display a stock's price and remaining quantity. Run pytest to observe that there are now 2 failures and 2 passes. We'll now add the add_new_stock() method: class Inventory: def __init__(self, limit=100): self.limit = limit self.total_items = 0 self.stocks = {} def add_new_stock(self, name, price, quantity): self.stocks[name] = { 'price': price, 'quantity': quantity } self.total_items += quantity You'll notice that a stocks object was initialized in the __init__ function. Again, run pytest to confirm that the test passed. Parametrizing Tests We mentioned earlier that the add_new_stock() method does input validation - we raise an exception if the quantity is zero or negative, or if it carries us over our inventory's limit. We can easily add more test cases, using try/except to catch each exception. This also feels repetitious. Pytest provides parametrized functions that allows us to test multiple scenarios using one function. Let's write a parametrized test function to ensure our input validation works: @pytest.mark.parametrize('name,price,quantity,exception', [ ('Test Jacket', 10.00, 0, InvalidQuantityException( 'Cannot add a quantity of 0. All new stocks must have at least 1 item')) ]) def test_add_new_stock_bad_input(name, price, quantity, exception): inventory = Inventory(10) try: inventory.add_new_stock(name, price, quantity) except InvalidQuantityException as inst: # First ensure the exception is of the right type assert isinstance(inst, type(exception)) # Ensure that exceptions have the same message assert inst.args == exception.args else: pytest.fail("Expected error but found none") This test tries to add a stock, gets the exception and then checks that it's the right exception. If we don't get an exception, fail the test. The else clause is very important in this scenario. Without it, an exception that wasn't thrown would count as a pass. Our test would therefore have a false positive. We use pytest decorators to add a parameter to the function. The first argument contains a string of all the parameter names. The second argument is a list of tuples where each tuple is a test case. Run pytest to see our test fail as InvalidQuantityException is not defined. Back in inventory.py let's create a new exception above the Inventory class: class InvalidQuantityException(Exception): pass And change the add_new_stock() method: def add_new_stock(self, name, price, quantity): if quantity <= 0: raise InvalidQuantityException( 'Cannot add a quantity of {}. All new stocks must have at least 1 item'.format(quantity)) self.stocks[name] = { 'price': price, 'quantity': quantity } self.total_items += quantity Run pytest to see that our most recent test now passes. Now let's add the second error test case, an exception is raised if our inventory can't store it. Change the test as follows: ')) ]) def test_add_new_stock_bad_input(name, price, quantity, exception): inventory = Inventory(10) try:") Instead of creating a whole new function, we modify this one slightly to pick up our new exception and add another tuple to the decorator! Now two tests are executed on a single function. Parametrized functions cut down on the time it takes to add new test cases. In inventory.py, we'll first add our new exception below InvalidQuantityException: class NoSpaceException(Exception): pass And change the add_new_stock() method: def add_new_stock(self, name, price, quantity): if quantity <= 0: raise InvalidQuantityException( 'Cannot add a quantity of {}. All new stocks must have at least 1 item'.format(quantity)) if self.total_items + quantity > self.limit: remaining_space = self.limit - self.total_items raise NoSpaceException( 'Cannot add these {} items. Only {} more items can be stored'.format(quantity, remaining_space)) self.stocks[name] = { 'price': price, 'quantity': quantity } self.total_items += quantity Run pytest to see that your new test case passes as well. We can use fixtures with our parametrized function. Let's refactor our test to use the empty inventory fixture: def test_add_new_stock_bad_input") Like before, it's just another argument that uses the name of a function. The key thing is to exclude it in the parametrize decorator. Looking at the code some more, there's no reason why there needs to be two methods to get adding new stocks. We can test errors and success in one function. test_add_new_stock_bad_input() and test_add_new_stock_success() and let's add a new function: ')), ('Test Jacket', 10.00, 5, None) ]) def test_add_new_stock: assert no_stock_inventory.total_items == quantity assert no_stock_inventory.stocks[name]['price'] == price assert no_stock_inventory.stocks[name]['quantity'] == quantity This one test function first checks for known exceptions, if none are found then we ensure the addition matches our expectations. The separate test_add_new_stock_success() function is now just executed via a tupled parameter. As we don't expect an exception to be thrown in the successful case, we specify None as our exception. Wrapping up our Inventory Manager With our more advanced pytest usage, we can quickly develop the remove_stock function with TDD. In inventory_test.py: # The import statement needs one more exception from inventory import Inventory, InvalidQuantityException, NoSpaceException, ItemNotFoundException # ... # Add a new fixture that contains stocks by default # This makes writing tests easier for our remove function @pytest.fixture def ten_stock_inventory(): """Returns an inventory with some test stock items""" inventory = Inventory(20) inventory.add_new_stock('Puma Test', 100.00, 8) inventory.add_new_stock('Reebok Test', 25.50, 2) return inventory # ... # Note the extra parameters, we need to set our expectation of # what totals should be after our remove action @pytest.mark.parametrize('name,quantity,exception,new_quantity,new_total', [ ('Puma Test', 0, InvalidQuantityException( 'Cannot remove a quantity of 0. Must remove at least 1 item'), 0, 0), ('Not Here', 5, ItemNotFoundException( 'Could not find Not Here in our stocks. Cannot remove non-existing stock'), 0, 0), ('Puma Test', 25, InvalidQuantityException( 'Cannot remove these 25 items. Only 8 items are in stock'), 0, 0), ('Puma Test', 5, None, 3, 5) ]) def test_remove_stock(ten_stock_inventory, name, quantity, exception, new_quantity, new_total): try: ten_stock_inventory.remove_stock(name, quantity) except (InvalidQuantityException, NoSpaceException, ItemNotFoundException) as inst: assert isinstance(inst, type(exception)) assert inst.args == exception.args else: assert ten_stock_inventory.stocks[name]['quantity'] == new_quantity assert ten_stock_inventory.total_items == new_total And in our inventory.py file first we create the new exception for when users try to modify a stock that doesn't exist: class ItemNotFoundException(Exception): pass And then we add this method to our Inventory class: def remove_stock(self, name, quantity): if quantity <= 0: raise InvalidQuantityException( 'Cannot remove a quantity of {}. Must remove at least 1 item'.format(quantity)) if name not in self.stocks: raise ItemNotFoundException( 'Could not find {} in our stocks. Cannot remove non-existing stock'.format(name)) if self.stocks[name]['quantity'] - quantity <= 0: raise InvalidQuantityException( 'Cannot remove these {} items. Only {} items are in stock'.format( quantity, self.stocks[name]['quantity'])) self.stocks[name]['quantity'] -= quantity self.total_items -= quantity When you run pytest you should see that the integration test and all others pass! Conclusion Test-Driven Development is a software development process where tests are used to guide a system's design. TDD mandates that for every feature we have to implement we write a test that fails, add the least amount of code to make the test pass, and finally refactor that code to be cleaner. To make this process possible and efficient, we leveraged pytest - an automated test tool. With pytest we can script tests, saving us time from having to manually test our code every change. Unit tests are used to ensure an individual module behaves as expected, whereas integration tests ensure that a collection of module interoperate as we expect them too. Both the pytest tool and the TDD methodology allow for both test types to be used, and developers are encouraged to use both. With TDD, we are forced to think about inputs and outputs of our system and therefore it's overall design. Writing tests provides additional benefits like increased confidence in our program's functionality after changes. TDD mandates a heavily iterative process that can be efficient by leveraging an automated test suite like pytest. With features like fixtures and parametrized functions, we are able to quickly write test cases as needed by our requirements.
https://www.codevelop.art/test-driven-development-with-pytest.html
CC-MAIN-2022-40
refinedweb
4,663
56.55
Log in to like this post! How to Enable CORS in the ASP.NET Web API Dhananjay Kumar / Monday, August 31, 2015 Have you ever come across the following error: “Cross-Origin Request Blocked. The same origin policy disallows reading the resource”. Us too!: 1. Scheme (HTTP) 2. Host (server) 3.: 1. Requested URL or URL of the server 2.: In the HTML document, we are using an XMLHttpRequest object to make the HTTP call. As it is evident that URI of Web API (URI of the resource requested) and the HTML document (URL from which the request originated) are not the same hence XMLHttpRequest object is blocking the resource sharing since they are not of the same origin. Very likely in the browser we will get the exception as shown in the image below: Let us dig further into the bug. In the browser, open the developer tool and the network tab. You will find Origin and Host in Request Header as shown in the image below. It is clear that both are not the same, and CORS is not allowed by the user agent XMLHttpRequest. If you look at the Response Header there would be no information about Access-Control-Allow-Origin. Since the server does not send a response about which origin can access the resource in the header, XMLHttpRequest object blocks the resource sharing in the browser. Let us go ahead and enable the CORS support for the Web API. Enabling CORS in ASP.NET Web API To enable CORS in ASP.NET Web API 2.0, first, you need to add the Microsoft.AspNet.WebApi.Cors package to the project. Either you can choose the command prompt to install the package or NuGet manager to search and install as shown in the image below: You can configure CORS support for the Web API at three levels: 1. At the Global level 2. At the Controller level 3. At the Action level To configure CORS support at the global level, first, install the CORS package and then open WebApiConfig.cs file from App_Start folder. var cors = new EnableCorsAttribute("", "*", "*"); config.EnableCors(cors); After enabling CORS at the global level, again host the Web API and examine the request and response header. Also, notice that in the Enable CORS attribute we have set the Origin URL to the URL of the JavaScript App. The Web API server is adding an extra header Access-Control-Allow-Origin in the response header as shown in the image below. The URL in the Access-Control-Allow-Origin header in the response header and the URL in the Origin header in the request header must be same then only XMLHttpRequest will allow the CORS operations. In some cases, the value of the Access-Control-Allow-Origin response header will be set to a wildcard character*. This means the server allows CORS support for all the origins instead of a particular origin. We have enabled the CORS support on the server, so we should not get the exception and data should be fetched in the browser. As we discussed earlier, in the ASP.NET Web API, CORS support can be enabled at three different levels: 1. At the Action level 2. At the Controller level 3. At the Global level Enable CORS at the Action level CORS support can be enabled at the action level as shown in the listing below: [EnableCors(origins: "", headers: "*", methods: "*")] public HttpResponseMessage GetItem(int id) { // Code here } In the above code listing, we have enabled CORS for the GetItem action. Also, we are setting parameters to allow all the headers and support all the HTTP methods by setting the value to star. Enable CORS at the Controller level CORS support can be enabled at the controller level as shown in the listing below: [EnableCors(origins: "", headers: "*", methods: "*")] public class ClassesController : ApiController { In the above code listing, we have enabled CORS for the Classes Controller. We are also setting parameters to allow all the headers and support all the HTTP methods by setting the value to star. We can exclude one of the actions from CORS support using the [DisableCors] attribute. Enable CORS at the Global level To configure CORS support at the global level, first install the CORS package and then open the WebApiConfig.cs file from App_Start folder. var cors = new EnableCorsAttribute("", "*", "*"); config.EnableCors(cors); If you set the attribute in more than one scope, the order of precedence is as follows: Attributes of EnableCors There are three attributes to pass to EnableCors: 1. Origins: You can set more than one origins value separated by commas. If you want any origin to make AJAX request to the API then set origin value to wildcard value star. 2. Request Headers: The Request header parameter specifies which Request headers are allowed. To allow any header set value to * 3. HTTP Methods: The methods parameter specifies which HTTP methods are allowed to access the resource. To allow all methods, use the wildcard value “*”. Otherwise set comma separated method name to allow set of methods to access the resources. Putting that all together, you can enable CORS for two origins, for all the headers, and then post and get operations as shown in the listing below: [EnableCors(origins: "", headers: "*", methods: "post,get")] public class ClassesController : ApiController { Optionally you can also pass credentials to the Web API and create a custom policy, but I hope you found this post about the basics of CORS in the ASP.NET Web API. Have something to add? Share your comments below!
https://www.infragistics.com/community/blogs/b/dhananjay_kumar/posts/how-to-enable-cors-in-the-asp-net-web-api
CC-MAIN-2022-40
refinedweb
926
64.3
plpydbapi 0.20121018 DB-API compatible interface on top of PL/Pythonplpydbapi ========= This module provides a (sort of) Python DB-API 2.0 compatible interface on top of PL/Python. About DB-API: <http:"" dev="" peps="" pep- About PL/Python: <http:"" docs="" current="" static="" plpython. Installation ------------ plpydbapi supports Python 2.6 and later, including Python 3.x, and requires PostgreSQL 9.1 or later. Using `cursor.description` requires PostgreSQL 9.2. Just install it like any setuptools-enabled Python module, for example python setup.py install or use easy_install. Make sure you use the Python version that your installation of PL/Python was built against. Using ----- Here is an example how to use it: import plpydbapi dbconn = plpydbapi.connect() cursor = dbconn.cursor() cursor.execute("SELECT ... FROM ...") for row in cursor.fetchall(): plpy.notice("got row %s" % row) dbconn.close() Test suite ---------- []() There is a test suite in the test/ subdirectory. It uses the DB-API compliance test framework from <https: launchpad.. So first fetch, er, clone, er, branch yourself a copy of that bzr branch lp:dbapi-compliance into the current directory. If you have [mr]() just run `mr up`. If you are using Python 2.6, you also need the unittest2 package; with Python 2.7 and later, the unittest module in the standard library is enough. Then run python setup.py test This will run the unittest suite inside the PostgreSQL server, forwarding the output for the client to see. If you have a complicated setup, such as multiple PostgreSQL versions or nonstandard ports, use libpq environment variables such as PGHOST and PGPORT to point the test suite driver to an instance it can use. You can also look into the files setup.py and test/run_test_plpydbapi_dbapi20.sql for some additional ways to tweak the process. - Author: Peter Eisentraut - Categories - Package Index Owner: petere - DOAP record: plpydbapi-0.20121018.xml
https://pypi.python.org/pypi/plpydbapi/0.20121018
CC-MAIN-2018-13
refinedweb
312
61.83
go to bug id or search bugs for Description: ------------ Traits, when used in a class, are not added to class' type, and therefore can not be use in type hints. The RFCs on traits and on horizontal reuse do not explain if this is by design. On the other hand Traits seem to share the same namespace as Classes and Interfaces, since it is impossible to have an Interface and a Trait that share the name ('Fatal error: Cannot redeclare class' is raised when this is attempted). Test script: --------------- <?php trait SomeTrait {} class SomeClass { use SomeTrait; } $a = new SomeClass(); var_dump(is_a($a,'SomeTrait')); Expected result: ---------------- bool(true) Actual result: -------------- bool(false) Add a Patch Add a Pull Request I believe this is the correct result as $a is not an instance of the trait but rather of the class that utilizes the trait. Mike: That's one way of looking at it. My point of view is that a trait adds methods to class' interface (where interface is a set of public members of a class - both methods and fields) and this should be reflected in class type. Currently (unless I missed something that was not mentioned in RFC - I admit to not have gone through SVN version of docs) there seem to be no way to check if class uses a trait or no. Only new functions mentioned are trait_exists() and get_declared_traits(). Checking if the object has a method will not work, if trait is meant to override method in host class. Having traits reflected in object's type, would solve this problem nicely. Adding another function to glabal namespace (uses_trait() ?) is not something I would like to see. > $a is not an instance of the trait but rather of > the class that utilizes the trait. You can say the same of interfaces and abstracts, but is_a returns true for them. Test script: --------------- trait someTrait {} interface someInterface {} abstract class someAbstract {} class someClass extends someAbstract implements someInterface { use someTrait; } $a = new someClass(); var_dump(is_a($a, 'someClass')); var_dump(is_a($a, 'someAbstract')); var_dump(is_a($a, 'someInterface')); var_dump(is_a($a, 'someTrait')); Expected result: ---------------- bool(true) bool(true) bool(true) bool(?) Actual result: ---------------- bool(true) bool(true) bool(true) bool(false) My view on this issue is that traits do not constitute types and do not provide interfaces. (I proposed the later one in the beginning in the sense of traits are interfaces with implementation, but this was disregarded to make clear that traits are neither classes nor interfaces.) Thus, is_a should also not say anything about a trait. Traits are not units of encapsulation, they do not guarantee to provide/protect any invariants. However, if you need to know what traits are used by a class, please refer to: ReflectionClass::getTraits() I just noticed that we have the following function in the SPL: That should probably be mirrored to provide the same functionality as ReflectionClass::getTraits(). Not sure what the design policies are here. From a symmetry perspective there should be a class_uses() function, but from my personal perspective, class_implements should get nuked and uses should transition to the reflection extension if they need such meta programming facilities. Well, the later is not practical, so we will probably need to have class_uses(). Automatic comment from SVN on behalf of gron Revision: Log: Added missing class_uses(..) function to SPL to mirror class_implements(..). # Was pointed out as missing in bug #55266. Added class_uses(..) in SPL to mirror existing class_implements(..) per This bug has been fixed in SVN. Snapshots of the sources are packaged every three hours; this change will be in the next snapshot. You can grab the snapshot at. Thank you for the report, and for helping us make PHP better.
https://bugs.php.net/bug.php?id=55266
CC-MAIN-2016-50
refinedweb
617
69.01
Upgrading a BIS geodatabase connection (Bathymetry Solution) If you currently use the 10.1 release of ArcGIS for Maritime:Bathymetry and have not installed the 10.1 Service Pack 1 release, you need to upgrade your existing BIS geodatabase connections after installing 10.2.1. This upgrade process updates the BIS geodatabase schema to enable the new mosaic dataset naming functionality for composite surface models, provide support for additional raster formats other than the BAG format, and parse and display metadata for release 1.5 BAGs. In the previous release of 深海探测学解决方案, when you saved a composite surface model through the Compose Surface window and chose to create a mosaic dataset with your model, the name of the mosaic dataset was generated for you. After the upgrade process, you can define your own name for the mosaic dataset when saving a composite surface model. This allows you to set your own naming conventions when the mosaic dataset is to be shared publicly or used as an image service, or privately within your organization. Similarly, in the previous release of 深海探测学解决方案, you were only able to add BAGs to your BIS. After the upgrade process, you can now add other common raster formats to the BIS, such as GeoTIFF, Esri Grid, and ASCII Grid, as well as many other Esri-supported raster formats. Due to different namespaces used in the internal metadata XML of BAGs 1.5 and later, earlier releases of 深海探测学解决方案 did not support displaying, filtering, or sorting by a BAG’s internal metadata attributes. Following the upgrade to the latest BIS geodatabase schema, this will now be possible. Chances are you have active connections to your BIS geodatabases from a previous release. If this is the case, when you start ArcMap and open the Manage Connections dialog box, you will immediately be prompted to run the upgrade process. If you don’t have an active connection, you need to connect to and activate the BIS workspace connection you want to upgrade. Any release of the software that requires an upgrade to the BIS ensures that all upgrades in previous releases are included. Additionally, when an existing BIS workspace is upgraded, it ensures that the upgraded BIS workspace uses the same schema definition as a newly created BIS at that software release. - Start ArcMap. - On the main menu, click Customize > Toolbars > Bathymetry. - Click the Manage Connections button on the Bathymetry toolbar. The Manage Connections dialog box appears. - Check the Active check box for the BIS workspace you want to upgrade. The following message appears. - Click OK to return to the Manage Connections dialog box. - Click the icon next to the BIS you want to upgrade. The following error message appears and notifies you that the workspace is out of date and asks whether you would like to upgrade. - Click Yes. The Manage Connections dialog box appears with an upgrade message. - Read the instructions listed. 提示: If you are not ready to upgrade your BIS workspace at this time, click Cancel Upgrade and perform the steps necessary to prepare for the upgrade. - Click OK. The Upgrading BIS workspace status dialog box appears. 警告: If you have modified your ONSBagInternalMetadataDef.xml file, pay close attention to note the warning message that appears as well as how to manually correct the change to the XML file. An example warning message is as follows: Warning: The ONSInternalMetadataConfig.xml file was updated to support v1.5 of the BAG schema, but the field(s): <your field> were not able to be updated. These fields will need to be updated according to information outlined in the help topic titled Internal BAG metadata XML schema. 注: For ArcSDE workspaces, if there are open connections to the BIS workspace and you attempt to run the process, it will fail and roll back to the previous release. - Click Close when the process completes. If your only active connection is to an older release of the BIS geodatabase, the error dialog box from step 6 appears and you can skip to step 7. All BIS users need to have the latest 深海探测学解决方案 release installed before they can access the upgraded BIS geodatabase. For ArcSDE workspaces, you need to close and start ArcMap before you can use the upgraded BIS geodatabase.
https://resources.arcgis.com/zh-cn/help/main/10.2/0203/02030000002q000000.htm
CC-MAIN-2022-27
refinedweb
711
62.27