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
#include <Marshal.hpp> List of all members. Marshalis a data packer for sending and receiving parallel messages. The data put-to (<<) is appended to the stream as a string of bytes, likewise data gotten-from (>>) is extracted from the stream into the object as a string of bytes. The write() and read() functions perform the data movements to and from the packed stream. The common implementation is the create a << and >> operator for an object which properly appends and extracts the object's members. The object can put-to and get-from it's typeid() to add type checking. This operation ensures that the data types being read was the data type written before the data is extracted. This type checking can be disabled since it may be desired to put-to an object of one type, but get-from into an object of an extractable but different type. The TYPE_CHECK bit masks can be provided at put-to Marshal construction to activate the type checking. The Marshaller send the type check code as the first message to allow the get-from to initialize properly. The put-to operator and get-from operators for plain old data, std::string, std::vector and std::list have been implemented. Additional ones could be added here, or left to the developer using the marshaller. The stream and type_check members were left as public due to the extensive use. If this proves bothersome, getter/setter methods could be introduced. Definition at line 49 of file Marshal.hpp. Creates a new Marshal instance for get-from operations. Definition at line 162 of file Marshal.cpp. Member function str returns the string of packed bytes created by put-to operations to the stream. std::stringcreated from the packed byte stream. Definition at line 172 of file Marshal.cpp. Member function size returns the byte count of the string of packed bytes creates by put-to operations to the stream. size_tin bytes of the packed byte stream. Definition at line 179 of file Marshal.cpp. Member function write writer bytes to the packed byte stream. Definition at line 192 of file Marshal.cpp. Member function read reads bytes from the packed byte stream. Definition at line 201 of file Marshal.cpp. Member function operator void * returns the state of the packed byte stream. voidconst pointer which is non-zero if status is good. Definition at line 185 of file Marshal.cpp.
http://trilinos.sandia.gov/packages/docs/r10.2/packages/stk/doc/html/structstk_1_1Marshal.html
CC-MAIN-2014-35
refinedweb
404
67.25
public class Bucket extends Object implements Serializable Represents an Amazon S3 bucket.: There are no limits to the number of objects that can be stored in a bucket. Performance does not vary based on the number of buckets used. Store all objects within a single bucket or organize them across several buckets. equals, getClass, hashCode, notify, notifyAll, wait, wait, wait public Bucket() Bucket(String) public Bucket(String name) name- The name for the bucket. Bucket() public String toString() toStringin class Object Object.toString() public Owner getOwner() nullif the bucket's owner is unknown. nullif it is unknown. setOwner(Owner) public void setOwner(Owner owner) owner- The bucket's owner. getOwner() public Date getCreationDate() nullif the creation date is not known. nullif not known. public void setCreationDate(Date creationDate) creationDate- The bucket's creation date. public String getName() setName(String) public void setName(String name) name- The name for the bucket.
https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/s3/model/Bucket.html
CC-MAIN-2021-04
refinedweb
150
52.15
Component. Why you should choose ComponentOne's PDFDocumentSource and FlexViewer - Load and view PDFs easily. You can load the PDF into the viewer at design time without any code and view your PDF at run time. If you want to do this in the code-behind instead, you only need to write a few lines of code. - There's no dependency on Adobe Reader on your system. - These are supported across platforms: the same lines of code will work on WinForms, WPF, and UWP with minimal differences — which can be specific to each platform. - Read, view, export, and print PDFs in .NET applications without any external dependencies. - They supports many PDF and Viewer features: - Support for embedded fonts (with minor limitations for CFF fonts). - Text search and selection in FlexViewer,. - Navigate using outlines and hyperlinks in FlexViewer. Different Use Cases Where These Components Help You might need to work with PDFs in .NET applications in various situations. The following lists are some of the use cases where you might need a PDF component and a viewer. Please note that all these examples are supported across WinForms, WPF, and UWP platforms with minimal code differences. Please visit the respective documentation for more help. In the following examples, make sure you have the following DLLs in your respective platform applications: WinForms: - C1.Win.4 - C1.Win.C1Document - C1.Win.Barcode.4 - C1.Win.Chart.FlexChart.4 - C1.Win.FlexViewer.4 - C1.Win.ImportServices.4 - C1.Win.Bitmap.4 - C1.Win.C1DX.4 - C1.C1Excel.4 - C1.C1Pdf.4 - C1.C1Word.4 - C1.C1Zip.4 WPF: - C1.WPF.4 - C1.WPF.Document.4 - C1.WPF.FlexViewer.4 - C1.WPF.BarCode.4 - C1.WPF.Bitmap.4 - C1.WPF.DX.4 - C1.WPF.Excel.4 - C1.WPF.FlexChart.4 - C1.WPF.ImportServices.4 - C1.WPF.Pdf.4 - C1.WPF.Word.4 - C1.WPF.Zip.4 - C1.WPF.FlexViewer.4 UWP: - C1.UWP - C1.UWP.Document - C1.UWP.BarCode - C1.UWP.Bitmap - C1.UWP.DX - C1.UWP.Excel - C1.UWP.FlexChart - C1.UWP.Imaging - C1.UWP.Pdf - C1.UWP.Word - C1.UWP.Zip - C1.UWP.FlexViewer Load and view PDF files from a stream You might want to load a file from a memory stream instead of the disk to improve the application’s speed. C1PdfDocumentSource provides two overloads for loading PDF files: - C1PdfDocumentSource.LoadFromFile(string fileName) - C1PdfDocumentSource.LoadFromStream(System.IO.Stream stream) While the first overload helps you directly load a PDF file from a disk, the second overload helps you easily load and view PDF files in a stream using the following steps in a WinForms application: - Step 1: Drop C1FlexViewer on the form. - Step 2: Drop C1PdfDocumentSource on the form. - Step 3: Add Invoice.pdf to the project. - Step 4: Go to Form_Load method in the code-behind. - Step 5: Paste the following code in Form_Load. using (System.IO.FileStream fileStream = File.OpenRead(@"..\\..\\Invoice.pdf")) { //create new MemoryStream object MemoryStream memStream = new MemoryStream(); memStream.SetLength(fileStream.Length); //read file to MemoryStream fileStream.Read(memStream.GetBuffer(), 0, (int)fileStream.Length); c1PdfDocumentSource1.LoadFromStream(memStream); c1FlexViewer1.DocumentSource = c1PdfDocumentSource1; } - Step 6: Run the application. The PDF File gets loaded in C1FlexViewer. View PDF files with multi-language text in a PDF Viewer You can produce PDF files from documents written in any language. By supporting different PDF fonts, C1PDFDocumentSource also supports multi-language text. The component supports TrueType, Type0, Type1, OpenType, and Unicode fonts. Because of this support, C1PDFDocumentSource can read most PDF files with different fonts — with the exception of currently having only partial support for CFF fonts. Here's how you can load a PDF file with Arabic text in FlexViewer in a WinForms application (as well as how you can load a PDF in FlexViewer through C1PDFDocumentSource at design time without any lines of code): - Step 1: Drop C1FlexViewer on the form. - Step 2: Drop C1PdfDocumentSource on the form. - Step 3: Add ArabicText.pdf to the project. - Step 4: Set C1PdfDocumentSource1.DocumentLocation="C:\ArabicText.pdf" - Step 5: Select the DocumentSource dropdown for C1FlexViewer and set it to c1PdfDocumentSource1. - Step 6: Run the application. The PDF file loads in C1FlexViewer. Read and view PDF files in UWP applications Because it has cross-platform support, C1PDFDocumentSource can load a PDF file on any platform. In addition to WinForms and WPF, C1PDFDocumentSource and C1FlexViewer are also supported on UWP applications. Load a PDF through a stream in C1FlexViewer in a UWP application using the following steps: - Step 1: Create a UWP -> Blank App. - Step 2: Add C1FlexViewer to MainPage.xaml. - Step 3: Add a reference to C1.UWP.Document in the project. - Step 4: Create a Resources folder in the project and add a PDF file. For example, add Invoice.PDF to the folder. - Step 5: Go to the code-behind in Page_Loaded method. - Step 6: Include the following namespace: using C1.UWP.Document - Step 7: Load the PDF file through a stream: Stream stream = this.GetType().GetTypeInfo().Assembly.GetManifestResourceStream("PdfDocumentSourceSamples.Resources.DefaultDocument.pdf"); - Step 8: Create a C1PdfDocumentSource object and load the file from the stream into it: C1PdfDocumentSource _pdfDocSource=new C1PdfDocumentSource(); await _pdfDocSource.LoadFromStreamAsync(stream.AsRandomAccessStream()); - Step 9: Assign FlexViewer’s DocumentSource object to the C1PdfDocumentSource object: C1FlexViewer1.DocumentSource=_pdfDocSource; Here's what your PDF file should look like in the UWP C1FlexViewer: yet to add Convert PDF pages to JPEG in a specific resolution The easiest way to view PDF files on your system without Acrobat Reader is to convert them to JPEG files. Even if you want to view PDFs in your browser, you might need an external plug-in to do so, while viewing JPEG files doesn't require any plug-ins. It's easy to convert PDF files to JPEG with C1PDFDocumentSource: you can load a PDF file and export the pages to JPEG files. Now it's time to set the resolution. You can specify more resolution if you want to see less loss in the clarity of the image,but these JPEGs would be larger in size. Simply write the following code in your WinForms application and run it: - Step 1: Add Shipping Labels.pdf to the project. - Step 2: Go to the code-behind and add the following namespace: using C1.Win.C1Document; - Step 3: Create a C1PDFDocumentSource object and load a PDF into it. C1PdfDocumentSource pdf = new C1PdfDocumentSource(); pdf.LoadFromFile(@"..\\..\\ShippingLabels.pdf"); - Step 4: Create a JPEG exporter object and specify the resulting FileName: var exporter = ExportProvider.JpegExportProvider.NewExporter(); exporter.FileName = "TestPDF.jpg"; - Step 5: Call ShowOptionsDialog of the exporter. This dialog is used to set the resolution for the JPEG image. export.ShowOptionsDialog(); - Step 6: Use the PDF object to export to JPEG. pdf.Export(exporter); - Step 7: Run the application. - Step 8: Set the desired resolution and click OK. Here's what the final JPEG file should look like: Convert a batch of PDF files to JPEG The above example showed you how you can convert a single PDF file to JPEG. However, you might want to convert to JPEG images all at once. With C1PDFDocumentSource, you can convert a batch of files easily using the following code: String inputDirectory = @"C:\\PDF\\"; String[] files = Directory.GetFiles(inputDirectory, "*.pdf"); foreach (String filePath in files) { int startIdx = filePath.LastIndexOf("\\\"); int endIdx = filePath.LastIndexOf("."); String docName = filePath.Substring(startIdx + 1, endIdx - startIdx - 1); C1PdfDocumentSource pdf = new C1PdfDocumentSource(); var exporter = ExportProvider.JpegExportProvider.NewExporter(); exporter.FileName = "PDFtoJPEG”+”docName+”.jpg"; pdf.LoadFromFile(@"C:\\PDF\\"+docName+".pdf"); pdf.Export(exporter); } View a PDF in Viewer with rotated pages FlexViewer is a powerful tool when it comes to offering display preferences to users for the documents it supports. View a PDF with rotated pages at design time or at run time. To load a PDF rotated 90 degrees clockwise, follow these steps in a WinForms application: - Step 1: Add CustomerSuppliers.pdf to the project. - Step 2: Go to the code-behind and add the following namespace: using C1.Win.C1Document; - Step 3: Create the C1PdfDocumentSource object and load a PDF file. C1PdfDocumentSource pdf = new C1PdfDocumentSource(); pdf.LoadFromFile(@"..\\..\\CustomerSuppliers.pdf"); - Step 4: Drop C1FlexViewer on the form in design mode. - Step 5: In the code-behind, set: C1FlexViewer1.DocumentSource=pdf.DocumentSource; - Step 6: At design time, select C1FlexViewer on the form. - Step 7: In Properties, set the following property: C1FlexViewer.RotateView= C1.Win.FlexViewer.FlexViewerRotateView.Rotation90Clockwise; This will rotate all of your PDF pages 90 degrees clockwise. You can also set the same property in the code-behind. Here's what your PDF should like: Navigate through a PDF Document in a WPF viewer One of the uses of C1PdfDocumentSource, as mentioned earlier, is that it can help you load a PDF in FlexViewer. With its 2017v2 release, this component also supports outlines and hyperlinks, making it possible to navigate through these documents in FlexViewer. You only need to load a PDF with outlines or hyperlinks, and FlexViewer can help you navigate through the documents. If you want to view a PDF with hyperlinks in a WPF application, use the following steps: - Step 1: Drop C1FlexViewer on the form. - Step 2: Set the following property for C1FlexViewer in the XAML tag: <c1:C1FlexViewer - Step 3: Add a reference to C1.WPF.Document DLL in the project. - Step 4: Add Invoice.pdf to the project. - Step 5: Go to the code-behind in the Window_Loaded event. - Step 6: Include the following namespace for the C1.WPF.Document: using C1.WPF.Document - Step 7: Create a C1PdfDocumentSource object and load a PDF file to it. C1PdfDocumentSource pdf=new C1PdfDocumentSource(); Pdf.LoadFromFile(@”..\\..\\Invoice.pdf”); - Step 8: Set FlexViewer’s DocumentSource to the C1PdfDocumentSource object. Flv.DocumentSource=pdf; - Step 9: Run the application. - Step 10: Click on the ‘Document Outlines’ button on the FlexViewer toolbar. - Step 11: Click on an outline in the Document Outlines panel that opens on the left to navigate through the document. You might come across other instances where you would need to work with PDF files in a .NET application. For more information across platforms, please visit the following documentation: add links to documentation when it's available C1Document for Winforms, C1Document for WPF, C1Document for UWP. Sample You can find samples on PDFDocumentSource and SSRSDocumentSource at the following locations after installing C1Studio installer for WinForms, WPF, and UWP: WinForms: C:\Users\ WPF: C:\Users\ - PDFDocumentSourceSamples - PrintAndExport UWP: C:\Users\ - PDFDocumentSourceSamples Generate, View, and Print PDFs Apart from loading, viewing, and printing, you can also generate a PDF in your application. Please visit this blog this links to another blog for more details. Limitations C1PDFDocumentSource has certain limitations in every platform. Please refer to the respective documentation to view these limitations. Read more about PDF DocumentSource. <!-- p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px 'Helvetica Neue'; color: #454545} --><!-- p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Calibri} -->
https://www.grapecity.com/blogs/load-export-search-and-print-pdfs-with-net-pdf-component-and-pdf-viewer
CC-MAIN-2019-22
refinedweb
1,806
50.23
Programm will not work This program will not compile if u compile this as it. programm 18| |84 69 54| |138 114 90| Java Matrix Java collection Vector Java collection Vector How can we use the vector class in java program? The vector class is similar to the ArrayList class except that the vector class is synchronized. import java.util.Iterator; import Java Vector Java Vector Vector represents a collection of similar items. In Java, the Vector class is defined..., its items can be accessed using an integer index. Once the Vector has been java programm java programm Create program, which will calculate number of days between two dates. The program has to accordance with the leap-years (do...: dd.mm.yyyy-dd.mm.yyyy (d-day, m-month, y-year) Example: $java Collection frame work - Java Beginners Collection frame work How to a sort a list of objects ordered by an attribute of the object write a programm using java write a programm using java print the following using java programming menu drive programm in java menu drive programm in java calculate area of circle, square,rectangele in menu driven programme in java Vector in java Vector in java Vector in java implements dynamic array. It is similar to array... and the increment is specified by incr. Vector(Collection c)This form will create a vector that contain the element specified in collection. Here are some Java Collection Java Collection What are Vector, Hashtable, LinkedList and Enumeration
http://www.roseindia.net/tutorialhelp/allcomments/145258
CC-MAIN-2014-10
refinedweb
248
53.21
This chapter investigates the details of C# methods and their parameters. It includes passing by value, passing by reference, and returning data via an out parameter. In C# 4.0, default parameter support was added, and this chapter explains how to use default parameters. Save 35% off the list price* of the related book or multi-format eBook (EPUB + MOBI + PDF) with discount code ARTICLE. * See informit.com/terms From. Besides the basics of calling and defining methods, this chapter covers some slightly more advanced concepts—namely, recursion, method overloading, optional parameters, and named arguments. All method calls discussed so far and through the end of this chapter are static (a concept that Chapter 6 explores in detail). Even as early as the HelloWorld program in Chapter 1, you learned how to define a method. In that example, you defined the Main() method. In this chapter, you will learn about method creation in more detail, including the special C# syntaxes (ref and out) for parameters that pass variables rather than values to methods. Lastly, we will touch on some rudimentary error handling. Calling a Method To begin, we reexamine System.Console.Write(), System.Console.WriteLine(), and System.Console.ReadLine() from Chapter 1. This time we look at them as examples of method calls in general instead of looking at the specifics of printing and retrieving data from the console. Listing 5.2 shows each of the three methods in use. Listing 5.2: A Simple Method Call class HeyYou { static void Main() { string firstName; string lastName; System.Console.WriteLine("Hey you!"); System.Console.Write("Enter your first name: "); firstName = System.Console.ReadLine(); System.Console.Write("Enter your last name: "); lastName = System.Console.ReadLine(); System.Console.WriteLine( $"Your full name is { firstName } { lastName }."); } } The parts of the method call include the method name, argument list, and returned value. A fully qualified method name includes a namespace, type name, and method name; a period separates each part of a fully qualified method name. As we will see, methods are often called with only a part of their fully qualified name. Namespaces Namespaces are a categorization mechanism for grouping all types related to a particular area of functionality. Namespaces are hierarchical and can have arbitrarily many levels in the hierarchy, though namespaces with more than half a dozen levels are rare. Typically the hierarchy begins with a company name, and then a product name, and then the functional area. For example, in Microsoft.Win32.Networking, the outermost namespace is Microsoft, which contains an inner namespace Win32, which in turn contains an even more deeply nested Networking namespace. Namespaces are primarily used to organize types by area of functionality so that they can be more easily found and understood. However, they can also be used to avoid type name collisions. For example, the compiler can distinguish between two types with the name Button as long as each type has a different namespace. Thus you can disambiguate types System.Web.UI.WebControls.Button and System.Windows.Controls.Button. In Listing 5.2, the Console type is found within the System namespace. The System namespace contains the types that enable the programmer to perform many fundamental programming activities. Almost all C# programs use types within the System namespace. Table 5.1 provides a listing of other common namespaces. Begin 4.0 Table 5.1: Common Namespaces End 4.0 It is not always necessary to provide the namespace when calling a method. For example, if the call expression appears in a type in the same namespace as the called method, the compiler can infer the namespace to be the namespace that contains the type. Later in this chapter, you will see how the using directive eliminates the need for a namespace qualifier as well. Type Name Calls to static methods require the type name qualifier as long as the target method is not within the same type.1 (As discussed later in the chapter, a using static directive allows you to omit the type name.) For example, a call expression of Console.WriteLine() found in the method HelloWorld.Main() requires the type, Console, to be stated. However, just as with the namespace, C# allows the omission of the type name from a method call whenever the method is a member of the type containing the call expression. (Examples of method calls such as this appear in Listing 5.4.) The type name is unnecessary in such cases because the compiler infers the type from the location of the call. If the compiler can make no such inference, the name must be provided as part of the method call. At their core, types are a means of grouping together methods and their associated data. For example, Console is the type that contains the Write(), WriteLine(), and ReadLine() methods (among others). All of these methods are in the same group because they belong to the Console type. Scope In the previous chapter, you learned that the scope of a program element is the region of text in which it can be referred to by its unqualified name. A call that appears inside a type declaration to a method declared in that type does not require the type qualifier because the method is in scope throughout its containing type. Similarly, a type is in scope throughout the namespace that declares it; therefore, a method call that appears in a type in a particular namespace need not specify that namespace in the method call name. Method Name Every method call contains a method name, which might or might not be qualified with a namespace and type name, as we have discussed. After the method name comes the argument list; the argument list is a parenthesized, comma-separated list of the values that correspond to the parameters of the method. Parameters and Arguments A method can take any number of parameters, and each parameter is of a specific data type. The values that the caller supplies for parameters are called the arguments; every argument must correspond to a particular parameter. For example, the following method call has three arguments: System.IO.File.Copy( oldFileName, newFileName, false) The method is found on the class File, which is located in the namespace System.IO. It is declared to have three parameters, with the first and second being of type string and the third being of type bool. In this example, we use variables (oldFileName and newFileName) of type string for the old and new filenames, and then specify false to indicate that the copy should fail if the new filename already exists. Method Return Values In contrast to System.Console.WriteLine(), the method call System.Console.ReadLine() in Listing 5.2 does not have any arguments because the method is declared to take no parameters. However, this method happens to have a method return value. The method return value is a means of transferring results from a called method back to the caller. Because System.Console.ReadLine() has a return value, it is possible to assign the return value to the variable firstName. In addition, it is possible to pass this method return value itself as an argument to another method call, as shown in Listing 5.3. Listing 5.3: Passing a Method Return Value as an Argument to Another Method Call class Program { static void Main() { System.Console.Write("Enter your first name: "); System.Console.WriteLine("Hello {0}!", System.Console.ReadLine()); } } Instead of assigning the returned value to a variable and then using that variable as an argument to the call to System.Console.WriteLine(), Listing 5.3 calls the System.Console.ReadLine() method within the call to System.Console.WriteLine(). At execution time, the System.Console.ReadLine() method executes first, and its return value is passed directly into the System.Console.WriteLine() method, rather than into a variable. Not all methods return data. Both versions of System.Console.Write() and System.Console.WriteLine() are examples of such methods. As you will see shortly, these methods specify a return type of void, just as the HelloWorld declaration of Main returned void. Statement versus Method Call Listing 5.3 provides a demonstration of the difference between a statement and a method call. Although System.Console.WriteLine("Hello {0}!", System.Console.ReadLine()); is a single statement, it contains two method calls. A statement often contains one or more expressions, and in this example, two of those expressions are method calls. Therefore, method calls form parts of statements. Although coding multiple method calls in a single statement often reduces the amount of code, it does not necessarily increase the readability and seldom offers a significant performance advantage. Developers should favor readability over brevity. Begin 6.0
http://www.informit.com/articles/article.aspx?p=2923212&amp;seqNum=10
CC-MAIN-2018-51
refinedweb
1,452
56.96
Go to: Synopsis. Return value. Related. Flags. MEL examples. viewFit [-allObjects] [-animate boolean] [-fitFactor float] [-namespace string] [camera] viewFit is undoable, NOT queryable, and NOT editable.The viewFit command positions the specified camera so its point-of-view contains all selected objects other than itself. If no objects are selected, everything is fit to the view (excepting cameras, lights, and sketching plannes). The fit-factor, if specified, determines how much of the view should be filled. If a camera is not specified, the camera in the active view will be used. After the camera is moved, its center of interest is set to the center of the bounding box of the objects. None // Position the active camera to view the active objects viewFit; // Position cameraShape-1 to view all objects viewFit -all cameraShape1; // Fill 50 percent of the active view with active objects viewFit -f 0.5; viewFit -all;
http://download.autodesk.com/us/maya/2009help/Commands/viewFit.html
crawl-003
refinedweb
149
55.34
TypeScript offers a powerful type-checking facility for JavaScript and a must-have tool for Front-end projects. If you are starting out, it may feel like introducing unnecessary overhead, but its usefulness is felt once you have built up a decent codebase. The additional work you put in for declaring the types acts as your own guard rails, preventing you from obvious type errors. In this post I want to cover the various options of declaring these types, from the anonymous-types to concrete classes and modules. Knowing these options allows you to pick the right style of declaring types. Since TypeScript follows a structural type system, you are not required to name your types when declaring them. This gives you the benefit of creating compatible types purely on the basis of having matching members. The TypeScript spec calls these as Object Type Literals, however I prefer to call them Anonymous Types, which is much easier to remember too!. import React from 'react'; const PersonComponent: React.StatelessComponent<{ name: string; email: string; avatarUrl: string; }> = ({ name, email, avatarUrl }) => { return <div>{/* Person VDOM */}</div>; }; In the above code, the props for the PersonComponent is declared with an anonymous-type. This kind of declaration usually works best for local types that do not need to be shared outside. With Type Aliases we adopt a name to represent the type. This is useful when the same structure gets repeated at multiple places. You can save yourself some typing (pun intended 😀) and use the name instead. type Person = { name: string; email: string; avatarUrl?: string; }; Type Aliases are strikingly similar to interfaces but lack a few important abilities: They also work well for domain-specific data-types: type UrlString = string; type PersonId = string | undefined | null; type SessionToken = string; type AuthChangedCallback = (username: string, token?: SessionToken) => void; As mentioned earlier, Interfaces are more useful than Type Aliases and should normally be your default choice for declaring the type. Both interfaces and type-aliases are compile-time-only constructs and there is no footprint when the final JavaScript is emitted. This particular characteristic is also known as zero-cost abstraction. interface Person { name: string; email: string; avatarUrl?: string; address?: Address; } interface Address { line1: string; line2?: string; city: string; state: string; country: string; pincode: string; } Interfaces work great when you are modeling your domain and identifying the various entities and value objects in the system. This frees you from the implementation quirks and focus more on the Ubiquitous Language of the domain. Classes are concrete types and can be instantiated with the new operator. A React component is a good example where you do have to declare a concrete type and even extend the framework type: React.Component. import React from 'react'; class Avatar extends React.Component { public render() { const { source, description } = this.props; return <img src={source} alt={description} style={{ width: 64, height: 64 }} />; } } Classes can also be guarded with an interface with constructor signatures to ensure type-safe creation, as seen below: interface Constructor<T> { new (greeting: string): T; } interface Greeter { greet(name: string): string; } class Hello implements Greeter { constructor(public greeting: string) { this.greeting = greeting; } public greet(name: string) { return `${this.greeting} ${name}`; } } const DefaultGreeter: Constructor<Greeter> = Hello; const x: Greeter = new DefaultGreeter('hi'); A little known fact about TypeScript is that you can also declare anonymous-types, type-aliases, interfaces, enums, classesinside a function. They are not just limited to top level declarations. Types declared inside functions are local and useful for local type checking. function authenticateUser(username: string) { type Credentials = { token: string; username: string; }; const creds: Credentials = { username, token: sessionService.getToken() }; authService.authenticate(creds); } In fact, you can even have declarations local to a block: function f() { if (true) { interface T { x: number; } let v: T; v.x = 5; } else { interface T { x: string; } let v: T; v.x = 'hello'; } } Namespaces are primarily meant to collect a set of related types and put them under a common bucket. It is an organizational tool in TypeScript and allows breaking up the domain into many cohesive sub-domains. Types inside a namespace are referenced with a dotted notation such as <Namespace>.<Type> Here’s a collection of types to track the state of the React Native app, organized inside the namespace: // my-app-state.ts export namespace MyAppState { export let offline = false; export let active = true; export function setup() { // setup code to add listeners for the offline + active state // using AppState and NetInfo } export class ActionTracker { /* track user actions by sending telemetry requests */ } } // app.ts import { MyAppState } from './my-app-state.ts'; console.log(MyAppState.offline); Note the need to exportthe members of the namespace to be available outside. Else they would be local and private to the namespace. This is the highest level of organization that is possible in TypeScript. You can collect all of the related namespaces and types under a module and can even import into a project purely for the type definitions. For example, the modules under the @types npm scope is meant for this purpose, such as @types/react, @types/react-dom, etc. Moving the domain-types of a project to a module is a good use of this construct. If you are building a set of related apps, it makes sense to move the domain-specific types to a module and import into the projects. Modules allow declaration merging. This lets you augment the type-definitions of a third-party module, in case you find something missing. // custom-module/index.d.ts declare module 'custom-module' { export class CustomConfigurator implements Configurator { /* ... */ } export interface Configurator {} export enum ConfigurationKey { name = 'name', place = 'place', animal = 'animal', thing = 'thing', } } // app.js import { Configurator } from 'custom-module'; If you are authoring a library or a private package for internal use, you can use declaration-files ( *.d.ts) to specify all the types. TypeScript will automatically look for these files when importing the library into your main project. There is a spectrum of options available for declaring types in TypeScript. Now that you know the various possibilities, you can pick and choose the right style based on your need.
https://blog.pixelingene.com/2018/10/different-ways-of-declaring-types-in-typescript/
CC-MAIN-2021-21
refinedweb
1,012
54.63
1 /*2 * @(#)LocaleServiceProvider.java 1.4 06/04/213 *4 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.5 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.6 */7 8 package java.util.spi;9 10 import java.util.Locale ;11 12 /**13 * <p>14 * This is the super class of all the locale sensitive service provider 15 * interfaces (SPIs). 16 * <p>17 * Locale sensitive service provider interfaces are interfaces that 18 * correspond to locale sensitive classes in the <code>java.text</code>19 * and <code>java.util</code> packages. The interfaces enable the 20 * construction of locale sensitive objects and the retrieval of 21 * localized names for these packages. Locale sensitive factory methods 22 * and methods for name retrieval in the <code>java.text</code> and 23 * <code>java.util</code> packages use implementations of the provider 24 * interfaces to offer support for locales beyond the set of locales 25 * supported by the Java runtime environment itself.26 * <p>27 * <h4>Packaging of Locale Sensitive Service Provider Implementations</h4>28 * Implementations of these locale sensitive services are packaged using the 29 * <a HREF="../../../../technotes/guides/extensions/index.html">Java Extension Mechanism</a>30 * as installed extensions. A provider identifies itself with a 31 * provider-configuration file in the resource directory META-INF/services, 32 * using the fully qualified provider interface class name as the file name. 33 * The file should contain a list of fully-qualified concrete provider class names, 34 * one per line. A line is terminated by any one of a line feed ('\n'), a carriage 35 * return ('\r'), or a carriage return followed immediately by a line feed. Space 36 * and tab characters surrounding each name, as well as blank lines, are ignored. 37 * The comment character is '#' ('#'); on each line all characters following 38 * the first comment character are ignored. The file must be encoded in UTF-8.39 * <p>40 * If a particular concrete provider class is named in more than one configuration 41 * file, or is named in the same configuration file more than once, then the 42 * duplicates will be ignored. The configuration file naming a particular provider 43 * need not be in the same jar file or other distribution unit as the provider itself. 44 * The provider must be accessible from the same class loader that was initially 45 * queried to locate the configuration file; this is not necessarily the class loader 46 * that loaded the file. 47 * <p>48 * For example, an implementation of the49 * {@link java.text.spi.DateFormatProvider DateFormatProvider} class should 50 * take the form of a jar file which contains the file: 51 * <pre>52 * META-INF/services/java.text.spi.DateFormatProvider 53 * </pre>54 * And the file <code>java.text.spi.DateFormatProvider</code> should have 55 * a line such as: 56 * <pre>57 * <code>com.foo.DateFormatProviderImpl</code>58 * </pre>59 * which is the fully qualified class name of the class implementing 60 * <code>DateFormatProvider</code>.61 * <h4>Invocation of Locale Sensitive Services</h4>62 * <p>63 * Locale sensitive factory methods and methods for name retrieval in the 64 * <code>java.text</code> and <code>java.util</code> packages invoke 65 * service provider methods when needed to support the requested locale. 66 * The methods first check whether the Java runtime environment itself 67 * supports the requested locale, and use its support if available. 68 * Otherwise, they call the <code>getAvailableLocales()</code> methods of 69 * installed providers for the appropriate interface to find one that 70 * supports the requested locale. If such a provider is found, its other 71 * methods are called to obtain the requested object or name. If neither 72 * the Java runtime environment itself nor an installed provider supports 73 * the requested locale, a fallback locale is constructed by replacing the 74 * first of the variant, country, or language strings of the locale that's 75 * not an empty string with an empty string, and the lookup process is 76 * restarted. In the case that the variant contains one or more '_'s, the 77 * fallback locale is constructed by replacing the variant with a new variant 78 * which eliminates the last '_' and the part following it. Even if a 79 * fallback occurs, methods that return requested objects or name are 80 * invoked with the original locale before the fallback.The Java runtime 81 * environment must support the root locale for all locale sensitive services 82 * in order to guarantee that this process terminates.83 * <p>84 * Providers of names (but not providers of other objects) are allowed to 85 * return null for some name requests even for locales that they claim to 86 * support by including them in their return value for 87 * <code>getAvailableLocales</code>. Similarly, the Java runtime 88 * environment itself may not have all names for all locales that it 89 * supports. This is because the sets of objects for which names are 90 * requested can be large and vary over time, so that it's not always 91 * feasible to cover them completely. If the Java runtime environment or a 92 * provider returns null instead of a name, the lookup will proceed as 93 * described above as if the locale was not supported.94 * 95 * @since 1.696 * @version @(#)LocaleServiceProvider.java 1.4 06/04/2197 */98 public abstract class LocaleServiceProvider {99 100 /**101 * Sole constructor. (For invocation by subclass constructors, typically102 * implicit.)103 */104 protected LocaleServiceProvider() {105 }106 107 /**108 * Returns an array of all locales for which this locale service provider 109 * can provide localized objects or names.110 *111 * @return An array of all locales for which this locale service provider 112 * can provide localized objects or names.113 */114 public abstract Locale [] getAvailableLocales();115 }116 Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ |
http://kickjava.com/src/java/util/spi/LocaleServiceProvider.java.htm
CC-MAIN-2017-30
refinedweb
967
54.63
I end up doing a lot of rapid prototyping and functional mockups for (one of) my job(s), and sometimes that ends with really crude solutions to complex problems. Sometimes the really crude solutions are actually kind of neat despite a faint taint of awful. This story is about one of those times. The Scenario I was prototyping a system for a client of a client where the prototyped used an inferior datasource to mock the intended results of the new system based on a superior datasource such that the inferior datasource looked like the results achieved with the non-existant improved system. Got that? Well, that sentence might have been intentionally confusing, so I'll try explaining that again. There were three datasources for this prototyped system: - The existing datasource used in production. - A planned but non-existant datasource that is intended to be superior to the existing datasource. - A datasource worse than the existing production datasource, which I needed to use to create a functional mock of the superior and non-existant datasource. This is the classic challenge: do more with less, but maybe with a slight twist: make it look like you're doing more, with less. In the short of it, I needed to display special metadata for content, except I didn't actually have the special metadata I needed to display. The Solution After staring at my sad stack of cards, I realized that the metadata I needed could be extracted from the structure of urls associated with the data. For example a piece of data with the url had video content, and something at was blog content. Throw in another half dozen url structures and I had enough metadata for polishing my impoverished data into something usable. Even with this realization, I still needed to perform some fairly complex matching, and depending on the results of the matching I needed to represent the data differently. And I wasn't thinking very well, so I didn't just do the matching in views and add an extra value to each result to tell the template in which way to represent the each piece of data. Instead I wrote a template tag to perform if-else blocks based on successfully matching a supplied regular expression. from django import template import re register = template.Library() @register.tag def ifmatches(parser, token): lst = token.split_contents() val = lst[1] regex = lst[2] nodelist_true = parser.parse(('else','endifmatches',)) token = parser.next_token() if token.contents == 'else': nodelist_false = parser.parse(('endifmatches',)) parser.delete_first_token() else: nodelist_false = template.NodeList() return MatchesRegexNode(nodelist_true, nodelist_false, val, regex) class MatchesRegexNode(template.Node): def __init__(self, nodelist_true, nodelist_false, val, regex): self.nodelist_true = nodelist_true self.nodelist_false = nodelist_false self.val = template.Variable(val) self.regex = regex.strip('"') def render(self, context): val = self.val.resolve(context) if re.search(self.regex, val): return self.nodelist_true.render(context) else: return self.nodelist_false.render(context) Usage is like this: {% ifmatches object.url "/video/\w+/" %} <p class="video">{{ object.title }}</p> {% else %} <p class="story">{{ object.title }}</p> {% endifmatches %} There are myriad and sundry reasons to hate this solution: you can't precompile the regular expressions and reuse them, you're doing too much calculation in the templates instead of views. Then again, I was on a binge of writing weird template tags and filters for that project: @register.filter def kilobytes(value): return int(value) / 1000 @register.filter def truncate_char(value, arg): length = len(value) arg = int(arg) if length > arg: return u"%s..." % stripped[:arg-3] return value Sometimes when you're putting out fires in throw-away code you make bad decisions, but that's the whole fun of rapid prototyping: get it done by any means possible, as quickly as possible. Later you review your code and decide never to make the same bad decisions again. Sometimes we call that learning.
http://lethain.com/bad-ideas-and-regular-expressions-in-templates/
CC-MAIN-2016-22
refinedweb
642
57.27
Comment about calling ProcessCapsules twice will break in some scenarios. For example windows capsule update will stage multiple capsules at once. If it mixes capsules from both stages and you use memory to preserve capsule contents you will lose your non system capsule because of the reboot. Advertising 2nd - For capsules that are not FMP or update capsules but capsules being requested to be put in the system table you will still need to process them even though the boot mode should not be BOOT_ON_FLASH_UPDATE. Thanks Sean > -----Original Message----- > From: edk2-devel [mailto:edk2-devel-boun...@lists.01.org] On Behalf Of > Jiewen Yao > Sent: Friday, September 30, 2016 5:21 AM > To: edk2-devel@lists.01.org > Cc: Michael D Kinney <michael.d.kin...@intel.com>; Feng Tian > <feng.t...@intel.com>; Chao Zhang <chao.b.zh...@intel.com>; Liming Gao > <liming....@intel.com>; Star Zeng <star.z...@intel.com> > Subject: [edk2] [PATCH V2 06/50] MdeModulePkg/CapsuleLib: Add > ProcessCapsules() API. > > ProcessCapsules() API can be used by platform BDS to process all capsules. > > Cc: Feng Tian <feng.t...@intel.com> > Cc: Star Zeng <star.z...@intel.com> > Cc: Michael D Kinney <michael.d.kin...@intel.com> > Cc: Liming Gao <liming....@intel.com> > Cc: Chao Zhang <chao.b.zh...@intel.com> > Contributed-under: TianoCore Contribution Agreement 1.0 > Signed-off-by: Jiewen Yao <jiewen....@intel.com> > Reviewed-by: Liming Gao <liming....@intel.com> > --- > MdeModulePkg/Include/Library/CapsuleLib.h | 45 ++++++++++++++++++-- > 1 file changed, 42 insertions(+), 3 deletions(-) > > diff --git a/MdeModulePkg/Include/Library/CapsuleLib.h > b/MdeModulePkg/Include/Library/CapsuleLib.h > index 487cb0f..659c077 100644 > --- a/MdeModulePkg/Include/Library/CapsuleLib.h > +++ b/MdeModulePkg/Include/Library/CapsuleLib.h > @@ -2,7 +2,7 @@ > > This library class defines a set of interfaces for how to process capsule > image > updates. > > -Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.<BR> > +Copyright (c) 2007 - 2016, Intel Corporation. All rights reserved.<BR> > This program and the accompanying materials are licensed and made available > under the terms and conditions of the BSD License that accompanies this > distribution. > The full text of the license may be found at @@ -20,7 +20,9 @@ WITHOUT > WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR > IMPLIED. > The firmware checks whether the capsule image is supported > by the CapsuleGuid in CapsuleHeader or if there is other specific > information > in > the capsule image. > - > + > + Caution: This function may receive untrusted input. > + > @param CapsuleHeader Pointer to the UEFI capsule image to be checked. > > @retval EFI_SUCESS Input capsule is supported by firmware. > @@ -35,7 +37,9 @@ SupportCapsuleImage ( > /** > The firmware-specific implementation processes the capsule image > if it recognized the format of this capsule image. > - > + > + Caution: This function may receive untrusted input. > + > @param CapsuleHeader Pointer to the UEFI capsule image to be processed. > > @retval EFI_SUCESS Capsule Image processed successfully. > @@ -47,4 +51,39 @@ ProcessCapsuleImage ( > IN EFI_CAPSULE_HEADER *CapsuleHeader > ); > > +/** > + > + This routine is called to process capsules. > + > + Caution: This function may receive untrusted input. > + > + If the current boot mode is NOT BOOT_ON_FLASH_UPDATE, this routine does > nothing. > + If the current boot mode is BOOT_ON_FLASH_UPDATE, the capsules > + reported in EFI_HOB_UEFI_CAPSULE are processed. If there is no > + EFI_HOB_UEFI_CAPSULE, this routine does nothing. > + > + This routine should be called twice in BDS. > + 1) The first call must be before EndOfDxe. The system capsules is > processed. > + If device capsule FMP protocols are exposted at this time, the device > + capsules are processed. > + Each individual capsule result is recorded in capsule record variable. > + System may reset in this function, if reset is required by capsule. > + > + 2) The second call must be after EndOfDxe and after ConnectAll, so that all > + device capsule FMP protocols are exposed. > + The system capsules are skipped. If the device capsules are NOT > processed > + in first call, they are processed here. > + Each individual capsule result is recorded in capsule record variable. > + System may reset in this function, if reset is required by capsule. > + > + @retval EFI_SUCCESS There is no error when processing capsules. > + @retval EFI_OUT_OF_RESOURCES No enough resource to process capsules. > + > +**/ > +EFI_STATUS > +EFIAPI > +ProcessCapsules( > + VOID > + ); > + > #endif > -- > 2.7.4.windows.1 > > _______________________________________________ > edk2-devel mailing list > edk2-devel@lists.01.org > _______________________________________________ edk2-devel mailing list edk2-devel@lists.01.org
https://www.mail-archive.com/edk2-devel@lists.01.org/msg17663.html
CC-MAIN-2017-51
refinedweb
684
53.17
Hello I run into problems with new binary package. Following function reads a list of elements one by one until end of stream. List is very long (won't fit into memory). In binary-0.5.0.1 and earlier it read list lazily. Now it seems that it tries to read whole list to memory. Program does not produce any output and memory usage steadily grows. > getStream :: Get a -> Get [a] > getStream getter = do > empty <- isEmpty > if empty > then return [] > else do x <- getter > xs <- getStream getter > return (x:xs) How could I add laziness to this function to revert to old behavior. -- Khudyakov Alexey
http://www.haskell.org/pipermail/haskell-cafe/2009-September/066531.html
CC-MAIN-2013-48
refinedweb
106
65.42
Patent application title: MODULAR TOOL FOR CONSTRUCTING A LINK TO A RIGHTS PROGRAM FROM ARTICLE INFORMATION Inventors: James Arbo (Chelmsford, MA, US) Assignees:-07 Patent application number: 20130036350 Abstract: A link to a rights advisor website can be constructed from article metadata. Claims: 1. A modular tool for constructing a link to a rights program from article information, comprising: a plurality of pre-defined modules, each of which accepts an input and contains program code that can be executed to generate an output from the input, at least one module of the plurality of modules accepting the article information as an input; a data file for specifying at least one input to each module and for specifying an execution order of the modules; and an execution engine that executes program code contained in each of the modules using the input specified by the data file and in the order specified by the data file, wherein a module which is executed last generates the link as an output. 2. The modular tool of claim 1 wherein each module is implemented as a Java class with predefined properties and predefined methods. 3. The modular tool of claim 1 wherein the data file is an XML data file. 4. The modular tool of claim 3 wherein the XML data file defines property expressions associated with a module which generate input parameters to that module. 5. The modular tool of claim 4 wherein property expressions associated with a module are evaluated by the execution engine prior to executing the program code contained in the module. 6. The modular tool of claim 3 wherein the XML data file defines a gating expression for a module and wherein the execution engine evaluates the gating expression for a module to determine whether to execute the program code of that module. 7. The modular tool of claim 1 wherein inputs to a module comprise at least one of the group consisting of the article information, literal expressions, an output from another module, and Java Expression Language expressions. 8. The modular tool of claim 1 wherein at least one module contains program code that is executed by the execution engine to access an http server and retrieve web page html code for a web page corresponding to an http URL provided to the program code. 9. The modular tool of claim 8 wherein at least one module contains program code that is executed by the execution engine to extract the link from the retrieved web page html code. 10. The modular tool of claim 8 wherein at least one module contains program code that is executed by the execution engine to extract javascript from the retrieved web page html code and to run the extracted javascript in order to obtain the link. 11. A method for use on a computer with a processor and a memory, the method constructing a link to a rights program from article information and comprising: (a) providing and controlling the processor to store in the memory a plurality of pre-defined modules, each of which accepts an input and contains program code that can be executed to generate an output from the input, at least one module of the plurality of modules accepting the article information as an input; (b) providing and controlling the processor to store in the memory a data file for specifying at least one input to each module and for specifying an execution order of the modules; and (c) controlling the processor to execute program code contained in each of the modules using the input specified by the data file and in the order specified by the data file, wherein a module which is executed last generates the link as an output. 12. The method of claim 11 wherein step (a) comprises implementing each module as a Java class with predefined properties and predefined methods. 13. The method of claim 11 wherein step (b) comprises providing the data file as an XML data file. 14. The method of claim 13 wherein the XML data file defines property expressions associated with a module which generate input parameters to that module. 15. The method of claim 14 wherein step (c) comprises evaluating property expressions associated with a module prior to executing the program code contained in the module. 16. The method of claim 13 wherein the XML data file defines a gating expression for a module and wherein step (c) comprises evaluating the gating expression for a module to determine whether to execute the program code of that module. 17. The method of claim 11 wherein inputs to a module comprise at least one of the group consisting of the article information, literal expressions, an output from another module, and Java Expression Language expressions. 18. The method of claim 11 wherein step (a) comprises providing at least one module containing getter program code that accesses an http server and retrieves web page html code and step (c) comprises providing an http URL as an input to, and executing, the getter program code to retrieve the web page html code from a web page corresponding to the URL. 19. The method of claim 18 wherein step (a) comprises providing at least one module that contains scraping program code that extracts a link from web page html code and step (c) comprises executing the scraping program code to obtain the link from the retrieved web page html code. 20. The method of claim 18 wherein step (a) comprises providing at least one module that contains javascript program code that extracts javascript from web page html code and runs the extracted javascript and step (c) comprises executing the javascript program code to extract and run javascript from the retrieved web page html code to obtain the link. Description: BACKGROUND [0001] This invention relates to digital rights display and methods and apparatus for determining reuse rights for content to which multiple licenses and subscriptions apply. Works, or "content", created by an author is generally subject to legal restrictions on reuse. For example, most content is protected by copyright. In order to conform to copyright law, content users often obtain content reuse licenses. A content reuse license is actually a "bundle" of rights, including rights to present the content in different formats, rights to reproduce the content in different formats, rights to produce derivative works, etc. Thus, depending on a particular reuse, a specific license to that reuse may have to be obtained. [0002] Many organizations use content for a variety of purposes, including research and knowledge work. These organizations obtain that content through many channels, including purchasing content directly from publishers and purchasing content via subscriptions from subscription resellers. Subscriptions generally include some reuse rights that are conveyed to the subscriber. A given subscription service will generally try to offer a standard set of rights across its subscriptions, but large customers will often negotiate with the service to purchase additional rights. Thus, reuse rights may vary from subscription to subscription and the reuse rights available for a particular subscription may vary even across publications within that subscription. In addition, the reuse rights conveyed in these subscriptions often overlap with other rights and licenses purchased from license clearinghouses, or from other sources. [0003] Many knowledge workers attempt to determine which rights are available for particular content before using that content in order to avoid infringing legitimate rights of rightsholders. However, at present, determining what reuse rights an organization has for any given publication is a time-consuming, manual procedure, generally requiring a librarian or legal counsel to review in advance of the use, all license agreements obtained from content providers and purchased from other sources which may pertain to the content and its reuse. The difficulty of this determination means that sometimes an organization will overspend to purchase rights for which it already has paid. Alternatively, knowledge workers may run the risk of infringing a reuse right for which they believe that the organization has a license, but which, in actuality, the organization does not. [0004] Accordingly, organizations, such as the Copyright Clearance Center located in Danvers, Mass., have developed mechanisms that allow knowledge workers to purchase licenses during the search process. In one of these mechanisms, when the worker searching on a publisher's website has navigated to a webpage containing, for example, the content of an article in which the worker is interested, and the worker wants to determine available rights for that article, the worker can click on a link provided on the webpage by the publisher. The link contains a "Rightslink" URL of a rights advisor website and accesses the website. A URL associated with the article is then provided to the website. In response, the rights advisor website extracts all agreements stored therein that are applicable to the organization to which the worker belongs. The rights advisor website converts the URL of the article to a standard publication identifier. The publication identifier is then used to determine agreements that are applicable to that publication. These agreements are processed to determine available rights, terms and prices, which are returned online to the knowledge worker. [0005] However, in some cases, the knowledge worker is not searching on a publisher's website, but on another website which does not include the link to the rights advisor website. For example, the worker may be searching on a website, such as copyright.com, provided by the Copyright Clearance Center. In this case, if the worker requests information on available rights, information identifying an article located by the worker, such as a digital object identifier, is used to locate and access the publisher's webpage for that article. As noted, above, the publisher's webpage contains a link which allows the worker to access the rights advisor webpage and obtain available rights, terms and prices for the article. The Rightslink URL data is then extracted from the publisher's webpage and used to access the rights advisor website to obtain the rights information as disclosed above. [0006] Generally, the Rightslink URL data extraction process involves writing a small software program that is specific to the publisher or clearinghouse whose website is being examined and which processes the website in a manner particular to that website to extract the relevant information. This, in turn, generally involves the services of a programmer and thus the overall process is expensive and may be limited by the availability of programmer resources. It would therefore be desirable if non-programmer personnel could generate the required software code without programmer involvement. However, it is imperative that limitations be placed on the code generation process so that the malfunction of any generated software code does not compromise the entire system or code that extracts data from other websites or return erroneous results to the knowledge worker. SUMMARY [0007] In accordance with the principles of the present invention, the website processing code can be constructed. [0008] In one embodiment, each step is defined in XML text. A sequence of steps, also defined in the XML text forms a rule that forms the website processing code. [0009] In another embodiment, the XML text defines property expressions which are provided as input parameters to the associated widget. [0010] In still another embodiment, widgets are implemented as Java classes. BRIEF DESCRIPTION OF THE DRAWINGS [0011] FIG. 1 is a block schematic diagram of a system for constructing link from article metadata in accordance with the principles of the invention. [0012] FIG. 2 is a schematic diagram of the properties and methods of a widget using the Executable Widget interface. [0013] FIG. 3 is a page of XML data that implements a first exemplary rule. [0014] FIG. 4 is a page of XML data that implements a second exemplary rule. [0015] FIGS. 5A and 5B, when placed together, form a page of XML data that implements a third exemplary rule. DETAILED DESCRIPTION [0016] As set forth above, a pre-written collection, or toolbox, of modules called "widgets", each of which performs a specific task, is provided by a programming staff. A non-programmer user can then specify inputs to each widget and assemble the widgets into a chain called a "linking rule" which accepts article metadata as inputs and produces a Rightslink URL as an output. The user can then designate a set of works or articles with an existing tagging service and attach the linking rule to this set of works. Subsequently, a knowledge worker searching these works can invoke the linking rule which, in turn, scrapes or otherwise constructs a link that can be used, for instance, to invoke a rights advisor web application to review available content reuse rights. [0017] FIG. 1 is a block schematic diagram of the system 100. The system 100 is built on top of an execution engine 106. The purpose of the execution engine 106 is to execute a sequence of one or more steps. The configurable sequence of steps to be executed is called a linking rule and is defined in the XML linking rule data 102 that is applied to the execution engine 106 as indicated schematically by arrow 104. [0018] As defined in the XML data 102, each step specifies a valid widget class name. This name can refer to any widget class that implements the ExecutableWidget interface (discussed below) and exists in the widget toolbox 108. The widget will be executed during execution of the step as schematically illustrated by arrow 110. A step definition also requires a step name, which is a character string value that is used to identify the step so the step properties and result can be referenced in subsequent steps. [0019] Further included are zero or more optional property values that are provided to the widget. These property values can include a list of input parameters including top level arguments provided by the system that invokes the linking rule. These arguments, called context variables, could include, for example, article and work metadata, such as a digital object identifier (DOI). The context variables are stored in the execution engine thread as indicated schematically by context memory 114 and provided to the execution engine 106 as indicated schematically by arrow 112. [0020] Other property values can also include literals, the output from a previous step, and Java Expression Language (JEXL) expressions. JEXL is a well-known open-source library intended to facilitate the implementation of dynamic and scripting features in applications and frameworks. More details can be found at commons.apache.org. [0021] Property values can either be static or dynamic. A static property remains fixed for each execution of the step during execution of a rule. A dynamic property is any valid JEXL expression and is resolved just prior to execution of the widget. This JEXL expression can contain references to context variables and/or other widget properties [0022] A step further defines an optional gating expression which is a JEXL expression that can access properties from any other widget that has already executed and resolves to true or false. An empty expression or any expression that resolves to true will result in the widget associated with the step executing. If the expression resolves to false, the widget will not execute. The expression is resolved at runtime so its result depends on the state of the linking rule for that invocation. [0023] In one embodiment, widgets are implemented as Java classes. Any java class can be a widget as long as it implements an ExecutableWidget interface as defined in Java. FIG. 2 illustrates the components of a widget 200. These include the widget name 202, a set of widget properties 204 and a gating expression 206. The gating expression 206 is the aforementioned JEXL expression that determines whether this widget will be executed during the execution of the linking rule. [0024] The widget further includes a set of methods 206 which are defined as follows: TABLE-US-00001 Method Description g/setName( ) Sets the name of the widget. The name can be used to identify and access properties of the widget from any other widget during rule execution g/setGatingExpression( ) Sets the gating expression g/setPropertyExpressions(List Sets the initial value of the properties 204. <PropertyExpression>) This method references a list of PropertyExpressions. A PropertyExpression is an object that contains a property name and a JEXL expression. Just before executing a widget, the execution engine evaluates each of its PropertyExpressions. The result of each expression is used to set the value of the corresponding widget property. This allows for the determination of widget property values at runtime. prepareForExecution( ) This method is called just prior to executing a widget. widget implementers can include any code in this method that must be invoked prior to widget execution. execute( ) This method is called when the execution engine executes the widget. It must return a WidgetResult object. [0025] An example widget written in the Java programming language that concatenates two character strings is shown below. TABLE-US-00002 public class Concat extends BaseWidget implements ExecutableWidget { private String part1; private String part2; @Override public WidgetResult execute( ) { if (part1 == null) { getWidgetResult( ).setFailure(getName( )+".part1 was null"); } else if (part2 == null) { getWidgetResult( ).setFailure(getName( )+".part2 was null"); } else { getWidgetResult( ).setSuccess(part1 + part2); } return getWidgetResult( ); } public String getPart1( ) { return part1; } public void setPart1(String part1) { this.part1 = part1; } public String getPart2( ) { return part2; } public void setPart2(String part2) { this.part2 = part2; } } [0026] The execution engine 106 will look on the Java classpath for all implementations of the ExecutableWidget interface when it is invoked. The result of a widget can be any java object from the Java classpath and must be wrapped within a WidgetResult object, which is a standard Java object. The WidgetResult object carries additional data about the result. For example, it carries whether the invocation succeeded, failed or was gated. It also contains a reference to the exception if one was raised while executing the widget. [0027] Using a simple graphical user interface, a user can test an individual step by providing its input arguments via the user interface. The system will display the widgets output on the screen. The user can also test a sequence of steps by providing the necessary input arguments. The system will display the output of those steps on the screen. [0028] A user can create a linking rule by selecting one or more widgets from toolbox 108, defining the input arguments for each widget and defining the order of execution. Both the input arguments and the order of execution are determined by means of XML linking rule data that is schematically illustrated as data 102 in FIG. 1. This data can be manipulated via the aforementioned graphical user interface. [0029] The final result of a rule is the same as the result of its final widget. The result is always a Java object and it is always wrapped within a conventional Java WidgetSetResult object. The WidgetSetResult object contains a status field that identifies whether all of the steps successfully executed or whether there was an error during execution. [0030] The XML data that defines an example rule 300 is illustrated in FIG. 3. The rule is defined by the parameters appearing between the "Rule" XML tags. The purpose of this rule is to concatenate two character strings, which are provided as property values to the concatenation widget described above. The rule 300 has a name 306 defined by the "Name" XML tags and at least one step defined by the parameters between the "Step" XML tags 302. In this example, there is a single step 304. Each step is defined by XML tags which are the name of the widget associated with the step. The example uses the widget class "Concat" set forth above. Thus, the XML tags are "Concat". The step 304 includes a name 308 defined by the XML "Name" tags, a gatingExpression 310, defined the "gatingExpression" name tags (which, in this example, is empty) and a set of property expressions defined by the "prop" XML tags. Each property expression has a name 312 and a JEXL based expression value 314. When this rule is executed by the execution engine 106, the property expressions are evaluated by the execution engine 106 which calls in the Concat widget the set<property expression name>( ) method with each of the property expression names and the expression values set forth in the rule XML code. Then the execute( )method of the widget is called. Execution of the rule shown in FIG. 3 returns an instance of java.lang.string containing the text `my dog Fido likes to run`. [0031] The XML data for a more complicated rule is shown in FIG. 4. This rule scrapes a Rightslink link from a web page. The rule comprises two steps. The first step retrieves a target web page on which the link is located. This is performed by the ArticleAbstractGetter step which builds a URL to the target page using article metadata, in this case, the article DOI. This DOI value is expected to be a first-level variable in the execution Context which is provided by the calling program and stored in the context memory 114 (FIG. 1). This step first builds a URL property expression 404 using a URL corresponding to the International DOI Organization and concatenating the article DOI value. The HpptGet Widget then is executed. This Widget accesses the doi.org website and fetches the target page HTML from the website without displaying it. [0032] Then, the LinkScraper step is executed. This step uses the StringFragmentExtractor Widget which extracts a string from a search string. The stringToSeach property expression 406 is set to the result of the previous step. At runtime this result contains the HTML code that was retrieved from the doi.org website by the ArticleAbstractGetter step. The startGatheringBeforeToken property value specifies the position in the HTML code at which the StringFragmentExtractor Widget begins extracting characters. This property value is set to a string constant 408 identifying where to start extracting characters. Characters are extracted until the stopGatheringBeforeToken property value is reached. This latter property value is set to another string constant 410. Other property values 412-418 which may be used in other situations are left blank and are not used in this rule. The result of executing the above rule is a java.lang.string containing the characters that form the Rightslink URL. This URL can then be used to access the rights advisor website and retrieve the available rights. [0033] The XML data defining another example rule is shown in FIGS. 5A and 5B, which when placed together form an XML code page. The rule shown in FIGS. 5A and 5B also builds a Rightslink link. The difference between this rule and the rule shown in FIG. 4 is that this rule processes a target web page that does not contain a Rightslink link as a static string so the StringFragmentExtractor Widget cannot be used to directly extract the link. On the target web page in question, the Rightslink link is constructed using Javascript on the web page. Therefore, the rule must invoke that Javascript to obtain the link. [0034] Rule 500 also uses a GetAbstractPage step 502 which, similar to the ArticleAbstractGetter step shown in FIG. 4, builds a URL to a target page using the article DOI. During the execution of this step, the HpptGet Widget is executed and accesses the doi.org website in order to fetch the target page HTML from the website without displaying it. [0035] Next, the Javascript function definition and function call are extracted from the retrieved web page HTML code by two steps, the ExtractFunctionDefinition step 504 and the ExtractFunctionCall step 506. Both of these steps use the StringFragmentExtractor Widget to selectively extract character strings from the HTML code. For example, step 504 extracts characters from the result of the GetAbstractPage step 502 as indicated at 508. The startGatheringBeforeToken property value specifies the position in the HTML code at which the StringFragmentExtractor Widget begins extracting characters. This property value is set to a string constant 510 identifying where to start extracting characters. Characters are extracted until the stopGatheringBeforeToken property value is reached. This latter property value is set to another string constant 512. [0036] Similarly, step 506 extracts characters from the web page HTML as indicated at 514. The startGatheringBeforeToken property value is set to a string constant 516 identifying where to start extracting characters. Characters are extracted until the stopGatheringBeforeToken property value is reached. This latter property value is set to another string constant 518. [0037] At this point, both the Javascript function definition and function call have been extracted. The Javascript is then run in step 520 which uses a JavascriptRunner widget, which can run Javascript from within Java using a third party library called "Rhino". The step assembles the function definition, the return value and the function call using the results of the ExtractFunctionDefinition step 504 and the ExtractFunctionCall step 506 and the JEXL concatenation operator "+" and then runs the Javascript. The result is a java.lang.string containing the characters that form the Rightslink URL. [0038] An exemplary list of Widgets which can be used to process many web pages is set forth below: TABLE-US-00003 Test Takes an JEXL expression and returns true or false depending on the value of the expression Concat Takes 2 input strings and returns them as a single concatenated string CookieSetter Takes a domain, path, and value and sets a cookie on the active HttpClient FormSubmitter Takes a chunk of html that describes a form, an action URL, and form field values. It then performs an HTTP post to the action URL along with the specified form field values. This Widget ultimately returns the html that was returned as a result of posting the form. FormToURL This Widget converts a block of form html into an equivalent Get request URL. The new URL is returned as a string. Getter This widget accepts an http URL and performs an HTTP GET. It returns a string containing the page html that was returned by the http server. HttpURLDecoder This widget takes a string and returns the same string after decoding the characters. JavascriptRunner This widget takes a block of Javascript, executes it, and returns the result. KeyValueMapper This widget takes a string and returns a corresponding value from a database table. StringFragmentExtractor This widget extracts one string from another and returns the substring. StringReplacer This widget replaces one string within a second string with a third string. The resulting string is returned. [00 James Arbo, Chelmsford, MA US Patent applications by Copyright Clearance Center,:
http://www.faqs.org/patents/app/20130036350
CC-MAIN-2015-22
refinedweb
4,441
50.26
Making Code Faster: Going Down the I/O Chute Making Code Faster: Going Down the I/O Chute Ayende Rahien continues his series about making code faster in terms of input and output. Join the DZone community and get the full member experience.Join For Free After introducing the problem and doing some very obvious things, and then doing some pretty non-obvious things, we have managed to get to one-eighth of the initial time of the original implementation. We can do better still. So far, we relied heavily on the File.ReadLines method, which handles quite a lot of the parsing complexity for us. However, that would still allocate a string per line, and our parsing relied on us splitting the strings again, meaning more allocations. We can take advantage of our knowledge of the file to do better. The code size blows up, but it is mostly very simple. We create a dedicated record reader class that will read each line of the file with a minimum of allocations. public class RecordReader : IDisposable { public long Duration; public long Id; private readonly StreamReader _streamReader; private const int SizeOfDate = 19;// 2015-01-01T16:44:31 private const int SizeOfSpace = 1; private const int SizeOfId = 8; // 00043064 private const int SizeOfNewLine = 2; // \r\n private const int SizeOfRecord = SizeOfDate + SizeOfSpace + SizeOfDate + SizeOfSpace + SizeOfId + SizeOfNewLine; private readonly char[] _buffer = new char[SizeOfRecord]; public RecordReader(string file) { _streamReader = new StreamReader(file); } public bool MoveNext() { int sizeRemaining = _buffer.Length; int index = 0; while (sizeRemaining > 0) { var read = _streamReader.ReadBlock(_buffer, index, sizeRemaining); if (read == 0) return false; index += read; sizeRemaining -= read; } Duration = (ParseTime(20) - ParseTime(0)).Ticks; Id = ParseInt(40, 8); return true; } private DateTime ParseTime(int pos) { var year = ParseInt(pos, 4); var month = ParseInt(pos + 5, 2); var day = ParseInt(pos + 8, 2); var hour = ParseInt(pos + 11, 2); var min = ParseInt(pos + 14, 2); var sec = ParseInt(pos + 17, 2); return new DateTime(year, month, day, hour, min, sec); } private int ParseInt(int pos, int size) { var val = 0; for (int i = pos; i < pos + size; i++) { val *= 10; val += _buffer[i] - '0'; } return val; } public void Dispose() { _streamReader.Dispose(); } } There is a nontrivial amount of stuff going on here. We start by noting that the size in character of the data is fixed, so we can compute the size of a record very easily. Each record is exactly 50 bytes long. The key parts here is that we are allocating a single buffer variable, which will hold the line characters. Then we just wrote our own date and integer parsing routines that are very trivial, specific to our case and most importantly, don’t require us to allocate additional strings. Using this code is done with: var stats = new Dictionary<long, FastRecord>(); using (var reader = new RecordReader(args[0])) { while (reader.MoveNext()) { FastRecord value; if (stats.TryGetValue(reader.Id, out value) == false) { stats[reader.Id] = value = new FastRecord { Id = reader.Id }; } value.DurationInTicks += reader.Duration; } } So, we are back to single-threaded mode. Running this code gives us a runtime of 1.7 seconds, 126 MB allocated and a peak working set of 35 MB. We are now about 2.5 times faster than previous parallel version, and over 17 times faster than the original version. Making this code parallel is fairly trivial now; divide the file into sections and have a record reader on each section. However, is there really much point at this stage? Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/making-code-faster-going-down-the-io-chute
CC-MAIN-2019-26
refinedweb
597
53.71
Other AliasTcl_FindSymbol SYNOPSIS #include <tcl.h> int Tcl_LoadFile(interp, pathPtr, symbols, flags, procPtrs, loadHandlePtr) void * Tcl_FindSymbol(interp, loadHandle, symbol) ARGUMENTS - - Tcl_Interp *interp (in) Interpreter to use for reporting error messages. - - Tcl_Obj *pathPtr (in) The name of the file to load. If it is a single name, the library search path of the current environment will be used to resolve it. - - const char *const symbols[] (in) Array of names of symbols to be resolved during the load of the library, or NULL if no symbols are to be resolved. If an array is given, the last entry in the array must be NULL. - - int flags (in) The value should normally be 0, but TCL_LOAD_GLOBAL or TCL_LOAD_LAZY or a combination of those two is allowed as well. - - void *procPtrs (out) Points to an array that will hold the addresses of the functions described in the symbols argument. Should be NULL if no symbols are to be resolved. - - Tcl_LoadHandle *loadHandlePtr (out) Points to a variable that will hold the handle to the abstract token describing the library that has been loaded. - - Tcl_LoadHandle loadHandle (in) Abstract token describing the library to look up a symbol in. - - const char *symbol (in) The name of the symbol to look up. DESCRIPTION Tcl_LoadFile loads a file from the filesystem (including potentially any virtual filesystem that has been installed) and provides a handle to it that may be used in further operations. The symbols array, if non-NULL, supplies a set of names of symbols (typically functions) that must be resolved from the library and which will be stored in the array indicated by procPtrs. If any of the symbols is not resolved, the loading of the file will fail with an error message left in the interpreter (if that is non-NULL). The result of Tcl_LoadFile is a standard Tcl error code. The library may be unloaded with Tcl_FSUnloadFile. Tcl_FindSymbol locates a symbol in a loaded library and returns it. If the symbol cannot be found, it returns NULL and sets an error message in the given interp (if that is non-NULL). Note that it is unsafe to use this operation on a handle that has been passed to Tcl_FSUnloadFile. KEYWORDSbinary code, loading, shared library
https://manpages.org/tcl_loadfile/3
CC-MAIN-2022-21
refinedweb
369
62.38
I was trying to look for a Bidirectional/Omnidirectional Queue to send jobs back and forth between processes. the best solution I could come up with was to use two multiprocessing queues that are filled from one process and read through the other (or a Pipe which is apparently faster, still haven't tried it yet). I came across this answer that describes the difference between a Pipe and a Queue, it states that A Queue() can have multiple producers and consumers. I know a queue can be shared between multiple processes( > 2 processes ), but how should I organize the communication between the processes so that a message has a targeted process, or at least the process does not read the jobs it inserted to the queue, and how I scale it to more than 2 processes. EX: I have 2 (or more) Processes (A, B) they they share the same Queue, A needs to send a job to B and B sends a job to A, if I simply use queue.put(job), the job might be read from either processes depending on who called queue.get() first, so the job that was put by A intended to B might be read by A, which is not the targeted process, if I added a flag of which process it should be executed by, it would destroy the sequentiality of the queue. For those facing the same problem, I have found the solution, it is multiprocessing.Pipe() it is faster than queues but it only works if you have 2 processes. Here is a simple example to help import multiprocessing as mp from time import time def process1_function(conn, events): for event in events: # send jobs to the process_2 conn.send((event, time())) print(f"Event Sent: {event}") # check if there are any messages in the pipe from process_2 if conn.poll(): # read the message from process_2 print(conn.recv()) # continue checking the messages in the pipe from process_2 while conn.poll(): print(conn.recv()) def process2_function(conn): while True: # check if there are any messages in the pipe from process_1 if conn.poll(): # read messages in the pipe from process_1 event, sent = conn.recv() # send messages to process_1 conn.send(f"{event} complete, {time() - sent}") if event == "eod": break conn.send("all events finished") def run(): events = ["get up", "brush your teeth", "shower", "work", "eod"] conn1, conn2 = mp.Pipe() process_1 = mp.Process(target=process1_function, args=(conn1, events)) process_2 = mp.Process(target=process2_function, args=(conn2,)) process_1.start() process_2.start() process_1.join() process_2.join() if __name__ == "__main__": run() External links referenced by this document:
https://programmatic.solutions/gfz86u/python-multiprocessing-controlled-bidirectional-queue
CC-MAIN-2022-40
refinedweb
433
70.13
EDIT: after many hours, I've found out that the problem has nothing to do with Eucalyptus. It looks like the image is buggy. Very, very buggy. More details in the end. I didn't manage to fix it, and I will file a bug. EDIT 2: I managed to fix it, it apparently works. I have a 4-machine cluster running Ubuntu Server Natty (11.04) x64. I've installed "Ubuntu Enterprise Cloud" from the installtion CD (then updated it) on each of these machines. The cloud seems to work fine, I have lots of virtual machines running Natty servers on them. Now I'd like to run Oneiric in a virtual machine, but somehow I can't. I downloaded Oneiric's (x64) image from, published it (uec-publish-tarball oneiric-server-cloudimg-amd64.tar.gz oneiric-server-cloudimg-amd64) exactly as I did with Natty, then tried to launch an instance (euca-run-instances -n 1 -k my-key -t m1.small -z my-cloud emi-XXXXXXXX) using Oneiric's image, but the instance is not able to boot. uec-publish-tarball oneiric-server-cloudimg-amd64.tar.gz oneiric-server-cloudimg-amd64 euca-run-instances -n 1 -k my-key -t m1.small -z my-cloud emi-XXXXXXXX With euca-get-console-output I get the following: euca-get-console-output [ 0.461269] VFS: Cannot open root device "sda1" or unknown-block(0,0) [ 0.462388] Please append a correct "root=" boot option; here are the available partitions: [ 0.463855] Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(0,0) [ 0.465331] Pid: 1, comm: swapper Not tainted 3.0.0-13-generic #22-Ubuntu [ 0.466526] Call Trace: [ 0.466989] [<ffffffff815d3ee5>] panic+0x91/0x194 [ 0.467860] [<ffffffff81ad1031>] mount_block_root+0xdc/0x18e [ 0.468891] [<ffffffff81ad126a>] mount_root+0x54/0x59 [ 0.469829] [<ffffffff81ad13dc>] prepare_namespace+0x16d/0x1a7 [ 0.470883] [<ffffffff81ad0d76>] kernel_init+0x140/0x145 [ 0.471837] [<ffffffff815f38e4>] kernel_thread_helper+0x4/0x10 [ 0.472889] [<ffffffff81ad0c36>] ? start_kernel+0x3df/0x3df [ 0.473884] [<ffffffff815f38e0>] ? gs_change+0x13/0x13 The filesystem is labeled "cloudimg-rootfs", inside the image both /etc/fstab and /boot/grub/grub.cfg always refer to the image by the label, everything seems to be correct, yet the kernel says it can't find the root file system. I've spent many hours googling, but nothing came out. I've asked on #ubuntu-server, but nobody knew what to do. I've asked on #eucalyptus but got no answer at all. Any ideas on why this is happening and how to solve it? Thanks EDIT: after many hours, I've found out that the problem has nothing to do with Eucalyptus. It looks like the image is buggy. Very, very buggy. The first problem is that the Kernel in the image is a -generic kernel, while I suppose it should be a -virtual one. I chrooted into the image, removed the -generic packages, replaced it with the -virtual ones. Then I extracted the new kernel (and replaced the original one (-generic) that came with the tarball) because I need it when I publish and launch an image with Eucalyptus. -generic -virtual The problem described above was solved. But then, the console started showing this: mount: mount point ext4 does not exist If you check the /etc/fstab file in the image, it says: LABEL=cloudimg-rootfs ext4 defaults 0 1 Damnt, where's my mount point? Note that it is missing /proc as well. /proc Well, when you think it is over, you will notice that your instance will have no network connectivity. Let's check /etc/network/interface: # interfaces(5) file used by ifup(8) and ifdown(8) auto lo iface lo inet loopback Oh my! It is missing eth0... here I stopped. I can't take no more. I give up. Looks like Canonical has just forgotten to properly set up this image. At first, I though: "have I downloaded a server image by mistake?", but no, I double checked. It is really the cloud image, it has even "cloud-init" installed (which is not, by default, on server images). They just forgot to prepare it. I will file a bug (and reference it here once this is done), and hope they fix it soon! EDIT 2: it looks like the network configuration was the last thing missing. I decided to test it with the fixes above, and it booted properly! However, I haven't got the slightest idea if the image is now good to go... The bug report is at: I hope it gets fixed soon! By posting your answer, you agree to the privacy policy and terms of service. asked 4 years ago viewed 316 times active
http://serverfault.com/questions/335076/cant-launch-oneiric-x64-instance-on-eucalyptus/335125
CC-MAIN-2016-26
refinedweb
780
77.03
. - cosysop is a group for trusted community members which also allows editing most protected pages such as those in the DeveloperWiki namespace. - sysop is a group for highly trusted users who are responsible for critical wiki-administrative tasks like page deletion or user blocking, thus requiring the demonstration of extensive knowledge of how the wiki is organized. They also have all rights of the checkuser group whicher is a group for the ArchWiki:Maintenance Team members. - All maintainers are given the cosysop access level by default. Maintainers with the sysop access level are called administrators. - translator is a group for the most productive members of an ArchWiki Translation Team or individual translators. - archdev is a group for Arch Developers. - All archdevs are given the cosysop access level by default. - archtu is a group for Arch Trusted Users. - archstaff is a group for users with other roles within the Arch Linux community.
https://wiki.archlinux.org/index.php/ArchWiki:Access_levels_and_roles
CC-MAIN-2019-22
refinedweb
151
56.35
This program is supposed to function as a "guessing game". A user guesses a number between 1000 and 9999 and the program guesses a number, the user then tells how many digits in the program's "guess" match the number of digits the user was thinking of. Then it guesses again with a modified result, until it guesses the correct answer or determines the number can't exist. My program is built to have all possible numbers (1000 through 9999) in an arraylist and, upon getting the number of matches, to delete any numbers that don't match it. I go about this by putting the number that the computer guessed along with the first possible number into two arrays of length four (so each digit has its own index), then counting the number of matches and deleting the current number if the matches aren't the same as what the user input. However, it simply doesn't go about the process like I believe it should. I would appreciate any help you could give in hinting to me where the problem is. The second half of the program (separated by a line break) was given to us and shouldn't be changed, it is what we work off of to create the methods and functions. Thanks for any help! Code:import java.util.ArrayList; import java.util.Random; import javax.swing.JOptionPane; public class Assignment2 { public int totalGuesses = 0; public int guess; Random rand = new Random(); ArrayList<Integer> numbers = new ArrayList<Integer>(); public Assignment2 ( ){ for(int j = 1000; j<=9999; j++){ numbers.add(j);} } public int myGuessIs() { if(numbers.size() !=0){ guess = numbers.get((int) (rand.nextInt(numbers.size()-1))).intValue(); totalGuesses++;} else{guess = -1;} return guess; } public int totalNumGuesses() { return totalGuesses; } public void updateMyGuess(int nmatches) { int modnumbers; int modguess = guess; int tempmodnumbers; int tempmodguess; int matches; for(int j = 0; j<numbers.size(); j++){ matches = 0; modnumbers = numbers.get(j).intValue(); for(int i = 3; i>=0; i--){ tempmodnumbers = modnumbers%10; modnumbers = modnumbers/10; tempmodguess = modguess%10; modguess = modguess/10; if(tempmodnumbers == tempmodguess){ matches++;} } if(matches != nmatches){ numbers.remove(j); j--; } else{System.out.println(numbers.get(j));} } } // fill in code here (optional) // feel free to add more methods as needed // you shouldn't need to change the main function public static void main(String[] args) { Assignment2 gamer = new Assignment2( ); JOptionPane.showMessageDialog(null, "Think of a number between 1000 and 9999.\n Click OK when you are ready...", "Let's play a game", JOptionPane.INFORMATION_MESSAGE); int numMatches = 0; int myguess = 0; do { myguess = gamer.myGuessIs(); if (myguess == -1) { JOptionPane.showMessageDialog(null, "I don't think your number exists.\n I could be wrong though...", "Mistake", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } String userInput = JOptionPane.showInputDialog("I guess your number is " + myguess + ". How many digits did I guess correctly?"); // quit if the user input nothing (such as pressed ESC) if (userInput == null) System.exit(0); // parse user input, pop up a warning message if the input is invalid try { numMatches = Integer.parseInt(userInput.trim()); } catch(Exception exception) { JOptionPane.showMessageDialog(null, "Your input is invalid. Please enter a number between 0 and 4", "Warning", JOptionPane.WARNING_MESSAGE); numMatches = 0; } // the number of matches must be between 0 and 4 if (numMatches < 0 || numMatches > 4) { JOptionPane.showMessageDialog(null, "Your input is invalid. Please enter a number between 0 and 4", "Warning", JOptionPane.WARNING_MESSAGE); numMatches = 0; } if (numMatches == 4) break; // update based on user input gamer.updateMyGuess(numMatches); } while (true); // the game ends when the user says all 4 digits are correct System.out.println("Aha, I got it, your number is " + myguess + "."); System.out.println("I did it in " + gamer.totalNumGuesses() + " turns."); } }
http://forums.devshed.com/java-help/675104-homework-creating-game-program-post2411013.html
CC-MAIN-2019-22
refinedweb
610
50.12
Re: Decompiler.NET reverse engineers your CLS compliant code From: Shawn B. (leabre_at_html.com) Date: 09/24/04 - ] Date: Fri, 24 Sep 2004 11:28:43 -0700 > > see it as tying to a specific machine. What happens if you go out of > > business in 2 years? > > That won't happen. We're also only charging $500, not 5 million. There is as > much of a risk that you may get hit by a bus tomorrow and won't need the > software anymore. How do you know that won't happen? Because you don't want it to? There have been many many 3rd parties and small software vendors and large ones that have come and gone. I'm not saying that will happen to you, but I'm saying the possibility exists. For as long as the use of the software depends on the existence of the vendor, that software has a very high risk of becoming useless in the unfortunate case that the vendor dissappears. Again, I'm not saying it will happen to you, but there aren't many software vendors that don't eventually go the way of the do-do bird without becoming the largest entity in the niche you are targeting or being purchased by a larger company. Who's to say that larger company will continue to support the product? If the licensing didn't require such a strict lockdown, it wouldn't be a problem. But because the ability to use the software depends on a particular companies existance, it is a very high risk for me to purcahse *any* product that follows suit (not just yours). Alos, with new laws being passed every day, you could become outlawed and thus, out of business, or arrested, or whatever, for providing a tool that can potentially be used maliciously for whatever reason the media/software industry decides is harmful to them... they have a powerful lobby, how powerful is yours? The point is it is a risk to spend any money on software that depends on the vendors existence to continue usage. A risk that it too great for my pocket book. Nothing personal. > > Besides, I didn't say I'd write my own decompiler, I just said if it was > > that important I could, I'm more than capable, its just not a priority and > > since I don't decompile non System.* assemblies, the price is not > > justifyable. > > > > We spent over two years writing ours. I imaging that two years of your time > is worth more to you than the $500 we charge for a license which our > costomers feel is a tremendous value to them. I don't doubt you spent 2 years on this. My time is worth more, but then again, since I only occasionaly review the System.* namespaces, $500 isn't worth it to me. If I was going to look at some proprietary code other than System.*, perhaps it would be. But if I was going to do that, I would just create my own version and learn how to imitate a feature and learn from it, rather than "cheat" and take the easy way out. Of course, since I'm dependant on the System.* namespaces, I have no problem examining something when I'm not sure about the documentation. Would I pay $500 for that? No. It isn't *that* important. With Reflector, it is a convenience that I exploit. Nothing more. There's always Mono, but I'm much less inclined to actually look at GPL code (I generally avoid it for reasons I won't discuss in this thread). Besides that, Mono may not be programmed exactly the way that the System.* classes are. > > I'm not fine with being actively dependant on a vendor in > > order to keep using the software despite all of my requirements. > > You are not if you don't replace your motherboard or machine itself. Tivo > doesn't even let you move your lifetime subscriptions to newer hardware that > they themselves sell. I don't use Tivo so I wouldn't know. But we're not talking about hardware here, we're talking about software. > > I just happen to dissagree > > with that kind of licensing. It does nothing to keep prices low > > Pirated copied cause vendots to raise their prices for their software since > their target market is cannibalized. Locking down licensed copies to > hardware reduces the amount of software piracy and therefore does keep > prices lower that without it.Although you may feel that $500 is high, we > intenitionally priced our product much lower than the cost to develop it to > make it accessible to small developers like yourself who might benefit from > it. If Reflector also charged $500 and there weren't any free choices > available with relatively good decompilation capability, you would probably > feel differently towards our product and be glad that a product like it was > available to you instead of having to invest the two years yourself trying > to write your own decompiler that works as well. Name one commercial product that every lowered its price because they got piracy under control. No, what actually happens is they complain more and then justify the higher prices because they have to spend more money on R&D to contantly come up with new anti-piracy measures. Now that they have the average user inconvenienced and have thwarted "casual" sharing, prices aren't any lower than they were previously. But the true pirate still has no problems getting around it. Again, if Reflector wasn't free, I agree, I wouldn't be using it. I wouldn't be purchasing any tool to do the job, anyway. I can read IL, I would be inconvenienced, but I can do it (I program in it sometimes, probly because I program Win32 in assembly also) but, if I wasn't "restricted" to my initial machine which changes often and "dependant" on a vendor, I might consider it. But since we're going in circles here, there's no more point in elaborating why I don't purchase your product or any other that causes me to be dependant on them and screwed, blued, and tattoo'd if they go out of business. You obviously feel justified and confident in your product and licensing terms, and I obviously feel like it creates a severe financial risk for me to use the product and nothing is going to change that. If the entire software industry follows suit, I'll use less software or will eventually move to Free software (free as in beer, free as in speech) because I just happen to refuse dependance on any particular non-Microsoft software vendor. It has nothing to do with you, it has everything to do with my freedom and getting value out of my hard-earned money. Thanks, Shawn - ]
http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.languages.vb/2004-09/4817.html
crawl-002
refinedweb
1,145
69.01
In this section, you will learn how to parse file with several delimiters and line feeders. We have used BufferedReader class in order to read the file. All the delimiters and the line feeders have been replaced using regular expression with replaceAll() method and replace() method and we get the values present between the tags, spaces etc. Here is the file.txt: Here is the code: import java.io.*; import java.util.regex.*; public class Read { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new FileReader("C:\\file.txt")); String line; String data = ""; while ((line = bf.readLine()) != null) { String replacedData = line.replaceAll("[|,|:|/|\\|\'><*}{^();]", " ").replaceAll("\"", "").replace('[', ' ').replace(']', ' '); System.out.println(replacedData); } } } Output: cr lf lf rsphdr cr lf M ctag COMPLD cr lf aid aidtype ntfcncde condtype srveff ocrdat ocrtm locn dirn tmper conddescr aiddet obsdbhvr exptdbhvr dgntype tblislt cr lf Advertisements Posted on: November
http://www.roseindia.net/tutorial/java/io/parseFile.html
CC-MAIN-2017-17
refinedweb
147
56.45
The function "view(" doesn't seem to work with jupyter notebook I'm sorry if the question was already answered somewhere, but I did not find out an answer by myself: In the "old" sagemath notebooks, there was a function "view" to display latex that MathJax cannot display. For instance the sage documentation proposes the following: from sage.graphs.graph_latex import setup_latex_preamble setup_latex_preamble() latex.engine('pdflatex') latex.add_to_mathjax_avoid_list('tikzpicture') view(graphs.CompleteGraph(4)) - In the "old" sage notebook, this produces a png version of a graph (compiled from latex), which is inserted into the output of the cell - In the Jupyter netbook, by contrast, it opens a pdf version of the graph into an external window. Is there some way to obtain, in the Jupyter notebook, the same behaviour as in the "old netbook" ? Thanks Actually, the example graphs.CompleteGraph(4)is a bad example because pretty_print already does what I wish, for this example (it is the example that was in the documentation of sage). But the question remains with, for instance view(Tableau([[1,2],[3]])), for which pretty_print doesn't work (due to limitation of MathJax with respect to tables). But if someone is able to explain to me how pretty_print(graphs.CompleteGraph(4))works, that will already be something (it displays more than what latex(graphs.CompleteGraph(4))has).
https://ask.sagemath.org/question/49209/the-function-view-doesnt-seem-to-work-with-jupyter-notebook/
CC-MAIN-2021-17
refinedweb
223
51.58
Hi, > This is assuming that someone would use both Adobe and Apache spark > components Which is very likely as initially the apache set of components are going to be small in number and would be used with other spark or mx components. > It's 4 extra lines of code. Why is this a bad situation? It not bad as such. I just thought it would be nice not to have to specify those lines of code over again in multiple files in a single project. It something that bugs me a little. > What is "a" for? An Apache version of FX? Sorry to be naïve. New apache components. Neither fx or mx nor sparc. Doesn't have to be "a" as you can name name spaces anything, "as" and "asf" have also been suggested. Previous discussion around name spaces concluded to put all new components into an name space while they can be worked on before decided if they should go into the spark or mx space or a new name space. It has been decided that having real URLs in as the namespace is a good idea. It hasn't been decided if we should just have a apache namespace and a temporary name space or just use a single namespace for both. ie components will stay in the apache namespace if they don't fit in with spark or mx once it been decided they are good enough. Was also suggested that we have a namespace for incubation and for after we graduate (so the URLs are correct and point somewhere real). It's also suggested an apache mx name space and spark name space but there seems a little resistance to that. Hopefully I've got all that correct. Thanks, Justin
http://mail-archives.apache.org/mod_mbox/incubator-flex-dev/201203.mbox/%3CD6CA3C15-4EAA-4F44-BE8C-DBF888C528D5@classsoftware.com%3E
CC-MAIN-2014-23
refinedweb
294
81.43
Java file FAQ: Can you share some examples of the Java BufferedReader class? Sure. When it comes to reading character input streams, the Java BufferedReader class is extremely important, and I'll demonstrate this in several different source code examples.Back to top Using a Java BufferedReader with a FileReader I'll start with what might be the most common use of the BufferedReader class, using it with a FileReader to read a text file. (This code comes from my earlier "How to open and read a file with Java" tutorial.) The following method demonstrates my usual Java file-reading approach, including the Java 5 syntax:; } Again, this is the usual approach I take with Java to read a text file from a filesystem. I start with a FileReader, so it's important to understand how that class works. As the FileReader javadoc states: The FileReader ... is a convenience class for reading character files ... FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using a FileInputStream. Why both BufferedReader and FileReader? I wrap a BufferedReader around the FileReader for two reasons. First, the BufferedReader does what its name implies, buffering the input to make the reading process much faster. Second, the BufferedReader provides a readLine method which converts each line of input into a Java String, and greatly simplifies the file-reading process, as you saw in that previous example. Regarding the buffering process, here are a few lines from the BufferedReader javadoc:. Before I leave this example, I should also restate a line I included in the documentation above: The BufferedReader readLine method returns null when there is nothing else to read. Because of that behavior, it's very common to write a while loop that iterates over a BufferedReader as shown in the example above, and again here: while ((line = bufferedReader.readLine()) != null) Again, the BufferedReader readLine method either returns a String or a null reference, and it's a great convenience method to use when reading text input like this. Using a BufferedReader with System.in and an InputStreamReader It's also common to use the Java BufferedReader with an InputStreamReader. We saw this mentioned in the BufferedReader javadoc statement above, and now I'll share an example where I wrap a BufferedReader around an InputStreamReader to read from System.in. The following code comes from my "How to read command-line input with Java" tutorial. I've simplified that code and added some documentation to it so you can see how to wrap a BufferedReader around an InputStreamReader (which in turn is already wrapped around System.in): import java.io.*; public class JavaBufferedReaderSystemInExample { public static void main (String[] args) throws Exception { String userName = null; // prompt the user to enter their name System.out.print("Enter your name: "); // open up standard input, and buffer it BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); // use the readLine method of the BufferedReader class // to get whatever line the user types in: userName = bufferedReader.readLine(); System.out.println("Thanks for the name, " + userName); } } I hope the comments in the code cover what I'm doing in this code, but if you'd like more information, please visit my "How to read command line input with Java" tutorial.Back to top Using a Java BufferedReader with a URLConnection As one final BufferedReader example, the following code snippet again shows how to wrap a BufferedReader around an InputStreamReader, but in this case the InputStreamReader is wrapped around the input stream from a Java URLConnection: URL url = new URL(theUrl); URLConnection urlConnection = url.openConnection(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line; while ((line = bufferedReader.readLine()) != null) { content.append(line + "\n"); } bufferedReader.close(); As you can see, once you wrap a BufferedReader around an InputStreamReader, the rest of our code is very similar. As mentioned earlier, I usually just try to get to a point where I can use the BufferedReader readLine method. I think of that as a convenience method that makes reading from a file, standard input, or an internet connection (URL or socket) much easier. If you're interested in more details on this last BufferedReader example, I took that code snippet from my "How to open and read content from a URL with Java" tutorial, and there's much more discussion in that tutorial. Java BufferedReader summary As you've seen, the common thread around all of these examples is wrapping a BufferedReader around an InputStream, and then using the BufferedReader readLine method to simplify the process of reading the input as a series of Strings. Although I haven't discussed it in great length, the BufferedReader does what its name implies, buffering the input to make reading much faster. In tests I conducted before the Java 5 days, using a BufferedReader made file reading at least ten times faster than using a non-buffered approach. For more information on the Java BufferedReader class, please visit the BufferedReader javadoc link shown above, or the links to any of my other BufferedReader-related tutorials shared above.Back to top Share it! There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al. Add new comment
http://alvinalexander.com/java/java-bufferedreader-readline-string-examples
CC-MAIN-2017-22
refinedweb
878
51.89
Table Of Contents Properties¶ The Properties classes are used when you create an EventDispatcher. Warning Kivy’s Properties are not to be confused with Python’s properties (i.e. the @property decorator and the <property> type). Kivy’s property classes support: - Value Checking / Validation - When you assign a new value to a property, the value is checked against validation constraints. For example, validation for an OptionPropertywill make sure that the value is in a predefined list of possibilities. Validation for a NumericPropertywill check that your value is a numeric type. This prevents many errors early on. - Observer Pattern - You can specify what should happen when a property’s value changes. You can bind your own function as a callback to changes of a Property. If, for example, you want a piece of code to be called when a widget’s posproperty changes, you can binda function to it. - Better Memory Management - The same instance of a property is shared across multiple widget instances. Comparison Python vs. Kivy¶ Basic example¶ Let’s compare Python and Kivy properties by creating a Python class with ‘a’ as a float property: class MyClass(object): def __init__(self, a=1.0): super(MyClass, self).__init__() self.a = a With Kivy, you can do: class MyClass(EventDispatcher): a = NumericProperty(1.0). Value checking¶ If you wanted to add a check for a minimum / maximum value allowed for a property, here is a possible implementation in Python: class MyClass(object): def __init__(self, a=1): super(MyClass, self).__init__() self.a_min = 0 self.a_max = 100 self.a = a def _get_a(self): return self._a def _set_a(self, value): if value < self.a_min or value > self.a_max: raise ValueError('a out of bounds') self._a = value a = property(_get_a, _set_a) The disadvantage is you have to do that work yourself. And it becomes laborious and complex if you have many properties. With Kivy, you can simplify the process: class MyClass(EventDispatcher): a = BoundedNumericProperty(1, min=0, max=100) That’s all! Error Handling¶ If setting a value would otherwise raise a ValueError, you have two options to handle the error gracefully within the property. The first option is to use an errorvalue parameter. An errorvalue is a substitute for the invalid value: # simply returns 0 if the value exceeds the bounds bnp = BoundedNumericProperty(0, min=-500, max=500, errorvalue=0) The second option in to use an errorhandler parameter. An errorhandler is a callable (single argument function or lambda) which can return a valid substitute: # returns the boundary value when exceeded bnp = BoundedNumericProperty(0, min=-500, max=500, errorhandler=lambda x: 500 if x > 500 else -500) Observe Property changes¶ As we said in the beginning, Kivy’s Properties implement the Observer pattern. That means you can bind() to a property and have your own function called when the value changes. There are multiple ways to observe the changes. Observe using bind()¶ You can observe a property change by using the bind() method outside of the class: class MyClass(EventDispatcher): a = NumericProperty(1) def callback(instance, value): print('My callback is call from', instance) print('and the a value changed to', value) ins = MyClass() ins.bind(a=callback) # At this point, any change to the a property will call your callback. ins.a = 5 # callback called ins.a = 5 # callback not called, because the value did not change ins.a = -1 # callback called Note Property objects live at the class level and manage the values attached to instances. Re-assigning at class level will remove the Property. For example, continuing with the code above, MyClass.a = 5 replaces the property object with a simple int. Observe using ‘on_<propname>’¶ If you defined the class yourself, you can use the ‘on_<propname>’ callback: class MyClass(EventDispatcher): a = NumericProperty(1) def on_a(self, instance, value): print('My property a changed to', value) Warning Be careful with ‘on_<propname>’. If you are creating such a callback on a property you are inheriting, you must not forget to call the superclass function too. Binding to properties of properties.¶ When binding to a property of a property, for example binding to a numeric property of an object saved in a object property, updating the object property to point to a new object will not re-bind the numeric property to the new object. For example: <MyWidget>: Label: id: first text: 'First label' Label: id: second text: 'Second label' Button: label: first text: self.label.text on_press: self.label = second When clicking on the button, although the label object property has changed to the second widget, the button text will not change because it is bound to the text property of the first label directly. In 1.9.0, the rebind option has been introduced that will allow the automatic updating of the text when label is changed, provided it was enabled. See ObjectProperty. - class kivy.properties. Property¶ Bases: builtins.object Base class for building more complex properties. the StringProperty will check the default value. None is a special case: you can set the default value of a Property to None, but you can’t set None to a property afterward. If you really want to do that, you must declare the Property with allownone=True: class MyObject(Widget): hello = ObjectProperty(None, allownone=True) # then later a = MyObject() a.hello = 'bleh' # working a.hello = None # working too, because allownone is True. Changed in version 1.4.2: Parameters errorhandler and errorvalue added Changed in version 1.9.0: Parameter force_dispatch added dispatch()¶ Dispatch the value change to all observers. Changed in version 1.1.0: The method is now accessible from Python. This can be used to force the dispatch of the property, even if the value didn’t change: button = Button() # get the Property class instance prop = button.property('text') # dispatch this property on the button instance prop.dispatch(button) fbind()¶ Similar to bind, except it doesn’t check if the observer already exists. It also expands and forwards largs and kwargs to the callback. funbind or unbind_uid should be called when unbinding. It returns a unique positive uid to be used with unbind_uid. funbind()¶ Remove the observer from our widget observer list bound with fbind. It removes the first match it finds, as opposed to unbind which searches for all matches. link()¶ Link the instance with its real name. Warning Internal usage only. When a widget is defined and uses a Propertyclass, the creation of the property object happens, but the instance doesn’t know anything about its name in the widget class: class MyWidget(Widget): uid = NumericProperty(0) In this example, the uid will be a NumericProperty() instance, but the property instance doesn’t know its name. That’s why link()is used in Widget.__new__. The link function is also used to create the storage space of the property for this specific widget instance. - class kivy.properties. NumericProperty¶ Bases: kivy.properties.Property Property that represents a numeric value. >>> wid = Widget() >>> wid.x = 42 >>> print(wid.x) 42 >>> wid.x = "plop" Traceback (most recent call last): File "<stdin>", line 1, in <module> File "properties.pyx", line 93, in kivy.properties.Property.__set__ File "properties.pyx", line 111, in kivy.properties.Property.set File "properties.pyx", line 159, in kivy.properties.NumericProperty.check ValueError: NumericProperty accept only int/float Changed in version 1.4.1: NumericProperty can now accept custom text and tuple value to indicate a type, like “in”, “pt”, “px”, “cm”, “mm”, in the format: ‘10pt’ or (10, ‘pt’). - class kivy.properties. StringProperty¶ Bases: kivy.properties.Property Property that represents a string value. - class kivy.properties. ListProperty¶ Bases: kivy.properties.Property Property that represents a list.. ObjectProperty¶ Bases: kivy.properties.Property Property that represents a Python object. Warning To mark the property as changed, you must reassign a new python object. Changed in version 1.9.0: rebind has been introduced. Changed in version 1.7.0: baseclass parameter added. - class kivy.properties. BooleanProperty¶ Bases: kivy.properties.Property Property that represents only a boolean value. - class kivy.properties. BoundedNumericProperty¶ Bases: kivy.properties.Property Property that represents a numeric value within a minimum bound and/or maximum bound – within a numeric range. get_max()¶ Return the maximum value acceptable for the BoundedNumericProperty in obj. Return None if no maximum value is set. Check get_minfor a usage example. New in version 1.1.0. get_min()¶ Return the minimum value acceptable for the BoundedNumericProperty in obj. Return None if no minimum value is set: class MyWidget(Widget): number = BoundedNumericProperty(0, min=-5, max=5) widget = MyWidget() print(widget.property('number').get_min(widget)) # will output -5 New in version 1.1.0. set_max(. OptionProperty¶ Bases: kivy.properties.Property Property that represents a string from a predefined list of valid options. If the string set in the property is not in the list of valid options (passed at property creation time), a ValueError exception will be raised. For example: class MyWidget(Widget): state = OptionProperty("None", options=["On", "Off", "None"]) - class kivy.properties. ReferenceListProperty¶ Bases: kivy.properties.Property Property that allows the creation of a tuple of other properties. For example, if x and y are NumericPropertys, we can create a ReferenceListPropertyfor the pos. If you change the value of pos, it will automatically change the values of x and y accordingly. If you read the value of pos, it will return a tuple with the values of x and y. For example: class MyWidget(EventDispatcher): x = NumericProperty(0) y = NumericProperty(0) pos = ReferenceListProperty(x, y) - class kivy.properties. AliasProperty¶ Bases: kivy.properties.Property Create a property with a custom getter and setter. If you don’t find a Property class that fits to your needs, you can make your own by creating custom Python getter and setter methods. Example from kivy/uix/widget.py: def get_right(self): return self.x + self.width def set_right(self, value): self.x = value - self.width right = AliasProperty(get_right, set_right, bind=['x', 'width']) Changed in version 1. VariableListProperty¶ Bases: kivy.properties.Property A ListProperty that allows you to work with a variable amount of list items and to expand them to the desired list size. For example, GridLayout’s padding used to just accept one numeric value which was applied equally to the left, top, right and bottom of the GridLayout. Now padding can be given one, two or four values, which are expanded into a length four list [left, top, right, bottom] and stored in the property. Keeping in mind that the default list is expanded to a list of length 4, here are some examples of how VariabelListProperty’s are handled. - VariableListProperty([1]) represents [1, 1, 1, 1]. - VariableListProperty([1, 2]) represents [1, 2, 1, 2]. - VariableListProperty([‘1px’, (2, ‘px’), 3, 4.0]) represents [1, 2, 3, 4.0]. - VariableListProperty(5) represents [5, 5, 5, 5]. - VariableListProperty(3, length=2) represents [3, 3]. New in version 1.7.0. - class kivy.properties. ConfigParserProperty¶ Bases: kivy.properties.Property Property that allows one to bind to changes in the configuration values of a ConfigParseras well as to bind the ConfigParser values to other properties. A ConfigParser is composed of sections, where each section has a number of keys and values associated with these keys. ConfigParserProperty lets you automatically listen to and change the values of specified keys based on other kivy properties. For example, say we want to have a TextInput automatically write its value, represented as an int, in the info section of a ConfigParser. Also, the textinputs should update its values from the ConfigParser’s fields. Finally, their values should be displayed in a label. In py: class Info(Label): number = ConfigParserProperty(0, 'info', 'number', 'example', val_type=int, errorvalue=41) def __init__(self, **kw): super(Info, self).__init__(**kw) config = ConfigParser(name='example') The above code creates a property that is connected to the number key in the info section of the ConfigParser named example. Initially, this ConfigParser doesn’t exist. Then, in __init__, a ConfigParser is created with name example, which is then automatically linked with this property. then in kv: BoxLayout: TextInput: id: number text: str(info.number) Info: id: info number: number.text text: 'Number: {}'.format(self.number) You’ll notice that we have to do text: str(info.number), this is because the value of this property is always an int, because we specified int as the val_type. However, we can assign anything to the property, e.g. number: number.text which assigns a string, because it is instantly converted with the val_type callback. Note If a file has been opened for this ConfigParser using read(), then write()will be called every property change, keeping the file updated. Warning It is recommend that the config parser object be assigned to the property after the kv tree has been constructed (e.g. schedule on next frame from init). This is because the kv tree and its properties, when constructed, are evaluated on its own order, therefore, any initial values in the parser might be overwritten by objects it’s bound to. So in the example above, the TextInput might be initially empty, and if number: number.text is evaluated before text: str(info.number), the config value will be overwritten())
https://kivy.org/docs/api-kivy.properties.html?highlight=properties
CC-MAIN-2016-40
refinedweb
2,194
50.73
Deploying JavaFX Applications 12 JavaFX Ant Tasks This chapter shows how to use Ant to package JavaFX application. JavaFX Ant tasks and the JavaFX Packager tool are currently the only supported ways to package JavaFX applications. This includes supported versions of the NetBeans IDE, which build JavaFX applications with JavaFX Ant tasks. This page contains the following topics: Section 12.1, "Requirements to Run JavaFX Ant Tasks" Section 12.2, "JavaFX Ant Elements" Section 12.3, "Using JavaFX Ant Tasks" Section 12.4, "Ant Script Examples" See also the following two Ant Task Reference sections: 12.1 Requirements to Run JavaFX Ant Tasks The ant-javafx.jar file is required to use these tasks. It is located in the following locations: In JDK 7 Update 6 or later, it is located in jdk_home/lib In a standalone JavaFX installation, it is located in javafx-sdk-home/lib 12.2 JavaFX Ant Elements There are two categories of Ant elements for JavaFX. Each of the following elements is described in JavaFX Ant Task Reference. JavaFX Ant Tasks These elements accomplish the following tasks: Creating double-clickable JAR files Creating an HTML page and deployment descriptor for Web Start applications or applications embedded in a web page Digitally signing an application, when necessary Converting CSS files to binary format Assembling self-contained application packages See JavaFX Ant Task Reference. For general information about packaging for JavaFX applications, see Chapter 5, "Packaging Basics" and Chapter 6, "Self-Contained Application Packaging." Ant Helper Parameters These elements are used by the JavaFX tasks. They are listed and described in JavaFX Ant Helper Parameter Reference. 12.3 Using JavaFX Ant Tasks To use the JavaFX Ant tasks in the your Ant script, you must load their definitions. An example is shown in the build.xml file in Example 12-1: Example 12-1 Load JavaFX Ant Task Definitions <project name="JavaFXSample" default="default" basedir="." xmlns: <target name="default"> <taskdef resource="com/sun/javafx/tools/ant/antlib.xml" uri="javafx:com.sun.javafx.tools.ant" classpath=".:path/to/sdk/lib/ant-javafx.jar"/> </target> </project> Notes about Example 12-1: Ensure that you declare the fx: namespace, shown in bold in Example 12-1, because short names for some of JavaFX tasks are the same as those used for some system tasks. The current directory (".") is added to the classpath to simplify customization using drop-in resources. See Section 6.3.3, "Customization Using Drop-In Resources." Once JavaFX Ant task definitions are loaded, the javafx.ant.version property can be used to check the version of Ant tasks APIs. Use the following list for version numbers: Version 1.0: shipped in the JavaFX 2.0 SDK Version 1.1: shipped in the JavaFX 2.1 SDK Version 1.2: shipped in the JavaFX 2.2 SDK and JDK 7 Update 6 12.4 Ant Script Examples Example 12-2 shows an Ant script that uses the <fx:jar> task to build the JAR file and the <fx:deploy> task to build the JNLP and HTML files for web deployment. Other elements, such as <fx:application> and <fx:resources> are types that are described in the <fx:application> and <fx:resources> in the Ant task reference. Example 12-2 Typical JavaFX Ant Script <taskdef resource="com/sun/javafx/tools/ant/antlib.xml" uri="javafx:com.sun.javafx.tools.ant" classpath="${javafx.lib.ant-javafx.jar}"/> <fx:application <fx:resources <fx:fileset <fx:fileset </fx:resources> <fx:jar <!-- Define what to launch --> <fx:application <!-- Define what classpath to use --> <fx:resources <manifest> <attribute name="Implementation-Vendor" value="${application.vendor}"/> <attribute name="Implementation-Title" value="${application.title}"/> <attribute name="Implementation-Version" value="1.0"/> </manifest> <!-- Define what files to include --> <fileset dir="${build.classes.dir}"/> </fx:jar> <fx:signjar <fileset dir='dist/*.jar'/> </fx:signjar> <fx:deploy <fx:application <fx:resources <fx:info <!-- Request elevated permissions --> <fx:permissions </fx:deploy>
http://docs.oracle.com/javafx/2/deployment/javafx_ant_tasks.htm
CC-MAIN-2014-23
refinedweb
651
51.44
On Fri, 24 Oct 2008 12:23:18 -0700, Robert Dailey wrote: > Hi, > > I'm currently using boost::python::import() to import Python modules, so > I'm not sure exactly which Python API function it is calling to import > these files. I posted to the Boost.Python mailing list with this > question and they said I'd probably get a better answer here, so here it > goes... > > If I do the following: > > using namespace boost::python; > import( "__main__" ).attr( "new_global" ) = 40.0f; import( "__main__" > ).attr( "another_global" ) = 100.0f: > > Notice that I'm importing twice. What would be the performance > consequences of this? Do both import operations query the disk for the > module and load it into memory? Will the second call simply reference a > cached version of the module loaded at the first import() call? > > Thanks. I think it does not reload the module. Running python with verbose mode: blah at blah-laptop:~$ python -v (snip) >>> import xml import xml # directory /usr/local/lib/python2.6/xml # /usr/local/lib/python2.6/xml/__init__.pyc matches /usr/local/lib/ python2.6/xml/__init__.py import xml # precompiled from /usr/local/lib/python2.6/xml/__init__.pyc >>> import xml >>> It's also mentioned in the docs: (paraphrased to clarify the points) ''' The system maintains a table of modules that have been ... initialized.... When a module name is found..., step (1) is finished. If not, a search for a module ... . When ... found, it is loaded. '''
https://mail.python.org/pipermail/python-list/2008-October/506119.html
CC-MAIN-2014-15
refinedweb
243
69.58
I want to share a subtle gotcha with a particular approach to a software-extended timer, so that others might avoid being caught by it. I encountered this the common software-based extended timer based on an 8-bit timer and overflow interrupt. In this approach I avoided disabling interrupts in the read function. I failed to turn up anything about this particular issue, as most dicussions of software-extended timers involve disabling interrupts when reading the timer. Related topics: What is the right way to read a software extended timer?, Out of sequence time stamp....?, How to increase Atmega Timer resolution? In this application I couldn't disable interrupts while reading the timer due to the latency that would add to another higher-priority interrupt, so I needed to use a different approach than the usual one of disabling them. My flawed approach was to read the low byte, the high byte, and then re-read the low byte again and if an overflow had occurred since the last read, repeat the process: volatile uint8_t timer_hi; ISR(TIMER0_OVF_vect) { timer_hi++; } uint16_t get_timer( void ) { for ( ;; ) { uint8_t lo = TCNT0; uint8_t hi = timer_hi; if ( lo <= TCNT0 ) return hi<<8 | lo; } } The loop handles the case where the timer overflowed and we therefore don't know whether we read the high byte before or after the overflow interrupt incremented it. If no overflow occurred between the two TIMER0 reads, we wouldn't get an inconsistent value. As far as I can tell this would be a solid approach, since the overflow would cause the interrupt in a timely manner. But it's not solid. In some code that reads the timer repeatedly in a tight loop, it occasionally gets a value slightly before the previous reading, causing elapsed time calculations to report a large value and make it seem like a timeout occurred. With the usual way of coding an interrupt handler with a RETI at the end, if an interrupt source generates repeated interrupts in a row, the mainline code is still able to execute one instruction between each interrupt. I've run test code that confirms this for the atmega8, atmega328, and attiny85. It's not unexpected since this behavior matches the descriptions of instructions and the delayed effect of SEI/RETI on enabling interrupts. In this case, a higher-priority interrupt than timer overflow (e.g. INT0) being repeatedly triggered was effectively disabling all lower-priority interrupts, while still allowing mainline code to run (albeit quite slowly). This means that get_timer() cannot depend on the timer overflow interrupt being handled in a timely manner. There may be an overflow interrupt pending (TIMER0 has already overflowed), which never gets handled across the TIMER0 read, timer_hi read, TIMER0 read sequence. The loop might see identical values for both TIMER0 reads, so never know that timer_hi still needs to be incremented. It can't simply check the overflow flag and increment the high byte itself, because reading the flag and timer_hi can't be done atomically, and thus it might read the flag just before the overflow interrupt is finally handled, then read timer_hi after it's been incremented, so think it needs to be incremented again. One solution is to end the INT0 handler with a different sequence that ensures that the mainline code cannot run if there are repeated interrupts. I've tested that ending with SEI and then RETI (or just RET, since the I would now be superfluous) indeed stops mainline code (along with all other interrupt handlers) while the repeated lower-priority interrupts occur, because interrupts are enabled right after the RET(I) returns, and thus the INT0 handler can fire again before any mainline code has a chance to execute. Another approach that I used (not wanting to modify the library that provides the INT0 handler) is to have get_timer() detect this unhandled overflow interrupt case and keep looping until it is handled: uint16_t get_timer( void ) { for ( ;; ) { uint8_t lo = TCNT0; // be sure no unhandled overflow interrupt if ( !(TIFR & (1<<TOV0)) ) { uint8_t hi = timer_hi; if ( lo <= TCNT0 ) // no overflow between TCNT0 reads return hi<<8 | lo; } } } As before, the two TCNT0 reads detect any overflow event between them. The added TIFR check detects an unhandled overflow interrupt persisting possibly from before the first TCNT0 read. If there is no unhandled overflow, then any further overflows that would invalidate the reading will be detected by the two TCNT0 reads and cause the loop to repeat. As far as I can tell this fixed the issue. I'm bothered by how involved it is, but I can't think of any simplifications when taking this general route to solving the problem. The following demo program, which can be run on a USBasp stick, outputs waveforms on PB2, PB3, and PB4 showing activity and how INT0 can prevent TIMER0_OVF from running, while still letting mainline code run: avr-gcc -Wall -mmcu=atmega8 -DF_CPU=12000000 -Os demo.c avr-objcopy -j .text -j .data a.out avrdude -p atmega8 -c usbasp -U a.out #include <avr/io.h> #include <avr/interrupt.h> int main( void ) { // Enable low-level INT0. Pin is tied low. MCUCR &= ~(3<<ISC00); // Enable TIMER0 OVF every 256 clocks TCCR0 = 1<<CS00; // no prescaling TIMSK |= 1<<TOIE0; sei(); DDRB |= 1<<4 | 1<<3 | 1<<2; for ( ;; ) { uint8_t pb = 0; // Toggle PB2 many times uint8_t n; for ( n = 50; n--; ) { pb ^= 1<<2; PORTB = pb; } // Toggle INT0 enabled GICR ^= 1<<INT0; } } // ISR_NAKED to reduce unnecessary compiler-generated save/restore // Toggle PB3 on INT0 interrupt ISR(INT0_vect, ISR_NAKED) { PORTB |= 1<<3; // __asm( "sei" ); // causes INT0 to hog all time __asm( "reti" ); } // Toggle PB4 on timer overflow interrupt ISR(TIMER0_OVF_vect, ISR_NAKED) { PORTB |= 1<<4; __asm( "reti" ); } A logic trace of this running (wider view): The top trace shows how quickly the main code is running. Near the middle it runs quickly while INT0 is disabled and just the timer overflow interrupt fires occasionally. Before/after that, INT0 is firing continuously and the main code is running far slower than normal. The overflow interrupt isn't firing at all during that time. EDIT: clarified posting to be a cautionary tale, not a request to solve a particular problem in a particular program. Could you set a flag in your interrupt and then check it in get_timer()? I'd do it something like this: Top - Log in or register to post comments Are you really running so close to the edge that you can't disable interrupts for, what, 10 cycles? If you are you have serious hardware issues and you will soon run into a show stopper IMHO. You need a faster processor. That's the correct solution. And like you already figured out, you already disable interrupts in your overflow IRQ. The 'correct' way, since I can only guess at your requirements, is to have the timer overflow occur at a multiple of the time base you need. Then just count that time base. don't extent the base timer, just make a new timer tick. for example, you want to do something every 30ms have your timer overflow every 3ms and then count 10 of them, then reset your counter. You will get jitter that way if your high priority interrupt collides with your low priority interrupt, but it's pretty hard to avoid. In order to completely remove all interrupts ( except the hi pri one ) is to read the low pri timer status reg, wait for the overflow, then subtract the current time t determine how long it's been since the overflow. Total PITA Keith Vasilakes Firmware engineer Minnesota Top - Log in or register to post comments keith, thanks for another approach. With that approach even if the timer is more than 8 bits, I can use the first approach to reading, because now the low 8 bits will either be updating along with the others, or nothing will be updated, unlike with the described situation where the low 8 bits are always updating but the high might not be . I will check more closely to see how much of a budget of interrupt disabling I have. I suppose one point of this thread was to warn others of this gotcha when attempting to implement a software-extended timer's read function without disabling interrupts. christop, I think your solution suffers from the same problem. Consider how it would work if your read code was executing, but the overflow interrupt was disabled and the timer had just overflowed before your code began. You'd not see your own overflow flag set yet the high byte of the timer would be incorrect. Top - Log in or register to post comments You're right. My version works only when the timer overflow interrupt is enabled, but the way I read your post it seemed like you didn't disable interrupts (and disabling interrupts doesn't stop TCNT0 from incrementing). So are you ever calling get_timer() with interrupts disabled? I haven't looked through the datasheet regarding the overflow interrupt, but is it triggered exactly when the counter rolls over to 0? Or is there at least one instruction cycle in which code might read a 0 from TCNT0 before the overflow interrupt starts? Top - Log in or register to post comments The more I think about this the more I think since you have a hammer every problem looks like a nail. I think you need to start a new thread and tell us what the real problem is, what is so time critical that you can't wedge a simple IRQ in. Then we can fix the problem rather than chasing optimization geese all day. Keith Vasilakes Firmware engineer Minnesota Top - Log in or register to post comments keith, I should have been clearer in my opening post. I could post a new one with my intent better stated. My main goal was to share the gotcha involved in this approach to a software-extended timer, not to get help solving the problem in my particular program; a cautionary tale of sorts to anyone else taking the approach I took. Mentioning the details of the particular project made this unclear; I just wanted to establish a little context. I hope to be clearer in future postings about things. I don't know about others, but when I'm coming up with solutions I explore various ways of doing things. Knowing that a particular approach has subtle problems is valuable. That was my goal. I've updated the original post to clarify my intent. Are you suggesting that I am not approaching my particular problem flexibly, only using a particular approach inappropriately? I hope this idea about what's going on in my mind doesn't detract from the main point of my post as a cautionary tale for anyone, even people who don't have only a hammer yet have still arrived at the (flawed) approach described. The only thing that I can vaguely make out as a hammer is my preference for not disabling interrupts. I don't see that as a solution to every problem, as the mere lack of CLI doesn't solve a problem; I more see it as a way to avoid potential problems. I'm not highly experienced with interrupt timing and calculating worst-case overhead, thus would like to stick with my experience level in implementation. I know that if I miscalculate worst-case overhead, something worse than that might only occur very rarely so I might not see the problem. CLI-free code requires that I exercise my thinking, which I think is good for understanding things better, e.g. my tests that show how a continuous interrupt still gives a little time to mainline code. I have researched the library I was using further and there is a small budget for disabling interrupts, and I am now considering and researching how to make use of this to simplify the code. Perhaps the biggest realization was that ISR_NOBLOCK is viable and keeps the disabled-interrupt time minimal. christop, my point in the original post was that a repeatedly-firing higher-priority interrupt acts exactly like disabling lower-priority interrupts, but still allowing mainline code to run. Thus code which fails when the overflow interrupt is disabled will also fail when it's enabled but there is a repeatedly-firing higher-priority interrupt. That's the cautionary tale I was sharing. Top - Log in or register to post comments Ahhh ok, so I can just say there is no software solution to this problem :D Keith Vasilakes Firmware engineer Minnesota Top - Log in or register to post comments The original post shows two solutions: SEI before RET(I) in the higher-priority interrupt handler, or the extra OVF flag check in the read function. BTW, I edited my previous reply to you possibly before you made your quick reply just now, so you might not have seen my response to your sens that I was suffering from hammer-itis. Top - Log in or register to post comments There is no need to start a new thread. The OP is/has clarified things.
https://www.avrfreaks.net/comment/1351736
CC-MAIN-2020-40
refinedweb
2,198
57.5
Tablecloth: a new standard library for OCaml & ReasonML Tablecloth is an ergonomic, cross-platform, standard library for use with OCaml and ReasonML, which provides easy-to-use, comprehensive and performant modules, that have the same API on all OCaml / ReasonML / Bucklescript platforms. Tablecloth is not intended to replace your current standard library. Instead, it’s intended to be a smooth layer over different existing standard libraries to make them look the same. A tablecloth, you see. We have recently released version 0.5. As Tablecloth is in early alpha versions, it does not currently achieve all of its objectives. However, it is pointing in that direction, and contributions are appreciated. Design of Tablecloth Dark uses multiple versions of OCaml on the frontend and backend: - Our backend is written in OCaml native, using Jane Street Core as a standard library. - Our frontend is written in Bucklescript (dba ReasonML). - Parts of our backend are shared with the frontend by compiling them using js_of_ocaml, and running them in a web worker. We discovered that it was impossible to share code between the Bucklescript frontend and the OCaml backend, as the types and standard libraries were very different: - Bucklescript uses camelCase by default, while most native libraries, including Core and the OCaml standard library, use snake_case. - The libraries in Belt (Bucklescript’s standard library) have different names and function signatures than native OCaml and Base/Core functions. - Many OCaml libraries have APIs optimized for pipelast (|>), while Belt aims for pipefirst (|.). - Core does not work with Bucklescript, while Belt is optimized for the JS platform. - Belt does not work in native OCaml, while Core is optimized for the native OCaml runtime. - Belt is incomplete relative to Core, or to other languages’ standard libraries (such as Elm’s). - Belt makes it challenging to use PPXes. Tablecloth’s solution Tablecloth solves this by providing an identical API for Bucklescript and native OCaml. It wraps existing standard libraries on those platforms, in order to be fast and memory efficient. It is based off Elm’s standard library, which is extremely well-designed and ergonomic. Tablecloth provides separate libraries for OCaml native, js_of_ocaml, and Bucklescript. The libraries have the same API, but different implementations, and are installed as different packages. The APIs: - are taken from Elm’s standard library, which is extremely complete and well-designed. - ship as separate libraries via npm and opam, - include support for strings, lists, numbers, maps, options, and results, - have both snake_case and camelCase versions of all functions and types, - are backed by Jane Street Base (the slimmed down version of Core) for native OCaml, - are backed by Belt for Bucklescript/ReasonML, - use labelled arguments so that can be used with both pipefirst and pipelast, - expose the types they wrap so they can be used with existing libraries, We also have design goals that are not yet achieved in the current version: - Many of the functions in the Bucklescript version were written hastily, and could be much more efficient, - Tablecloth libraries don’t support PPX derivers well yet, - Tablecloth functions currently might throw exceptions, - All functions should be well documented, with well-known and consistent edge-case behaviour, but aren’t, - All functions should be well tested, but aren’t, - We have not yet made a js_of_ocaml-optimized version. We also hope that we can use this as a testing ground for making elegant and usable standard libraries for Dark. Contributing Tablecloth is an ideal library to contribute to, even if you’re new to OCaml, functional programming, or writing algorithms. The maintainers are warm and friendly, and the project abides by a Code of Conduct. There are many small tasks to be done , and each of them are pretty independent without requiring an understanding of a large system. In addition, a small change to a single function can be extremely helpful. Here are some ways to contribute: - point out inconsistencies between different functions in the library, - point out an inelegant function signature which could be improved, - point out a way in which the library or any of its parts are confusing, - report an edge-case or performance problem in one of the functions, - add a small test for an edge-case of one of the functions, - copy test cases for a function from another language’s standard library, - add documentation to a function, - improve a function’s documentation by discussing an edge-case, - check that a function cannot throw exceptions (and add a note to the function documentation to that effect), - add more functions from Elm’s core library: String, List, Result, Maybe, Array, Dict, Set, Tuple, or Basics, or from any of the Extra libraries. You can perhaps use Philip2 to convert them (and their tests!), - optimize a function (the Bucklescript version in particular), - write a benchmark for a function, or a set of functions, - fix testing for Tablecloth on CircleCI, - make a plan for the addition (or not) of U-suffixed functions like in Belt, - make a plan for adding polymorphic Maps and Sets, - design a Regex module, - design an Array module, and it’s interaction with the List module, - add a js_of_ocaml-optimized version (and perhaps versions wrapping other OCaml standard libraries like Batteries or Containers). - add a Caml namespace to allow users to access the builtin OCaml library functions - add a Tuple3 module A contribution which does as little as adding a docstring to a function is extremely useful, and your contributions are valued. If you’d like to contribute but don’t know where to start, open an issue with your thoughts or questions, or contact us on Twitter or by email.
https://medium.com/darklang/tablecloth-a-new-standard-library-for-ocaml-reasonml-d29a73a557b1?source=collection_home---6------0---------------------
CC-MAIN-2019-18
refinedweb
934
53.04
Simple Tracker Duplication For Universal Analytics First of all, I’m sorry about the title. I should really stop throwing the word “simple” around, since people always tell me that the stuff I claim to be easy and straightforward is rarely so. But since this is my blog, I reserve the right to use whatever stupid and misleading terminology I want. I maintain that what follows IS quite simple, especially when considering the amount of complexity it reduces in your Universal Analytics setup. Next, I want to direct your gaze to my latest Keynote / PowerPoint creation: This piece of art is called “…while waiting for the cosmos”. Note the enigmatic ellipsis in the beginning, the lack of capitalization, and the fact that the title has nothing to do with the image. Yes, friend. This is post-post-modernism at its best! So, I guess my amazing art kind of gave away what I want to show to you in this article. In short, it’s a simple little plugin I’ve been using in projects I work on, which duplicates all hits sent to a Google Analytics property. These duplicated hits are sent to another Google Analytics property, whose property ID you specify when initiating the plugin. This tutorial uses a Universal Analytics plugin (d’oh), which, in turn, utilizies the Tasks API. Before I proceed, I want to direct you to David Vallejo’s blog, where he and a bunch of other people are working together on an open-source project which does similar stuff, but on a WAY more configurable level. The plugin I’m about to walk you through will simply make an exact duplicate of the hit you sent, without letting you modify the payload one bit. Why, you may ask? Well, a surprisingly large number of projects I work with have a need for a “rollup” property, which collects data from all sites in the organization. The data sent to the rollup often mirrors whatever is collected in the local sites. It’s quite a chore to duplicate send commands across all trackers, so if the project is fine with simple duplication, I use this plugin. CAVEAT: This will best work with named trackers. Thus Google Tag Manager setting this up in Google Tag Manager is difficult, as you’ll have to mess with the Tracker name field. If you’re confident with your GTM implementation skills, feel free to do whatever you wish, of course. Nevertheless, in its current state, the plugin caters best to an on-page Universal Analytics implementation. Modifying the tracking code For this to work, you will need to make a small change to your Universal Analytics tracking code. Let’s say the code looks like this> You’ll need to add the following modification: '); // ADD THIS LINE: ga('require', 'simolatorDuplicator', {'newId' : 'UA-12345-2'}); ga('send', 'pageview'); </script> There’s a single addition: ga('require', 'simolatorDuplicator', {'newId' : 'UA-12345-2'});. This line invokes a plugin called simolatorDuplicator (I know! The awesomest plugin name in the UNIVERSE!), after which you pass an object with a single key-value pair: {newId : newTrackerId}. In place of newTrackerId, you place a String with the Google Analytics property ID to which you want to duplicate all the hits. The plugin itself There are two quick and easy (sorry about those words again) ways to load the plugin. Either host it in its own JavaScript file which you then load with a <script></script> loader, or just run the code in the page template itself. What’s important is that the plugin code needs to be loaded AFTER the tracking code. The code looks like this: (function() { var ga = window[window['GoogleAnalyticsObject']]; var GADuplicate = function(tracker, propertyId) { var o = tracker.get('sendHitTask'); var temp; tracker.set('sendHitTask', function(model) { o(model); temp = model.get('hitPayload').replace(new RegExp(model.get('trackingId'), 'g'), propertyId.newId); if (temp) { model.set('hitPayload', temp, true); o(model); } }); }; ga('provide', 'simolatorDuplicator', GADuplicate); })(); So either write this in a file named something.js (feel free to replace something with something else), or just add the code in its own <script> block after the tracking snippet. <!-- METHOD 1 --> <script> // GA Tracking code here </script> <script src="something.js" async></script> <!-- METHOD 2 --> <script> // GA Tracking code here </script> <script> (function() { var ga = window[window['GoogleAnalyticsObject']] || function() {};); } }); }; ga('provide', 'simolatorDuplicator', GADuplicate); })(); </script> Both are equally fine, though to keep things nice and tidy I do recommend the first method. Let’s take a quick stroll through the code. (function() { var ga = window[window['GoogleAnalyticsObject']] || function() {}; ... ga('provide', 'simolatorDuplicator', GADuplicate); })(); These lines wrap the plugin code in an immediately invoked function expression, which I use to protect the global namespace. No, you didn’t need to understand any of that. The next line establishes the ga() interface locally, by scoping it to the global Google Analytics Object. This is so that the plugin still works even if you’ve renamed the global GA interface from ga to something else. After the plugin code (represented by the “…”) we make the plugin available to the ga interface. This is a very important line, as it is the counterpart to the ga('require', 'simolatorDuplicator'...); command used in the tracking code. If you didn’t have this line, or if you had a typo in the plugin name, your GA code would not work at all! So remember to test, test, TEST. Next, the plugin constructor itself:); } }); }; Lots of things going on here. First, the function expression establishes a new function called GADuplicate, which takes two parameters: tracker and config. The tracker parameter is passed automatically by the plugin logic, and it contains a reference to the Universal Analytics tracker object which invoked the plugin. The config object is passed as a parameter in the modified tracking code. It’s the {'newId' : 'UA-12345-2'} which we covered earlier. Next, we make a copy of the original sendHitTask. This little method is actually the entire dispatch logic of analytics.js, so we’ll need it to send our data to Google Analytics. We need it especially because on the very next line after the variable declarations we overwrite the sendHitTask of the tracker with a new one! First, the original sendHitTask, temporarily copied to the method o(), is used to send the regular hit to Universal Analytics. This is really important, as without this you’d just be sending your duplicate hit! Then, we take the hitPayload you just sent to GA, and we replace all instances of the current property ID with the new property ID that you configured in the tracking code! This is the main logic in this plugin. We take the payload, we send it first regularly, and then we modify it and send the modified version. By using model.set('hitPayload', temp, true); we’re rewriting the payload, which is then submitted with a new invocation of the o() method. I maintain that it’s really quite simple when you think about it, but naturally it does require some understanding of how the APIs work. So feel free to plunge into the documentation. And that’s it! That’s the code, the setup, and the implementation. Remember, you will need to modify the tracking code accordingly on all pages of your site where you want to use this plugin. You can use it with named trackers, too; just modify the plugin call to: ga('myNamedTracker:require', 'simolatorDuplicator', {'newId' : 'UA-12345-2'}); And yes, you can rename the plugin to something else than simolatorDuplicator, though I will love you slightly less if you do so. Summary Please remember, this is an exact hit duplication method. If you want to modify the payload, you’ll need to add some additional logic to the code, and I really recommend you check out the link to David Vallejo’s blog in the introductory chapter of this article. Let me know if you’re having problems with this, or if you have suggestions! Please do test this thoroughly before implementing it. You are messing with code that can potentially cripple your Google Analytics implementation.
https://www.simoahava.com/analytics/simple-tracker-duplication-universal-analytics/
CC-MAIN-2018-17
refinedweb
1,356
63.09
Hi all, This problem must have been pilot error on my part as I cannot distill it into a more simple example nor at this point repeat it (the makefiles have been changed a lot). But at the time, I _thought_ I was doing a rigerous comparison of the output of "make -npq"... I apologize for the sending the false report. -sandy p.s. we are not using a '|' in the prerequisite RHS - we are only using a '|' in the variable names as part of the variables names themselves. The reason for this is that the makefile system, being non-recursive, needs some type of namespace delineation (all the makefiles need to keep out of each other's namespace - and there is no "in-package" make construct :-). We came up with a scheme that 'export-able' variable names could be named <relative dir path from BUILDROOT>|<var name>. Thus, makefiles can then reasonably and easily construct the names of variables that they need and not collide with names from other makefiles. Something like: perl/win32/modules|ALL_CFILES := perl/win32/modules/foo.c perl/win32|ALL_CFILES := perl/win32/modules/foo.c perl/win32/bar.c The first variable was defined in the modules subdirectory of the second makefile, which was defined in the perl/win32 directory of the build tree. These variables contain a list of all CFILES of all subdirectories within a directory node. Another idea was to require makefile local variable names to begin with a "_" The vertical bar ('|') was the selected as the delimiter for this scheme, for better or for worse... Paul D. Smith wrote: %% Sandy Currier <address@hidden> writes: sc> At least a dump of the database shows that the function block ends sc> up defining a target rule as opposed to an immediate variable sc> definition. Boris is correct about "|" appearing in a prerequisites list but you don't appear to be using it that way in the example makefile you provide... maybe you are doing so later on? sc> define SECTION_7_MODULE_ACCUMULATE_BLOCK sc> # $(1) = dira/dirb (parent directory) sc> # $(2) = dira/dirb/dirc (this directory) sc> # accumulatorssc> $$(foreach platform,$(PLATFORMS),$(2)|ALL_CFILES_$$(platform) := sc> $$(_LOCAL_CFILES_$$(platform)) $$($(2)|ALL_CFILES_$$(platform)))sc> endef This by itself looks fine to me. I think it all depends on how you're using this variable. Can you provide a _complete_, but small, makefile and example of what it's doing that you don't think it should be?
http://lists.gnu.org/archive/html/help-make/2004-05/msg00101.html
CC-MAIN-2015-35
refinedweb
409
59.03
hi all thx for reading and i hope you can help I am creating a game for kids, which shows them how to tell the time I need to put two random numbers into a textfield one for hours and one for minutes so that I can get the app to say show me 13:45 for example however I do not want to include the time of 12:00 as this is where the clock will start and defeats the purpose the clock is 24 hour, going from 1-24 in hours and 00-60 in minutes ive looked everywhere on how to do this but cannot find an answer at the moment i have a textfield which displays the time as the user adds hours etc which i plan to hide so that i can say if this random number textfield is equal to the time textfield then display correct and so on how would i go about this? any help is appreciated Thanks fonzio It's not really clear what you are trying to do nor what you are having a problem with. Do you have any code to show as an attempt? What is the purpose of the textfields and what do random numbers have to do with them? What is the user involvement as far as the user adding hours? Where are kids taught to read time in 24 hour format? An example function generates 24hr time string: function generateRandomTime():String { var hour:uint = Math.floor(Math.random()*24); // creates a random number 0 - 23 var minute:uint = hour == 12 ? Math.floor(Math.random()*59) + 1 : Math.floor(Math.random()*60); // creates a random number 0 - 59, if the hour is 12 the number range is 1 - 59 (so that you don't get 12:00) return hour + ":" + (minute < 10 ? "0" : "") + minute; // retun the result string } trace(generateRandomTime()); -- Kenneth Kawamoto excellent kenneth, that does what i would like it to one question though, is there a way to make it not repeat itself, lets say i run the code and i get 22:13 then i run again and get 22:13 is there a way to say if its the same, randomise again?? thanks for your help Fonzio incidentally I had to add a +1 so that i didnt get a zero: in the time however now im worried i might get 25 would I? thanks fonzio @ Ned, well i have a background, which changes from light to dark, denoting time, and a clock which reads, 1 to 12, and then changes after midday to 13 to 24, and so on as a dynamic textfield, each time the user adds an hour the textfield will add one, counting if you see what i mean now if this is hidden, i need to match it up with what kenneth did, you see the app will ask the question show me random : random time and this random time will need to be checked against my dynamic textfield in order to get a match hope this helps fonzio No but you would get times such as 24:59. The code above generates a time between 0:00 - 23:59. What range do you want to generate? -- Kenneth Kawamoto thats exactly the range then, thanks very much for your help fonzio is there a way to make it not repeat itself, lets say i run the code and i get 22:13 then i run again and get 22:13 Flash (or computer in general for that matter) Math.random() cannot really generate a random number but only a pseudo-random number. That said it's interesting it generates exactly the same outcome consecutively. If I do: for(var i:uint = 0; i < 10; i++){ trace(generateRandomTime()); } I get: 23:59 13:11 1:56 1:37 23:55 15:36 3:30 7:32 10:06 1:53 So it's pretty random. is there a way to say if its the same, randomise again?? Yes - but I don't like doing that, because in theory the function could run forever. If you want to make sure you never get the same time value, one way is to store all the time values in an Array, then randomise it, then pop one by one: // create an Array with numbers 0:00 - 23:59 in minutes, then randomise it function generateRandomTimeList():Array { var array:Array = new Array(); for(var i:uint = 0, end:uint = 60*24 - 1; i < end; i++){ array.push(i); } return FisherYates(array); } // Array randomising algorithm function FisherYates(a:Array):Array { var b:Array = new Array(a.length); b[0] = a[0]; for(var i:uint = 1, n:uint = a.length; i < n; i++){ var j:uint = Math.round(Math.random()*i); b[i] = b[j]; b[j] = a[i]; } return b; } // convert number to time formatted string function timeFormat(n:uint):String { var hour:uint = Math.floor(n/60); var minute:uint = n - hour*60; return hour + ":" + (minute < 10 ? "0" : "") + minute; } // trace 10 random time var randomTimeList:Array = generateRandomTimeList(); for(var i:uint = 0; i < 10; i++){ trace(timeFormat(randomTimeList[i])); } Trace 11:24 23:01 9:04 10:55 13:17 9:28 16:06 8:41 7:26 21:05 -- Kenneth Kawamoto excellent work kenneth, i think i use the array then is there a way to get that random time into a textfield called randomtime_txt.text rather than trace it? and how would i check if it matched the textfield of mytime_txt.text thanks for the help much appreciated Fonzio randomtime should be a variable mytime_txt.text == randomtime // true or false -- Kenneth Kawamoto hi ken, yes i have that working correctly one problem though is it is displaying 24:00 as 00 where can i add the +1 so that it goes from 1 to 24 thanks Fonzio one problem though is it is displaying 24:00 as 00 where can i add the +1 so that it goes from 1 to 24 In essence you want 0:01 to 24:00, not 0:00 to 23:59, right? If so you can modify the initial array population: for(var i:uint = 1, end:uint = 60*24; i < end; i++){ -- Kenneth Kawamoto no sorry ken, i have 1 to 12, then 13 to 24 there is no 0 as it may confuse the kids thanks for any help Fonzio Then simply substitute 0 with 24 return (hour == 0 ? 24 : hour) + ":" + (minute < 10 ? "0" : "") + minute; -- Kenneth Kawamoto thankyou ken, that did the job nicely thanks again fonzio Just for the fun of it, here is a one-line approach to generate random hours and minutes (including 24th hour replacement) - makes code much more abbreviated with no conditionals: for (var i:int = 0; i < 10; i++) { trace(new Date(1500000000000 * Math.random()).toString().match(/(?<=\d\s)\d+\:\d+/g)[0].replace(/^00/, "24").replace(/^0/, "")); } return (hour == 0 ? 24 : hour < 10 ? "0" : "") +hour + ":" + (minute < 10 ? "0" : "") + minute; on another note, i have ampm_txt can i somehow add this to the above and get a conditional to work like if (hours<12) { ampm_txt.text="AM"; } if (hours>12) { ampm_txt.text="PM"; } if (hours==24) { ampm_txt.text="AM"; } if (hours==12) { ampm_txt.text="PM"; that would be really great thanks fonzio @Andrei I thought about using Date object too first. But (1) shouldn't it be 1000*60*60*24 = 86400000 rather than 1500000000000 you have? (2) fonzio wants no duplication therefore you should create an Array of all the permutations first then randomise it. An Array of 86,400,000 Date objects is obviously too much but 60*24 = 1,440 Date objects would do. -- Kenneth Kawamoto htp:// randomTimeList in the code above contains numbers representing 0 minutes (0:00) to 1439 minutes (23:59) so you can test if a number is smaller than 720 minutes (12:00) ampm_txt.text = randomTimeList[i] < 60*12 ? "AM" : "PM"; (You don't have AM/PM with 24 hour clock though...) -- Kenneth Kawamoto "shouldn't it be 1000*60*60*24 = 86400000 rather than 1500000000000 you have?" It doesn't matter because time is expressed in milliseconds. Both values will do. I feel greater value leads to more random results. "(2) fonzio wants no duplication therefore you should create an Array of all the permutations first then randomise it." Randomizing milliseconds eliminates the need for array randomization. Granted, filtering out duplicates should be a separate task. It doesn't matter because time is expressed in milliseconds. Both values will do. I feel greater value leads to more random results. Not really - you'll get biased results if the number is not multiple of 86,400,000; and there is no point in using more than 86,400,000. The goal is to produce a random time string out of 1440 possibilities, which is different from producing random time. Randomizing milliseconds eliminates the need for array randomization. You are not eliminating duplication possibilities, which is the reason for Array randomisation. -- Kenneth Kawamoto I disagree although a little bias may be present. on a very large number it is negligible. As for the number manipulation vs performance - there is no difference so I would deal with as large number as possible. Multiples of 86400000 would help a little of course. So, one can use 1499990400000 instead of 1500000000000. By the way, the difference between these two number is only 0.0006399999999961992% - negligible. "You are not eliminating duplication possibilities, which is the reason for Array randomisation." Did I say I was eliminating duplicates? Array randomization does not eliminate duplicates per se. So, additional Array randomization is an overkill. If you read the thread you'll see a randomised array has been used to avoid duplicate. If you use yours (or my original code) the chance of getting the duplicate is relatively high - 1 in 1440 to get the next as a duplicated result, for a simple example. Also the probability for getting any one time string is always 1/1440 no matter how large the number you use for Date() (although the bias gets smaller and smaller and all probabilities will get close to 1/1440 as the number grows - if you do not use multiple of 86400000 that is, if you do there's no bias so might as well just use 86400000.) -- Kenneth Kawamoto thanks ken, i only want to randomize 5 times then the game will end and on to the next one thanks again fonzio That's fine - just pick up the first 5 from the randomised array, there's zero chance of getting the same time combinations -- Kenneth Kawamoto thanks ken incidentally the next game is a sequence game using numbers id like to use the same code if possible, so in level 1 the main number (3) would randomize, and then three others would appear which would need to be put in order (like in a jigsaw) as in 3, 5, 7, 9 randomize to 10, as in 10, 20, 30, 40 wondering if this is possible and how i would need to go about it? thanks fonzio First you need to generate an Array with numbers in sequence. You'll need to have (a) the base number, (b) the increment, and (c) the length. If we take your first example, the base number is 3, the increment is 2, and the length is 4. The code will be something like: var baseNumber:uint = 3; var increment:uint = 2; var length:uint = 4; var numberSequenceArray:Array = new Array(); for(var i:uint = 0; i < length; i++){ numberSequenceArray.push(baseNumber); baseNumber += increment; } trace(numberSequenceArray); // tarce // 3,5,7,9 Once you have the array you can randomise the order by using the same function as before. -- Kenneth Kawamoto North America Europe, Middle East and Africa Asia Pacific South America
http://forums.adobe.com/message/4013941
CC-MAIN-2013-20
refinedweb
1,974
66.67
Async Trello library Project description aiotrello Async Trello Python library Installation $ pip install aiotrello Examples import asyncio; loop = asyncio.get_event_loop() from aiotrello import Trello trello = Trello(key="123", token="abc123") # Initialize a new Trello client async def main(): # Create 10 boards and make a list for each for i in range(10): board = await trello.create_board(f"Board {i}") await board.create_list("My List") # Delete all boards that start with "Board" for board in await trello.get_boards(): if board.name.startswith("Board"): await board.delete() # Get a board and list, then make a new card, and finally, add a comment to it my_board = await trello.get_board(lambda b: b.id == "123") my_list = await my_board.get_list(lambda l: l.name == "My List") card = await my_list.create_card("Hello World", "Here is my awesome card") await card.add_comment("aiotrello rocks!") # Move card (above example) to a different list my_other_list = await my_board.get_list(lambda l: l.name == "My Other List") await card.move_to(my_other_list) # also supports moving to external boards board2 = await trello.get_board(lambda b: b.name == "My Other Board") list2 = await board2.get_list(lambda l: l.name == "My Other List") await card.move_to(list2, board2) # Edit a card (above), archive it, and then delete it await card.edit(name="This card will be deleted soon..") await card.archive() await card.delete() try: loop.run_until_complete(main()) finally: loop.run_until_complete(trello.session.close()) # Remember to close the session! Support Join our Discord Server Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/aiotrello/
CC-MAIN-2020-40
refinedweb
268
63.56
) Return Value Code sample ListUsers example 1 import arcpy arcpy.ListUsers("Database Connections/admin.sde") ListUsers example 2 The following example demonstrates how to print a list of connected users along with their connection time. import arcpy users = arcpy.ListUsers("Database Connections/admin.sde") for user in users: print("Username: {0}, Connected at: {1}".format( user.Name, user.ConnectionTime)) ListUsers example 3 The following example demonstrates how to generate a new list of only SDE IDs from the list returned by ListUsers. import arcpy # Set the admistrative workspace connection arcpy.env.workspace = "Database Connections/tenone@sde.sde" # Create a list of users ''' NOTE: When the arcpy.env.workspace environment is set, a workspace does not need to be provided to the function. ''' users = arcpy.ListUsers() # Create a list of SDE ID's. # Use a list comprehension to get the ID values in a new list. id_users = [user.ID for user in users] print(id_users)
https://desktop.arcgis.com/en/arcmap/10.5/analyze/arcpy-functions/listusers.htm
CC-MAIN-2020-16
refinedweb
154
51.95
Before we begin, a small note: I’ll be on conference in Istanbul next week, so I won’t be here for the next two exercises. In today’s Programming Praxis exercise we’re supposed to implement grep based on the regex matching functions we wrote in previous exercises. Let’s get started. First, some imports. import System.Environment import Text.Printf Obviously, we’re going to need the code we wrote in the previous two exercises. --Code from the previous two exercises goes here grepString shows all the lines of the input that (don’t) contain the regular expression, prefixed by the filename if one is provided. grepString :: Bool -> Maybe String -> [Chunk] -> String -> IO () grepString b p cs = mapM_ (printf "%s%s\n" $ maybe "" (++ ": ") p) . filter ((== b) . match cs) . lines grep searches all the given files, or the standard input if none are provided, for the regular expression. grep :: Bool -> [String] -> IO () grep _ [] = error "Not enough arguments provided" grep b (r:ps) = either print (f ps) $ parseRegex r where f [] cs = grepString b Nothing cs =<< getLine f _ cs = mapM_ (\p -> grepString b (Just p) cs =<< readFile p) ps Finally, main checks whether to display the lines that do or do not match. main :: IO () main = f =<< getArgs where f ("-v":args) = grep False args f args = grep True args And that’s it. See you guys in a week. Tags: bonsai, code, expression, grep, Haskell, kata, praxis, programming, regular, search
https://bonsaicode.wordpress.com/2009/09/25/programming-praxis-grep/
CC-MAIN-2017-30
refinedweb
243
70.53
. Using double and float for exact calculation public class BigDecimalExample { public static void main(String args[]) throws IOException { //floating point calculation double amount1 = 2.15; double amount2 = 1.10; System.out.println("difference between 2.15 and 1.0 using double is: " + (amount1 - amount2)); //Use BigDecimal for financial calculation BigDecimal amount3 = new BigDecimal("2.15"); BigDecimal amount4 = new BigDecimal("1.10") ; System.out.println("difference between 2.15 and 1.0 using BigDecimal is: " + (amount3.subtract(amount4))); } } Output: difference between 2.15 and 1.0 using double is: 1.0499999999999998 difference between 2.15 and 1.0 using BigDecmial is: 1.05 From above example of floating point calculation is pretty clear that result of floating point calculation may not be exact at all time and it should not be used in places where exact result is expected. Using Incorrect BigDecimal constructor Another mistake Java Programmers make is using wrong constructor of BigDecmial. BigDecimal has overloaded constructor and if you use the one which accept double as argument you will get same result as you do while operating with double. So always use BigDecimal with String constructor. here is an example of using BigDecmial constructed with double values: //Creating BigDecimal from double values BigDecimal amount3 = new BigDecimal(2.15); BigDecimal amount4 = new BigDecimal(1.10) ; System.out.println("difference between 2.15 and 1.0 using BigDecmial is: " + (amount3.subtract(amount4))); Output: difference between 2.15 and 1.0 using double is: 1.0499999999999998 difference between 2.15 and 1.0 using BigDecmial is: 1.049999999999999822364316059974953532218933105468750 I agree there is not much difference between these two constructor but you got to remember this. Using result of floating point calculation in loop condition One more mistake from Java programmer can be using result of floating point calculation for determining conditions on loop. Though this may work some time it may result in infinite loop another time. See below example where your Java program will get locked inside infinite while loop: double amount1 = 2.15; double amount2 = 1.10; while((amount1 - amount2) != 1.05){ System.out.println("We are stuck in infinite loop due to comparing with floating point numbers"); } Output: We are stuck in infinite loop due to comparing with floating point numbers We are stuck in infinite loop due to comparing with floating point numbers …………… ………….. This code will result in infinite loop because result of subtraction of amount1 and amount 2 will not be 1.5 instead it would be "1.0499999999999998" which make boolean condition true. That’s all on this part of learning from mistakes in Java, bottom line is : - Don’t use float and double on monetary calculation. - Use BigDecimal, long or int for monetary calculation. - Use BigDecimal with String constructor and avoid double one. - Don’t use floating point result for comparing loop conditions. Other Java tutorials you may like Related topics: 13 comments : Hey - that explain why all financial operations are computed using BigDecimal in my company. You opened my eyes! Hi Javin , great post! learnt about why to use BigDecimal. Looking forward for this article series. Funny to read about financial calculation. This java double format is useless for science too. Or want someone used that to calculate statistics of medical drugs safety for example? I think this type actually is mistake. Seams that someone forgot to set all bits from 8 byte number to 0 and rounds some memory garbage from a tail in every operation. And the most evil you can not predict this error - next operation you can add it in your result or multiply And BigDecimal is not a cure, because it is limited to use only functions - not operators. As for me it is horror to write some opeartion like a = x*b+c*b using BigDecimal class and it's functions. can anyone multiply (200 digit number) with (200 digit number) without using BIGNUMBER? Using float and double for financial calculations can be serious mistake. Great to see that you are educating people with this kind of practical advice, long is also not a perfect solution, as monetary calculation for notional and future predictions may go beyond range of long data type.
http://javarevisited.blogspot.com/2012/02/java-mistake-1-using-float-and-double.html?showComment=1405513828932
CC-MAIN-2016-22
refinedweb
694
52.05
This set of MongoDB Multiple Choice Questions & Answers (MCQs) focuses on “Troubleshooting Sharded Cluster”. 1. The preferred way to clear the _________ flag from a chunk is to attempt to split the chunk. a) boolean b) jumbo c) change d) all of the mentioned View Answer Explanation: If the chunk is divisible, MongoDB removes the flag upon successful split of the chunk. 2. Point out the correct statement: a) In some instances, MongoDB cannot split the no-longer jumbo chunk, such as a chunk with a range of single shard key value b) To ensure that mongos instances update their cluster information cache, run flushConfig in the admin database c) In a sharded cluster, you cannot use tags to associate specific ranges of a shard key with a specific shard or subset of shards d) All of the mentioned View Answer Explanation: If you clear the jumbo flag for a chunk that still exceeds the chunk size and/or the document number limit, MongoDB will re-label the chunk as jumbo when MongoDB tries to move the chunk. 3. _________ is used to remove tags from a particular shard. a) sh.removeTag() b) sh.removeShard() c) sh.removeShardTag() d) all of the mentioned View Answer Explanation: You may remove tags from a particular shard using the sh.removeShardTag() method when connected to a mongos instance. 4. ________ associates a shard with a tag or identifier. a) sh.collects() b) sh.addShardTag c) sh.results() d) all of the mentioned View Answer Explanation: MongoDB uses these identifiers to direct chunks that fall within a tagged range to specific shards. 5. Point out the wrong statement : a) You cannot overlap defined ranges, or tag the same range more than once b) The mongod provides a helper for removing a tag range c) The output from sh.status() lists tags associated with a shard, if any, for each shard d) None of the mentioned View Answer Explanation: The mongod does not provide a helper for removing a tag range. 6. To assign a tag to a range of shard keys use the _________ method when connected to a mongos instance. a) sh.addTagRange() b) sh.splitFind() c) sh.Range() d) all of the mentioned View Answer Explanation: You may delete tag assignment from a shard key range by removing the corresponding document from the tags collection of the config database. 7. Each document in the tags holds the ________ of the sharded collection and a minimum shard key value. a) tag b) chunk c) namespace d) size View Answer Explanation: In most circumstances, you should leave chunk splitting to the automated processes within MongoDB. 8. Which of the following parameter represents minimum value of the shard key range to include in the tag ? a) min b) max c) maximum d) minimum View Answer Explanation: The minimum is an inclusive match. 9. Use ________ to ensure that the balancer migrates documents that exist within the specified range to a specific shard . a) sh.addShardTag() b) sh.addTag() c) sh.aShardTag() d) all of the mentioned View Answer Explanation: Only issue sh.addTagRange() when connected to a mongos instance. 10. Which of the following parameter denotes name of the shard from which to remove a tag ? a) shard b) tag c) chunk d) none of the mentioned View Answer Explanation: Shard is of string type. Sanfoundry Global Education & Learning Series – MongoDB. Here’s the list of Best Reference Books in MongoDB.
https://www.sanfoundry.com/mongodb-questions-answers-troubleshooting-sharded-cluster/
CC-MAIN-2018-51
refinedweb
576
62.27
Announcing Prophet Today I released Prophet, a microframework for analyzing financial markets. Prophet strives to let the programmer focus on modeling financial strategies, portfolio management, and analyzing backtests. It achieves this by having few functions to learn to hit the ground running, yet being flexible enough to accomodate sophistication. Currently it provides a backtester and a method for generating trade orders. I am more than happy to take feature requests or feedback! Please open an issue here. I hope it helps you prophet from the stock market (hehe). Why? I wanted something that is lightweight and easy to pickup. Ideally a library that focuses on just support infrastructure and being performant and places as few restrictions on me as possible. Think Flask vs Django. When using Prophet, you really should primarily just be working with with pandas library. In comparison to Zipl. In comparison to QSTK. Using Prophet Prophet requires Python. Install prophet with the following command: pip install prophet If you want to dive straight into Prophet, here's the "Hello World": import datetime as dt from prophet import Prophet from prophet.data import YahooCloseData from prophet.analyze import default_analyzers from prophet.orders import Orders class OrderGenerator(object): def run(self, prices, timestamp, cash, **kwargs): # Lets buy lots of Apple! symbol = "AAPL" orders = Orders() if (prices.loc[timestamp, symbol] * 100) < cash: orders.add_order(symbol, 100) return orders prophet = Prophet() prophet.set_universe(["AAPL", "XOM"]) prophet.register_data_generators(YahooCloseData()) prophet.set_order_generator(OrderGenerator()) backtest = prophet.run_backtest(start=dt.datetime(2010, 1, 1)) prophet.register_portfolio_analyzers(default_analyzers) analysis = prophet.analyze_backtest(backtest) print analysis # +--------------------------------------+ # | sharpe | 1.09754359611 | # | average_return | 0.00105478425027 | # | cumulative_return | 2.168833 | # | volatility | 0.0152560508189 | # +--------------------------------------+ # Generate orders for your to execute today # Using Nov, 10 2014 as the date because there might be no data for today's # date (Market might not be open) and we don't want examples to fail. today = dt.datetime(2014, 11, 10) print prophet.generate_orders(today) # Orders[Order(symbol='AAPL', shares=100)] For a more thorough tutorial, please see the documentation. On Quant Investing Quant investing isn't a silver bullet. My personal take on quant investing is that it is really just a magnified reflection of your own investment skill. What formula do you program the computer with? The formula is subject to human tinkering, and at some point enough tinkering creates a human driven computer executed fund. - Nate Tobik, Oddball Stocks You could use financial signal processing and catch large market moves. You could implement a quantitative value strategy. Whatever your strategy does is something that - by the fact you wrote the code - you could do by hand, but slower. Strategies to Explore. Instead, make Prophet a testbed for you to leverage your own expertise, form hypotheses and test them. Remember to learn from mistakes and tests as if it was a scientific experiment. Always be learning.). Conclusion I am hoping people find this project interesting and that it provides a simple framework for programmers to explore and try trading strategies. I will personally be implementing a few strategies that have been on my mind for the last couple years. Even if Prophet doesn't meet your needs now, please open an issue here. I want to build Prophet as flexible as possible but your use case might just be different than mine. Until next time!
http://blog.michaelsu.io/announcing-prophet/index.html
CC-MAIN-2018-22
refinedweb
549
52.26
.... First you should learn how to download and install Java. Once Java is configured Create First Program is the video tutorial of: "Learn Java in a day - Create First Program"... Create First Program In this section, you will learn to write a simple Java Writing Simple Java Script Program of JavaScript and create your first JavaScript program. Creating your first JavaScript Program In the last lesson you learned how to create simple java script... Writing Simple Java Script Learn Java - Learn Java Quickly Development Kit (JDK), then its time to write your first Java program. Create... the function of JVM How to write your First Java program Ok... screen as: Hey! you are going to compile and run your first Java program Java Video Tutorial: How to learn Java? is to create and run the first Java program. Next you can learn the basic...Java Video tutorial for beginners - Provides learn first information about... technology. A beginner in the Java programming language first learn the how...JDBC - Java Database Connectivity Tutorials   Create a java program using Java with LinkedLists Create a java program using Java with LinkedLists Assignment is -- Question For this part of the assignment, you will develop a Java application... beginning, and although there are no marks for it, we do recommend making a plan first How to create LineDraw In Java How to create LineDraw In Java Introduction This is a simple java program . In this section, you will learn how to create Line Drawing. This program implements a line Day for the given Date in Java Day for the given Date in Java How can i get the day for the user input data ? Hello Friend, You can use the following code: import..."); String day=f.format(date); System.out.println(day How to Create Text Area In Java How to Create Text Area In Java In this section, you will learn how to create Text Area in Java. This section provides you a complete code of the program for illustrating)  ... for compiling and running. Hello world program is the first step of java... and it is used to develop the robust application. Java application program Learn Java online , NetBeans), about Java and creating his/her first Hello World program in Java... can learn at his/her pace. Learning Java online is not difficult because every... Runtime Environment (JRE) is required to run Java program and Java-based websites Navigation with Combo box and Java Script Navigation with Combo box and Java Script In this article you learn the basics of JavaScript and create your first JavaScript program. What is JavaScript How to Write a Java program which read in a number... out in the standard output. The program should be started like this: java... to be read. In this example, the program should create three threads for reading... the program. Requirements for first JDBC program: JDBC 1.6 or above should What is JavaScript? - Definition the basics of JavaScript and create your first JavaScript program. What... JavaScript Program In the first lesson we will create very simple JavaScript program...;head> <title>First Java Script</title> <script Introduction In the section, you will learn how...: dir1/dir2/dir3 created C:\nisha> This program takes inputs to create Hello world (First java program) Hello world (First java program)  ... and running. Hello world program is the first step of java programming ... and it is used to develop the robust application. Java application program is platform Java How to Program Java program on your computer and also how to write and run your first java... the program with the Java executable. Here is the first Java Hello World code... with the tradition Java Hello World app. But first take a look at the various requirements Sum of first n numbers Sum of first n numbers i want a simple java program which will show the sum of first n numbers.... import java.util.*; public class SumOfNumbers { public static void main(String[]args){ Scanner program java program Write a program to create an applet and display The message "welcome to java Java Create Directory - Java Tutorial Java Create Directory - Java Tutorial In the section of Java Tutorial you will learn how to create directory using java program. This program also explains Create a JSpinner Component in Java Create a JSpinner Component in Java In this section, you will learn how to create... are used to increase or decrease the numeric value. This program provides 9 Invincible Reasons to learn Java Check the 9 Invincible Reasons which to learn popular Java Programming... of the key reasons that inspire people to learn Java. 1. Gradually lowering...: Java Programming Tutorials Home Learn Java Writing First Hibernate Code First Persistence Class Hibernate uses the Plain Old Java Objects (POJOs... Writing First Hibernate Code In this section I will show you how to create a simple java program java program write a program to create text area and display the various mouse handling events How to Learn Java , how to learn Java? Learning Java is not that difficult just the right start is needed. The best way to learn Java today without spending money in through... Java training program in the market is provided by Roseindia. This online Learn Features of Spring 3.0 . The Spring 3.0 Framework is released with the support of Java 5. So, you can use all the latest features of Java 5 with Spring 3 framework. The first... and released to simplify the development of Enterprise Java applications Create a ToolBar in Java Create a ToolBar in Java In this section, you will learn how to create toolbar in java... been arranged horizontal in this program but, if you want to make it vertically Class Average Program ; This is a simple program of Java class. In this tutorial we will learn how to use java program for displaying average value. The java instances.... Description this program Here in program we are going to use Class. First How to learn programming free? , Here are the tutorials: Beginners Java Tutorial Learn Java in a day Master Java...How to learn programming free? Is there any tutorial for learning Java absolutely free? Thanks Hi, There are many tutorials on Java Java Program MY NAME Java Program MY NAME Write a class that displays your first name vertically down the screen where each letter uses up to 5 rows by 5 columns...() { }, Then, method main should create an object of your class, then call the methods Java Thread Priority Java Threads run with some priority There are Three types of Java Thread priority Normal, Maximum and Minimum Priority are set by setPriority() method. Java Thread Priority Example public class priority implements How to Java Program for the respective operating system. Java Program for Beginner Our first... How to Java Program If you are beginner in java , want to learn and make career in the Java Advertisements If you enjoyed this post then why not add us on Google+? Add us to your Circles
http://www.roseindia.net/tutorialhelp/comment/30138
CC-MAIN-2015-48
refinedweb
1,170
55.54
Look how much cleaner it is in Perl: And that's with extra code added in to populate the variables so you can run it and see what it does. I'm going to have to fix this some day. Update: solutions from Nicolás Sanguinetti: and Assaf Arkin: Both these solutions are cleaner than my Ruby, but I think neither one is as clean as the Perl. (And neither one addresses the more challenging Hpricot use case.) This local_variablesthing is one shiny new toy, though. I never saw that before. The other interesting discovery: Nicolás says PHP has this syntax too, and calls it "variable variables." Apparently in my language snobbery I underestimated PHP. Nicolás also said that he'd been up for 26 hours on too much coffee. Dude, Nicolás, get some sleep! Update: Dan Yoder's solutions: puts "<img #{%w( src width height ).map { |attr| "#{attr}='#{eval attr}'}.join(' ') }/>" assuming, as you do in the Perl example, that the attributes are already locals, since it isn't really fair to lump the hpricot interface into this. Even if we include Hpricot tho: puts "<img #{%w( src width height ).map { |attr| "#{ attr }='#{tag.at(:img)[attr] }'}.join(' ') }/>" it's been awhile since i hacked in perl but i don't recall being able to do things like this in one line. :-) But again I think the Perl remains cleaner. I'm not saying it can't be done a variety of ways in Ruby - I'm just saying the Perl solution is nicer-looking than any solution I've seen in Ruby. Update: Dan's response: Consider, however, that it only works for variables, whereas the Ruby syntax works for any expression. Should Ruby have a separate interpolation operator for locals, like, say '$$'? Or maybe keep the interpolation as it is an introduce an operator that says "eval this": "#{attr} = '#{$attr}" Ah, but wait! We can actually define such a thing if we want ... class String def ~ ; eval self ; end end "#{attr} = '#{~attr}" and I am still free to use an expression here to get the value of attr if I want. I think Ruby gets it right just because it provides a single powerful interpolation operator inside of which we can do whatever we want. :-) In fact, that is why I can write the whole loop in a single LOC. It's all inside the quotes! No way around it - that kicks ass. The Perl really remains cleaner even still, but it does so by a much, much slimmer margin than before, and the payoff for that slim margin is a lot of power.
http://gilesbowkett.blogspot.com/2008/03/self-defining-variables-cleaner-in-perl.html
CC-MAIN-2016-36
refinedweb
436
73.27
:: public static bool IsFatal(this Exception exception) { while (exception != null) { if (exception as OutOfMemoryException != null && exception as InsufficientMemoryException == null || exception as ThreadAbortException != null || exception as AccessViolationException != null || exception as SEHException != null || exception as StackOverflowException != null) { return true; }. We. I) I’ll admit this is an odd topic for me to write about since my job pretty far away from that part of the world, but our PM team at MS is building a set of demos for which we need some semi-random and fun input data that doesn’t change all that rapidly. So we thought that reading the temperature off hard drives would be a nice input. But how to get at it? The solution is to use the WMI interface for ATAPI to get at the SMART data. Binging the subject you’ll find a ton of little snippets that have one thing in common: ‘magic’. Somehow, you get at the ‘VendorSpecific’ structure of the SMART data using WMI and then you believe that byte number 115 is the one that holds the temperature. Of course that’s not what someone who’s doing protocol in their day-job would ever settle for. So I’ve been digging around a little and found a description of the structure and grabbed the attribute value list from Wikipedia, shook it all up a little and out came the little program below. The app grabs the vendor specific array from the ATAPI data, shreds it into a set of structures, and dumps it out. Code here, zip file at the bottom. // (c) Microsoft Corporation // Author: Clemens Vasters (clemensv@microsoft.com) // Code subject to MS-PL: // SMART Attributes and Background:. // SMART Attributes Overview: namespace SmartDataApp { using System; using System.Collections.Generic; using System.Management; using System.Runtime.InteropServices; public enum SmartAttributeType : byte { ReadErrorRate = 0x01, ThroughputPerformance = 0x02, SpinUpTime = 0x03, StartStopCount = 0x04, ReallocatedSectorsCount = 0x05, ReadChannelMargin = 0x06, SeekErrorRate = 0x07, SeekTimePerformance = 0x08, PowerOnHoursPOH = 0x09, SpinRetryCount = 0x0A, CalibrationRetryCount = 0x0B, PowerCycleCount = 0x0C, SoftReadErrorRate = 0x0D, SATADownshiftErrorCount = 0xB7, EndtoEnderror = 0xB8, HeadStability = 0xB9, InducedOpVibrationDetection = 0xBA, ReportedUncorrectableErrors = 0xBB, CommandTimeout = 0xBC, HighFlyWrites = 0xBD, AirflowTemperatureWDC = 0xBE, TemperatureDifferencefrom100 = 0xBE, GSenseErrorRate = 0xBF, PoweroffRetractCount = 0xC0, LoadCycleCount = 0xC1, Temperature = 0xC2, HardwareECCRecovered = 0xC3, ReallocationEventCount = 0xC4, CurrentPendingSectorCount = 0xC5, UncorrectableSectorCount = 0xC6, UltraDMACRCErrorCount = 0xC7, MultiZoneErrorRate = 0xC8, WriteErrorRateFujitsu = 0xC8, OffTrackSoftReadErrorRate = 0xC9, DataAddressMarkerrors = 0xCA, RunOutCancel = 0xCB, SoftECCCorrection = 0xCC, ThermalAsperityRateTAR = 0xCD, FlyingHeight = 0xCE, SpinHighCurrent = 0xCF, SpinBuzz = 0xD0, OfflineSeekPerformance = 0xD1, VibrationDuringWrite = 0xD3, ShockDuringWrite = 0xD4, DiskShift = 0xDC, GSenseErrorRateAlt = 0xDD, LoadedHours = 0xDE, LoadUnloadRetryCount = 0xDF, LoadFriction = 0xE0, LoadUnloadCycleCount = 0xE1, LoadInTime = 0xE2, TorqueAmplificationCount = 0xE3, PowerOffRetractCycle = 0xE4, GMRHeadAmplitude = 0xE6, DriveTemperature = 0xE7, HeadFlyingHours = 0xF0, TransferErrorRateFujitsu = 0xF0, TotalLBAsWritten = 0xF1, TotalLBAsRead = 0xF2, ReadErrorRetryRate = 0xFA, FreeFallProtection = 0xFE, } public class SmartData readonly Dictionary<SmartAttributeType, SmartAttribute> attributes; readonly ushort structureVersion; public SmartData(byte[] arrVendorSpecific) { attributes = new Dictionary<SmartAttributeType, SmartAttribute>(); for (int offset = 2; offset < arrVendorSpecific.Length; ) { var a = FromBytes<SmartAttribute>(arrVendorSpecific, ref offset, 12); // Attribute values 0x00, 0xfe, 0xff are invalid if (a.AttributeType != 0x00 && (byte)a.AttributeType != 0xfe && (byte)a.AttributeType != 0xff) { attributes[a.AttributeType] = a; } } structureVersion = (ushort)(arrVendorSpecific[0] * 256 + arrVendorSpecific[1]); } public ushort StructureVersion get return this.structureVersion; public SmartAttribute this[SmartAttributeType v] return this.attributes[v]; public IEnumerable<SmartAttribute> Attributes return this.attributes.Values; static T FromBytes<T>(byte[] bytearray, ref int offset, int count) IntPtr ptr = IntPtr.Zero; try ptr = Marshal.AllocHGlobal(count); Marshal.Copy(bytearray, offset, ptr, count); offset += count; return (T)Marshal.PtrToStructure(ptr, typeof(T)); finally if (ptr != IntPtr.Zero) Marshal.FreeHGlobal(ptr); [StructLayout(LayoutKind.Sequential)] public struct SmartAttribute public SmartAttributeType AttributeType; public ushort Flags; public byte Value; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] public byte[] VendorData; public bool Advisory return (Flags & 0x1) == 0x0; // Bit 0 unset? public bool FailureImminent return (Flags & 0x1) == 0x1; // Bit 0 set? public bool OnlineDataCollection return (Flags & 0x2) == 0x2; // Bit 0 set? public class Program public static void Main() var searcher = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM MSStorageDriver_ATAPISmartData"); foreach (ManagementObject queryObj in searcher.Get()) Console.WriteLine("-----------------------------------"); Console.WriteLine("MSStorageDriver_ATAPISmartData instance"); var arrVendorSpecific = (byte[])queryObj.GetPropertyValue("VendorSpecific"); // Create SMART data from 'vendor specific' array var d = new SmartData(arrVendorSpecific); foreach (var b in d.Attributes) { Console.Write("{0} :{1} : ", b.AttributeType, b.Value); foreach (byte vendorByte in b.VendorData) { Console.Write("{0:x} ", vendorByte); } Console.WriteLine(); } catch (ManagementException e) Console.WriteLine("An error occurred while querying for WMI data: " + e.Message); } For programmers writing distributed systems and are not using queues in them just yet. If you are a message-oriented middleware veteran - move along My. As our team was starting to transform our parts of the Azure Services Platform from a CTP ‘labs’ service exploring features into a full-on commercial service, it started to dawn on us that we had set ourselves up for writing a bunch of ‘enterprise apps’. The shiny parts of Service Bus and Access Control that we parade around are all about user-facing features, but if I look back at the work we had to go from a toy service to a commercial offering, I’d guess that 80%-90% of the effort went into aspects like infrastructure, deployment, upgradeability, billing, provisioning, throttling, quotas, security hardening, and service optimization. The lesson there was: when you’re boarding the train to shipping a V1, you don’t load new features on that train – you rather throw some off. The most interesting challenge for these infrastructure apps sitting on the backend was that we didn’t have much solid ground to stand on. Remember – these were very early days, so we couldn’t use SQL Azure since the folks over in SQL were on a pretty heroic schedule themselves and didn’t want to take on any external dependencies even from close friends. We also couldn’t use any of the capabilities of our own bits because building infrastructure for your features on your features would just be plain dumb. And while we could use capabilities of the Windows Azure platform we were building on, a lot of those parts still had rough edges as those folks were going through a lot of the same that we went through. In those days, the table store would be very moody, the queue store would sometimes swallow or duplicate messages, the Azure fabric controller would occasionally go around and kill things. All normal – bugs. So under those circumstances we had to figure out the architecture for some subsystems where we need to do a set of coordinated action across a distributed set of resources – a distributed transaction or saga of sorts. The architecture had a few simple goals: when we get an activation request, we must not fumble that request under any circumstance, we must run the job to completion for all resources and, at the same time, we need to minimize any potential for required operator intervention, i.e. if something goes wrong, the system better knows how to deal with it – at best it should self-heal. My solution to that puzzle is a pattern I call “Scheduler-Agent-Supervisor Pattern” or, short, “Supervisor Pattern”. We keep finding applications for this pattern in different places, so I think it’s worth writing about it in generic terms – even without going into the details of our system. The pattern foots on two seemingly odd and very related assumptions: ‘the system is perfect’ and ‘all error conditions are transient’. As a consequence, the architecture has some character traits of a toddler. It’s generally happily optimistic and gets very grumpy, very quickly when things go wrong – to the point that it will simply drop everything and run away screaming. It’s very precisely like that, in fact. The first picture here shows all key pieces except the Supervisor that I’ll introduce later. At the core we have a Scheduler that manages a simple state machine made up of Jobs and those jobs have Steps. The steps may have a notion of interdependency or may be completely parallelizable. There is a Job Store that holds jobs and steps and there are Agents that execute operations on some resource. Each Agent is (usually) fronted by a queue and the Scheduler has a queue (or service endpoint) through which it receives reply messages from the Agents. Steps are recorded in a durable storage table of some sort that has at least the following fields: Current State (say: Disabled, Active), Desired State (say: Disabled, Active), LockedUntil (Date/Time value), and Actor plus any step specific information you want to store and eventually submit with the job to the step agent. The initial flow is as If all went well, we now have a job record and, here in this example, two step records in our store. They have a current state of ‘Disabled’ and a desired state of ‘Active’. If things didn’t go well, we’d have incomplete or partially wedged records or nothing in the job store, at all. The client would also know about it since we’ve held on to the reply until we have everything done – so the client is encouraged to retry. If we have nothing in the store and the client doesn’t retry – well, then the job probably wasn’t all that important, after all. But if we have at least a job record, we can make it all right later. We’re optimists, though; let’s assume it all went well. For the next steps we assume that there’s a notion of dependencies between the steps and the second steps depends on the first. If that were not the case, the two actions would just be happening in parallel. ). Once the last step’s current state is equal to the current state, the job’s current state gets set to the desired state and we’re done. So that was the “99% of the time” happy path. So what happens when anything goes wrong? Remember the principle ‘all errors are transient’. What we do in the error case – anywhere – is to log the error condition and then promptly drop everything and simply hope that time, a change in system conditions, human or divine intervention, or – at worst – a patch will heal matters. That’s what the second principle ‘the system is perfect’ is about; the system obviously isn’t really perfect, but if we construct it in a way that we can either wait for it to return from a wedged state into a functional state or where we enable someone to go in and apply a fix for a blocking bug while preserving the system state, we can consider the system ‘perfect’ in the sense that pretty much any conceivable job that’s already in the system can be driven to completion. In the second picture, we have Agent 2 blowing up as it is processing the step it got handed in (7). If the agent just can’t get its work done since some external dependency isn’t available – maybe a database can’t be reached or a server it’s talking to spews out ‘server too busy’ errors – it may be able to back off for a moment and retry. However, it must not retry past the LockedUntil ultimatum that’s in the step record. When things fail and the agent is still breathing, it may, as a matter of courtesy, notify the scheduler of the fact and report that the step was completed with no result, i.e. the desired state and the achieved state don’t match. That notification may also include diagnostic information. Once the LockedUntil ultimatum has passed, the Agent no longer owns the job and must drop it. It must even not report failure state back to the Scheduler past that point. If the agent keels over and dies as it is processing the step (or right before or right after), it is obviously no longer in a position to let the scheduler know about its fate. Thus, there won’t be any message flowing back to the scheduler and the job is stalled. But we expect that. In fact, we’re ok with any failure anywhere in the system. We could lose or fumble a queue message, we could get a duplicate message, we could have the scheduler die a fiery death (or just being recycled for patching at some unfortunate moment) – all of those conditions are fine since we’ve brought the doctor on board with us: the Supervisor. The Supervisor is a schedule driven process (or thread) of which one or a few instances may run occasionally. The frequency depends on much on the average duration of operations and the expected overall latency for completion of jobs. The Supervisor’s job is to recover steps or jobs that have failed – and we’re assuming that failures are due to some transient condition. So if the system would expect a transient resource failure condition that prevented a job from completing just a second ago to be healed two seconds later, it’d depend on the kind of system and resource whether that’d be a good strategy. What’s described here is a pattern, not a solution, so it depends on the concrete scenario to get the timing right for when to try operations again once they fail. This desired back-off time manifests in the LockedUntil value. When a step gets scheduled, the Scheduler needs to state how long it is willing to wait for that step to complete; this includes some back-off time padding. Once that ultimatum has passed and the step is still in an inconsistent state (desired state doesn’t equal the current state) the Supervisor can pick it up at any time and schedule it. . The Supervisor can pursue a range of strategies for recovery. It can just take a look at individual steps and recover them by rescheduling them – assuming the steps are implemented as idempotent operations. If it were a bit cleverer, it may consider error information that a cooperative (and breathing) agent has submitted back to the Scheduler and even go as far as to fire an alert to an operator if the error condition were to require intervention and then take the step out of the loop by marking it and setting the LockedUntil value to some longer timeout so it’s taken out of the loop and someone can take a look. At the job-scope, the Supervisor may want to perform recovery such that it first schedules all previously executed steps to revert back to the initial state by performing compensation work (all resources that got set to active are getting disabled again here in our example) and then scheduling another attempt at getting to the desired state. In step (2)b up above, we’ve been logging current and desired state at the job-scope and with that we can also always find inconsistent jobs where all steps are consistent and wouldn’t show up in the step-level recovery query. That situation can occur if the Scheduler were to crash between logging one step as complete and scheduling the next step. If we find inconsistent jobs with all-consistent steps, we just need to reschedule the next step in the dependency sequence whose desired state isn’t matching the desired state of the overall job. To be thorough, we could now take a look at all the places where things can go wrong in the system. I expect that survey to yield that at as long we can successfully get past step (2)b from the first diagram, the Supervisor is always in a position to either detect that a job isn’t making progress and help with recovery or can at least call for help. The system always knows what its current intent is, i.e. which state transitions it wants to drive, and never forgets about that intent since that intent is logged in the job store at all times and all progress against that intent is logged as well. The submission request (1) depends on the outcome of (2)a/b to guard against failures while putting a job and its steps into the system so that a client can take corrective action. In fact, once the job record is marked as inconsistent in step (2)b, the scheduler could already report success back to the submitting party even before the first step is scheduled, because the Supervisor would pick up that inconsistency eventually... Anyone] Check this. Steve has a great analysis of what BizTalk Services means for Corzen and how he views it in the broader industry context.". Just so that you know: In addition to the regular breakout sessions, we have a number of interactive chalk talks scheduled here at the Connected Systems Technical Learning Center in the Expo Hall. Come by. This is my first TechEd! - as a Microsoft employee. It's of course not my first tech event in my new job (Egypt, Jordan, UK, France, Switzerland, Holland, Belgium, Denmark, Las Vegas/USA, Slovenia, and Israel are on the year-to-date list - on top of three long-distance commutes to Redmond), but the big TechEds are always special. It'll be fun. Come by the Connected Systems area in the exhibition hall and find me to chat if you are here in Boston. Frankly, I didn't expect a Sunday night keynote to be nearly as well attended as it was, but it looks that experiment mostly worked. The theme of the keynote were Microsoft's 4 Core Promises for IT Pros and Developers nicely wrapped into a video story based on the TV show "24" and with that show's IT superwoman Chloe O'Brian (actress Mary Lynn Rajskub) up on stage with Bob Muglia (our team's VP far up above in my chain of command), who acted as the MC for the show. Finally we got an apology from a Hollywood character for all the IT idiocy the put up on screen. Thanks, Chloe. Our team has a lot of very cool stuff to talk about at this show. The first highlight is John Justice's WCF Intro talk (Session CON208, Room 157ABC) today at 5:00pm with a "meet the team" panel Q&A session at the end. Block the time. I. private void exitMenuItem Click(object sender, EventArgs e) { if (runtime != null && runtime.Running) { ThreadPool.QueueUserWorkItem(delegate(object obj) { runtime.Stop(); Invoke(new ThreadStart(delegate() { this.Close(); })); }); } else { this.Close(); } } Just caught myself coding this up. The shown method is a Windows Forms event handler for a menu item. The task at hand is to check a local variable and if that’s set to a specific value, to switch to a different thread and perform an action (that particular job can’t be done on the Windows Forms STA thread), and to close the form back on the main STA thread once that’s done. I colored the executing threads; yellow is the Windows Forms STA thread, blue is an arbitrary pool thread. Works brilliantly. Sick, eh? [Mind that I am using ThreadStart just because it’s a convenient void target(void) delegate]. In the past months I’ve been throwing ideas back and forth with some of my friends and we’re slowly realizing that “Service Oriented Architecture” doesn’t really exist. The term “Service Oriented Architecture” implies that there is something special about architecture when it comes to service orientation, Web services, XML, loose coupling and all the wonderful blessings of the past 5 years in this wave. But if you look at it, there really isn’t much special about the good, old, proven architectural principles once you throw services into the picture. I’ll try to explain what I mean. There are five pillars of software architecture (this deserves more elaboration, but I will keep it short for now): · Edges: Everything that talks about how the network edge of a software system is shaped, designed, and implemented. SOAP, WSDL, WS-*, IIOP, RMI, DCOM are at home here, along with API and message design and ideas about coupling, versioning, and interoperability. · Protocols: Which information do you exchange between two layers of a system or between systems and how is that communication shaped? What are the communication patterns, what are the rules of communication? There are low-level protocols that are technically motivated, there are high-level protocols that are about punting business documents around. Whether you render a security token as a binary thing in DCOM or as an angle brackets thing is an edge concern. The fact that you do and when and in which context is a protocol thing. Each protocol can theoretically be implemented on any type of edge. If you were completely insane, you could implement TCP on top of SOAP and WS-Addressing and some other transport. · Runtimes: How do you implement a protocol? You pick an appropriate runtime, existing class or function libraries, and a programming language. That’s an architectural decision, really. There are good reasons why people pick C#, Java, Visual Basic, or FORTRAN, and not all of them are purely technical. Technically, the choice of a runtime and language is orthogonal to the choice of a protocol and the edge technology/design. That’s why I list it as another pillar. You could choose to do everything in Itanium assembly language and start from scratch. Theoretically, nothing stops you from doing that, it’s just not very pragmatic. · Control Flow: For a protocol to work and really for any program to work, you need concepts like uni- and bidirectional communication and their flavors such as datagrams, sockets, and queues, which support communication styles such as monologues, dialogues, multicast, or broadcast. You need to ideas like parallelization and synchronization, and iterations and sequences. All of these are abstract ideas. You can implement those on any runtime. They are not dependent on a special edge. They support protocols, but don’t require them. Another pillar. · State: This is why we write software (most of it, at least). We write software to transform a system from one state to the next. Press the trigger button and a monster in Halo turns into a meatloaf, and you score. Send a message to a banking system and $100.000 change owners. Keeping track of state, keeping it isolated, current, and consistent or things to consider. Is it ok to have it far away or do you need it close by? Do you cache, and replicate it for the purpose? Is it reference data or business data? Consolidated, preprocessed, or raw? How many concurrent clients have access to the data and how do you deal with the concurrency? All these are questions that have to do with state, and only state. None of this is depends on having a special technology that is being talked through way up above at the edge. Service orientation only speaks about the edge. Its tenets are about loose coupling, about independent evolution and versioning of contracts, and about technology-agnostic metadata exchange. All this is important to make systems interoperate better and to create systems where the effects of changes to one of its parts to any other part are minimized. But none of the SO tenets really speaks about architecture [Sidenote: The “autonomy” is about autonomous development teams and not about autonomous computing]. When you look at what’s being advertised as “serviced oriented architecture”, you see either. There is Service Orientation – and that’s good. There is appropriate architecture for a problem solution – and that’s good too. These are two things. Combining the two is excellent. But “Service Oriented Architecture” is not an isolated practice. I’ve started to use “SO/A” to make clear that I mean architecture that benefits from service orientation. I understand that there is an additional architectural tier of “service orientation” that sits at the business/technology boundary. On that meta-level, there could indeed be something like “service oriented architecture” along the lines of the service convergence that Rafal, Pat and myself were discussing on stage at TechEd Europe last year. But when I see or hear SOA discussed, people speak mostly about technology and software architecture. In that context, selling “SOA” as a completely new software architecture school does not (no longer) make sense to me. Or am I missing something??). You read it here first. Kimberly Tripp blogs (rss). If you do anything with SQL Server: Subscribe!. It's inevitable, its security improvements are absolutely necessary and it might break your code. I would strongly suggest that you install a test box with XP SP2 now if you haven't already done so. I've had some interesting surprises today. link).. suggested answer to the first question is incorrect and illustrates a security problem. Step..] We just had a short discussion here at the office on the goodness and badness of using Reflection to cheat around private and protected and cases where it does and doesn't work (it's of course a System.Security.Permissions.ReflectionPermission thing). The discussion brought back memories of that old C/C++ hack that I've been using for almost any application back in my Borland C++ and OWL days: #define private public#define protected public#include <owl.h> Dan Farino, who wrote the CLR based, Regex extended stored procedure on which I put a warning sign yesterday, wrote me an email back (I notified him that I wrote that blog entry) and told me that he just uploaded an unmanaged version. Haven't downloaded it, yet, but it seems to be functionally equivalent. If it's stable and quick, I can think of 2 bazillon uses for this -- including, of course, Regex based XML parsing inside SQL Server (while we wait for Yukon)..) Matevz Gacnik got it and put himself on the list (Note: I set the output cache to expire every 180 seconds and therefore it mostly takes a little while to rebuild by getting the fresh data from UDDI) © Copyright 2013, Clemens Vasters - Powered by: newtelligence dasBlog 1.9.7067.0
http://vasters.com/clemensv/CategoryView,category,Technology.aspx
CC-MAIN-2013-20
refinedweb
4,326
51.58
What is a sage object? How do I convert a lambda function to a sage object? I would like to use the plot command with my lambda function from numpy import sign H=lambda x: (sign(x)+1)/2 P = lambda x, a,b: H(x - a) - H(x - b) plot(P(x,5,10), (x,-10,20) # or BOX510(x) = lambda x: P(x,5,10) plot(BOX510(x), (x,-10,20) I get error messages. I had a glance at the documentation. It says the plot command expects a Sage Object, but unfortuntely I do not have the notion for its meaning. Eureka, it works, when I use the sign function of sage instead of the one I imported from numpy. Yet, I would like to know what a sage object is?
https://ask.sagemath.org/question/9680/what-is-a-sage-object/
CC-MAIN-2018-13
refinedweb
134
80.51
The Commons Lang library provides much needed additions to the standard JDK's java.lang package. Very generic, very reusable components for everyday use. The top level package contains various Utils classes, whilst there are various subpackages including enums, exception seeks to support Java 1.2 onwards, so although you may have seen features in later versions of Java, such as split methods and nested exceptions, Lang still maintains non-java.lang versions for users of earlier versions of Java. You will find deprecated methods as you stroll through the Lang documentation. These are removed in the next major release.. Lang also has a series of Exceptions that we felt are useful. All of these exceptions are descendents of RuntimeException, they're just a bit more meaningful than java.lang.IllegalArgumentException.. Enums are an old C thing. Very useful. One of the major uses is to give type to your constants, and even more, to give them order. For example: public final class ColorEnum extends Enum { public static final ColorEnum RED = new ColorEnum("Red"); public static final ColorEnum GREEN = new ColorEnum("Green"); public static final ColorEnum BLUE = new ColorEnum("Blue"); private ColorEnum(String color) { super(color); } public static ColorEnum getEnum(String color) { return (ColorEnum) getEnum(ColorEnum.class, color); } public static Iterator iterator() { return iterator(ColorEnum.class); } } The enums package used to be the enum package, but with Java 5 giving us an enum keyword, the move to the enums package name was necessary and the old enum package was deprecated. JDK 1.4 brought us NestedExceptions, that is an Exception which can link to another Exception. This subpackage provides it to those of us who have to code to something other than JDK 1.4 (most reusable code libaries are aimed at JDK 1.2). It isn't just a nested exception framework though, it uses reflection to allow it to handle many nested exception frameworks, including JDK 1.4's. The reflection ability is one of the more interesting tricks hidden in the reflection sub-package, and of much use to writers of applications such as Tomcat or IDEs, in fact any code which has to catch 'Exception' from an unknown source and then wanting to display in a novel way. Although Commons-Math also exists, some basic mathematical functions are contained within Lang. These include classes to represent ranges of numbers,. The second is the JVMRandom class. This is an instance of Random which relies on the Math.random() method for its implementation and so gives the developer access to the JVM's random seed. If you try to create Random objects in the same millisecond, they will give the same answer; so quickly you will find yourself caching that Random object. Rather than caching your own object, simply use the one the JVM is caching already. The RandomUtils provides a static access to the JVMRandom class, which may be easier to use..
http://commons.apache.org/lang/userguide.html
crawl-001
refinedweb
485
54.32
Basecamp-like Subdomains with DeviseBy Dave Kennedy Building authentication for applications is a run of the mill task we have all encountered at some point or another. In the past, most developers would have reached into their tool belt and pulled out restful authentication. Lately, a new kid on the block has been stealing a lot of thunder where authentication is concerned, and with good reason. Devise provides a complete authentication solution. Views, mailers and a host of common authentication helpers such as registration, confirm via email, and the ability to lock accounts come as standard features out the box. Rolling your own authentication system can be a good exercise and, in most cases, is not too big a chore. Having something stable, feature rich and modular like Devise can be a big time saver. Today, we are going to look at implementing Devise in a real world scenario. While the base features of Devise are well-known, its flexibility is somewhat overlooked. We will look at customizing how users log in. A common idiom in multi-tenant applications these days is to have subdomains defined as the users account, for example rubysource.basecamp.com could be a fictional Basecamp login for Rubysource. Let’s do this with Devise. The Application We will start with the essence of our application first. It will be a Rails 3.1-based note taking application. At this stage, we will keep it really simple and only have three models in our domain, Account, Note and User. Let’s crank up some generators for Account and Note and leave User for Devise. rails g model Account subdomain:string rails g scaffold Note title:string content:text user_id:integer account_id:integer In our Account model we will create the associations, class Account < ActiveRecord::Base has_many :users has_many :notes, :through => :users end Similarly for Note we build the associations as follows. class Note > ActiveRecord::Base belongs_to :user belongs_to :account end Nothing special here, just a couple of ActiveRecord models with associations. The only point of interest is the subdomain attribute on the Account model. This is essentially the slug for the account in the request URL (“rubysource” in our previous example). Introducing Devise Devise is a gem, so very straight forward to install. Add Devise to your Gemfile, gem devise then run bundle install. Now on the command line run rails g and check out the generators Devise adds to our application. Devise: devise devise:form_for devise:install devise:shared_views devise:simple_form_for devise:views We will use the obvious rails g devise:install to get Devise running inside our application. After running the generator we should get a couple of instructions telling us to set the root of the application to map somewhere, have a flash area in our layout and setting the default mailer in our development and test environments. Just follow those to the letter. I have set the root of the application to point to notes#index. We need a user model for Devise to authenticate. As it turns out, we can use devise to generate that for us rails g devise User. This generates the model,corresponding migration and the specialized devise_for route in our config/routes.rb file. Before running the migrations we need to modify the User model to associate the Account. We also associate Note as a has_many. I should point out this is the best time to decide what modules Devise will use such as adding :confirmable to the migration, but for now we will just use the default given to us by the generator. With Devise installed, the easiest way to protect our content is with the blanket before_filter :authenticate_user! placed in the ApplicationController. Starting up the server and navigating to localhost:3000, the generic Devise login form is displayed. Knowing it Works Now we have Devise in place, it is not doing quite what we want just yet. We need to authenticate against the subdomain. There are a couple of options in terms of testing. True, we do not really want to test Devise itself. It’s a third party, well- used piece of software, so it’s fair to say it has been well tested. However, we still want to ensure our customizations behave the way we expect. We could do some work starting up a local server and using the brilliant lvh.me domain so we do not have to keep adding subdomains to our hosts file. But aren’t we are better than that? We want reproducible, automated tests. Let’s use our integration tests and the awesomeness that is Capybara. Capybara, by default, runs our suite under the domain. However by simply using the app_host helper we can explicitly specify the domain the test runs under. Here is a basic test of the behavior we are looking for using RSpec requests. describe "LoginToAccounts" do before do other_account = Factory.create(:account) @invalid_user = Factory.create(:user, account: other_account) @account = Factory.create(:account, subdomain: "test-account") @user = Factory.create(:user, account: @account) Capybara.app_host = "" visit '/' end describe "log in to a valid account" do before do fill_in 'Email', with: @user.email fill_in 'Password', with: @user.password click_button 'Sign in' end it "will notify me that I have logged in successfully" do page.should have_content "Signed in successfully" end end describe "fail login for valid user wrong account" do before do fill_in 'Email', with: @invalid_user.email fill_in 'Password', with: @invalid_user.password click_button 'Sign in' end it "will not notify me that I have logged in successfully" do page.should_not have_content "Signed in successfully" end end end Devise Flexibility Now that we have a test, it’s time to implement the functionality of capturing the subdomain and making sure the user is authenticating into the correct account. When we installed Devise, it generated an initializer, aptly named devise.rb in the config/initializers directory. This file is brilliantly commented and should be the first point of call when looking to add functionality to the vanilla install of Devise. You will see on line 33 of this file (based on installing version 1.4.7 of Devise) that we can add request keys for authentication. Simply uncomment the line and add :subdomain to the array of keys. This will basically push this request parameter to Devises authentication method to test against. Even though that was simple enough, we are not quite there yet. Remember that Devise authenticates on User and the subdomain attribute is with the Account. Now, we could simply add a subdomain attribute to user and be done, but that just seems plain wrong to me. Instead, we will override the find_for_authentication method used by Devise. This method is our dropping off point before Devise takes over. To find the Account we are looking for, we will grab the subdomain from the request and pass it up the chain to be authenticated. Using Rails 3+ makes this really easy. In the User model simply add def self.find_for_authentication(conditions={}) conditions[:account_id] = Account.find_by_subdomain(conditions.delete(:subdomain)).id super(conditions) end Here we are popping out the subdomain parameter and doing a find by on the Account and pass it up to the find_for_authentication method. With all this in place we can run the tests and make sure we have a passing suite. The demo code can be found on Github. Where to Next? Our naive little application has authentication and no unauthorized users can access our all-important notes. We still have some work to do regarding what notes are displayed for what login. That is solved with the common multi-tenant idiom of making all our data in the controller extract down from the “current tenant”, like this on by DHH. That is not really what we were looking at here today. Normally, I would avoid testing third party code, but the behavior of our application and the changes we made require that we at least tip our hat to Devise. Wrapping this as an integration test is the best place to do so and using a tool like Capybara makes it easy, so it would be criminal not to be thorough. Authentication is a pattern we will do over and over again when it comes to Rails applications, and something as feature rich as Devise can be intimidating. Hence, why some look to simpler gems such as Restful Authentication, Sorcery or just roll our own. I recommend you invest some time in Devise. With a good understanding you can almost write off the authentication element out of your application and use Devise as a drop in replacement. It’s design is so great and personally I have yet to find myself in the situation where I am fighting against Devise. It’s usually a case of hooking into it to create exactly what I need.
https://www.sitepoint.com/basecamp-like-subdomains-with-devise/
CC-MAIN-2016-44
refinedweb
1,471
56.66
mayukhBAN USER def maxConsecutive(a): # a = [1, 94, 93, 1000, 2, 92, 1001] a.sort() consecutive = 0 prev = a[0] m = consecutive for each in a[1::]: if each == prev + 1: consecutive += 1 else: if consecutive != 0: if m < consecutive + 1: m = consecutive + 1 consecutive = 0 prev = each return m This can only be done for 2..This is because n & (n - 1) will always be non-zero for n not being divisible by 2 and zero otherwise. Now if n is divisible by 2 then n % 2^k == n & (2^k - 1) This is why to check if a number is even or not we can do n & (2 - 1) == n & 1 instead of n % 2 #include <iostream> #include <string> #include <map> std::string removeDuplicates(std::string s){ std::map<char, int> m; std::string ret = ""; for (auto each : s){ m[each]++; } for(auto each : s){ if (m[each] == 1) ret += each; } return ret; } For c++ code...complexity O(n) For python code...complexity O(n) Update even better solution without vector in c++...complexity O(n) Update:: Even better answer without vector - mayukh July 27, 2016
https://careercup.com/user?id=5726058092429312
CC-MAIN-2021-31
refinedweb
188
59.03
Functional programming emphasizes “pure” functions, functions that have no side effects. When you call a pure function, all you need to know is the return value of the function. You can be confident that calling a function doesn’t leave any state changes that will effect future function calls. But pure functions are only pure at a certain level of abstraction. Every function has some side effect: it uses memory, it takes CPU time, etc. Harald Armin Massa makes this point in his PyCon 2010 talk “The real harm of functional programming.” (His talk is about eight minutes into the February 21, 2010 afternoon lightning talks: video.) Even pure functions in programming have side effects. They use memory. They use CPU. They take runtime. And if you look at those evil languages, they are quite fast at doing Fibonacci or something, but in bigger applications you get reports “Hmm, I have some runtime problems. I don’t know how to get it faster or what it going wrong. Massa argues that the concept of an action without side effects is dangerous because it disassociates us from the real world. I disagree. I appreciate his warning that the “no side effect” abstraction may leak like any other abstraction. But pure functions are a useful abstraction. You can’t avoid state, but you can partition the stateful and stateless parts of your code. 100% functional purity is impossible, but 85% functional purity may be very productive. Related posts: 21 thoughts on “Pure functions have side-effects” Alvaro: Right, when most people talk about side-effects they mean side-effects in the logical state of the program in memory. But I think the point being made is that pure functions DO affect the state of the machine they are executing on (BUSY / NOT-BUSY / etc) regardless of whether they affect the logical state of the program and you can never get around this problem completely because we will never have an infinite number of cores to deploy functions to nor an infinite amount of memory and memory bandwidth. John, I disagree with that citation. I don’t know the whole context of his statements, but for my point of view the “No side effects” tenet of FP is not about not taking some RAM or using some CPU. So while he’s right in what he says, I believe that the FP jargon doesn’t means what he means. Sorry if my english is too confusing 😀 Alvaro: Your English is fine. I don’t think Massa disagrees with the FP community about what the stateless abstraction means. He disagrees about its usefulness. FP calls a function “pure” if it has no side effects of a certain kind. I think what Massa is saying is “Yes, but the kinds of side effects that you leave out of your abstraction become important as programs scale. Also, I think your effort to make things stateless, even according to your abstraction, is misguided.” I think this is a brilliant observation. It also frames one of my complaints about attempting to learn functional languages. It seems like every time I try, the books start out by explaining how wonderfully expressive and natural the functional language in question is. But before you get very far, they start explaining how you need to uglify your code in order to make it fast enough to use in practical situations. Fibonacci is a great example, because there is a very natural recursive definition which is completely useless for real world calculations. It is pure in the functional sense, but it is too damn slow to be practical, and naively trying to use it in your code is akin to performing a denial of service attack on yourself. It seems like what we really should be doing is trying to minimize side effects of all sorts, not just those that functional programming recognizes directly…. i must say i never really started to understand the idea of functional programming, or why i should do things according to that kind of thinking. maybe i am too stupid, maybe i haven’t read the right book or met the right guy, yet. so i am very much a procedural, dynamic typing programmer. on the other hand, i used to be an object oriented programmer as well, but in the past four to two years, i have completely changed my style; now i do it the data-centric, library-oriented way. which means that on one hand, i deal with generic structures that represent things, whatever, say that ubiquitous car from OOP intros, which would perhaps look like { '~isa': 'car', 'weight': { '~isa': 'quantity', value: 750, unit: 'kg', }, 'wheels': [ { '~isa': 'wheel', ..., }, ... ], }, you get the idea. so that is an object, and state is broken down to very generic datatypes; assembly is done with dictionaries, sets, lists, that kind of stuff. in order to work with these things, i write generic and specialized libraries of procedures (methods). libraries do not have state, or let us say, in the typical case a library can depend on a configuration, that typically does not change over its lifetime. this configuration is itself stored in passive data structures. again, typically, since libraries have static state which is their configuration, you can instantiate one library when the application starts, put it into the global namespace, and leave it sit there waiting to be used by whatever procedure chooses to call one of its methods. it is only the data objects that are passed around, that change, that are constantly created and destroyed. i find this style of programming tremendously clearer, easier and pragmatic than classical OOP; i am so much more productive with it, for a number of reasons. now reading your post, i realized there is, after all, something that links this style and FP: those libraries do not change. they do not alter their own state when one of their methods is called; their methods are FP ‘pure’ functions with respect to their own state. so it is like part of the perceived usefulness of the scheme described is directly linked to precisely this property. I recently heard someone describe imperative and functional programming by saying that imperative programming sends the data to functions, but functional programming sends functions to the data. The idea “stateless is better than stateful” comes about very naturally in imperative programming too, once you start thinking about concurrent programming. It is not possible to avoid having a state, but at least try not to share it between threads. I agree with Massa. Just by executing, a “pure” function modifies the environment that it’s running in. Here’s a concrete example: In XNA, (a .net game framework) the main render function should get called 60 times a second for the game to render smoothly. Unfortunately, garbage collection typically takes too long for it to execute and a frame to completely render, which results in pauses in the game, so a lot of XNA games are optimized to not allocate objects at all during gameplay. So, if you have a function with “no side effects” that allocates objects, you’ve got side effects. Even with traditional compiled languages, you get side effects via your function’s interacting with the memory manager and memory caches. Typically, it doesn’t matter, but sometimes (like with XNA) it does. And when it does, you need to be aware of how your code interacts with the environment that it executes in. I think that was his point. Moral: There’s no silver bullet. “Hmm, I have some runtime problems. I don’t know how to get it faster or what it going wrong.” Personally this sounds like a straw man argument – as if he tried doing it once and just gave up, but granted, I don’t know the whole context so I may be very wrong here. Personally, I find pure abstractions very reasonable for things relating to optimization at least in Haskell – many times I’ve needed more efficient code, I can just pick a more optimized library. The fact that many of these libraries have a pure interface makes replacing the slower, also pure ones, easy to test and make sure I got it correct (examples: containers/unordered containers, string/bytestring, array/vector.) No programming language is ever going to preclude the need for good engineers to know their environment, from their compiler and OS to their programming languages and their implementation. Python, functional programming or not. I don’t think anybody reasonably believes that pure functions don’t use RAM, or CPU time. That’s an obvious statement – the point of pure functional programming is that the reasoning benefits granted by it are a boon in many cases. Not that it suddenly means we don’t have to worry about the real world at all. I’d agree “100% pure functional programming” isn’t possible – that’s why it’s not advocated (by anyone that isn’t crazy, at least.) The point isn’t to eradicate mutable state, or win some war. It never was – it’s to control such effects and make them easier to reason about, by leveraging things like the type system. That’s what pure functional languages like Haskell allow you to do, with, in my opinion, great benefit. It just turns out lots of problems can be modeled in a mostly pure way. I didn’t watch his presentation. But from the description he is mixing abstraction levels and attributing a change in the environment to the wrong effector. All computation on the machine modifies its environment. No where in the abstraction contract is there even a description nor a mention of what the code does to the machine, that is up to the runtime and the hardware. FP is a mathematical and structural contract that says nothing of the runtime behavior. FP will not magically make all of your code O(1). Equally, non-functional code also modifies the state of the machine, in much the same way. If he wants a formalism that describes both referential, structural or temporal transparency (perhaps he doesn’t) he needs more than fp. Sounds like many arguments that boil down to, “yeah and but …” Physically, functional programming may be an important tool in decreasing the amount of energy needed to perform a computation. This is because a functional program can be executed without erasing information. And it is the erasing of information which causes energy dissipation (aka heat). On a related topic, I think that a quantum computer would be easier to program using FP, because the natural language of programming quantum computers are unitary (reversible) transformations: Psi(t) = U Psi(0). Which is quite functional, when you think about it for a while 😉 The argument is true. Actually, there are side effects. That’s the way the whole universe is built, anyway. However, the argument is not convincing. Or should we now give up all abstraction layes? A compiler or an interpreter have side effects, so do CPUs. I expect abstraction layers like algebras or functions to raise the abstraction level in such a way so that the developer is protected from the mutable reality. It should be the responsibility of a few language implementers to take care of this issue instead of thousands of language users. Of course, transparency could lead to shooting yourself in the foot. Thus, developers should be aware of the physical underpinnings of their platform. And thus they also will know good reasons whenever they need to deviate from the pure functional perspective. its an amusing but pointless observation. the abstraction of a pure function still has value, there have been no balloons popped here QuantDev wrote: Actually, any logically irreversible operation results in heat dissipation; which includes deletion but also copying. See, for instance, Landauer’s principle: Thus, copying a data structure during functional computation, when it results in overwriting bits, results in an entropy-increase. I realize that you said, “a functional program can be executed without erasing information” (emphasis mine); and not that it will or must. But, practically speaking, even a functional program will be in the business of entropy-augmentation. Just wanted to highlight this part of the post: Here’s the thing: no one is selling functional purity and side-effect-free-ness as tools to maximize runtime predictability. They’re sold as tools to maximize the effectiveness of certain kinds of reasoning about program structure and correctness under the old guideline that programmer time is more valuable than computer time. No one disputes that this type of reasoning feels less natural to some people and some problems are a better fit for the paradigm. But the real side-effect of FP is the change in the mindset for the programmer. I seem to be late to the party, but I want to throw my 2¢ in anyway. Telling the computer HOW to do something is different from telling it WHAT to do. It’s as if we have a slider, and if we drag it to the WHAT end, we get to describe our problems to the computer and have it figure out how to solve them for us, and if we drag it to the HOW end, we tell the computer how to solve our problems without it knowing what the problems are. One way of looking at pure functional programming is that it’s just imperative programming, yanked a few notches toward the WHAT end of the slider. When you write a pure function, you theoretically have no idea how it’s going to be executed. I mean, you can guess based on what you know about compilers and computers, and it’s pretty easy to predict in every functional language I’ve seen, but all the contract really says is that the return value of your function will be correct. That gives the compiler a lot of room to be awesome, and a lot of room to suck. When the compiler’s chosen execution plan takes too long or requires too much space, that sucks. It failed to choose the correct HOW, so now you have to step in to provide it, sacrificing some of that sweet WHAT abstraction. So what I’m trying to say is that I agree with both of you. Yes, every time a functional language’s compiler executes our code less than optimally that is bad. As compiler authors and as application authors, we should try to avoid it. And yes, functional programming is a useful abstraction because it gets us closer to WHAT in a lot of cases that matter. But I don’t think purity is the end; the fact that its performance falls short in situations people run into every day is a strike against it. And of course, none of this changes the fact that you should always be using the right tool for the job. 🙂 PyCon certainly isn’t LtU. There is machine code, and then there are ways of thinking about programming…
http://www.johndcook.com/blog/2010/05/18/pure-functions-have-side-effects/comment-page-1/
CC-MAIN-2016-26
refinedweb
2,514
60.85
elixir to start with Some months ago I decided to take a more serious look at Elixir (I drop the gory details about my background and studying different technologies, etc, etc). While I confess that I like F# and Functional Programming in general, the main reason here was Phoenix, the web framework. After getting done with preparations and some Elixir from the website, tried to write something with Phoenix, just some CRUD and possibly a chat app. Things were going on too smoothly, without a hassle! I suspected it’s because of Phoenix. So decided to write something else - a Telegram Bot - to go deeper and actually understand Elixir and BEAM (Erlang Virtual Machine or EVM). Fortunately I’ve found a 4 or 5 days of free time (both business and family). So decided to do a sandboxed, 4 days long, Living-With-Elixir. That was very helpful and this is what I’ve got. How to start to thinking in ElixirHow to start to thinking in Elixir There are three concepts that we need to keep in mind: Our code snippets/blocks, have no idea of other code snippets, even inside the very same file. They are not aware of each other’s existence. There’s just messaging. They communicate via messaging. Each snippets runs inside a process - something like a green thread, coroutine, goroutine. And a process have a unique process id or pid naturally, so we can send messages to it. We do not modify state. There is no such thing as mutable state. Instead, we just pick our state, do something with it, generate a new state (since there is no mutation), recur with new state (which will become the old state of next recur). In short, we keep our state using recursion and modify it using recursion and messaging. when processing state, we can receive messages. - OTP seems confusing to people for some reason that I don’t understand. It’s just when we recursively modify our state, we may receive messages at each recur. Now instead of writing a recursive code and handling all sort of messages ourselves, we just write bunch of callbacks and hand them over to OTP. Depending on what we need, OTP with make a server out of those callbacks, or a state machine or something else, and provides us lots of extra goodies too. As a developer, for sure your mind will see things differently later, and even find out some inaccuracies here, but this path in thinking served me very well, helped me get started relatively fast and led me to actual results. So our app consists of three concepts, a swarm of running snippets , recursive functions and OTP , which is a set of callbacks to be injected inside a recursive function. The rest is all familiar, functions and things, and tooling of-course; a hassle-free one, the mix! Creating somethingCreating something Let’s create a new app: $ mix new acrobot --sup --module Acrobot Installing Elixir is straightforward. And mixis a build tool that comes with Elixir. Here we tell mix to create a new app for us, named acrobot. The --module Acrobot tells mix to create a module named Acrobot which we will put stuff there and --sup means our application will be created in a supervised manner. If you do not know about something, don’t worry. They are pretty simple concepts. Just pretend you know about them. For example, remember that swarm of code snippets we spoke of? The swarm of processes? A supervisor is simply a process that monitors and supervises other processes. We can tell it to restart them, if they fail, or start new ones so we can talk to them and tell them what to do. By the way, this way your app will never crash! Of-course we have the option to make it crash, if one might like to do so; who knows! This is what mix built for us: Not much yet and like any other programming endeavor, we will add stuff as we go. We are using Atom editor. To open a directory as a project, enter $ atom -n acrobot/. The packages used for Elixir programming in Atom are: The next step is accessing Telegram Bot APIs. For that there is a nice Elixir package named nadia. Assuming you already created your bot and have your bot access token (How do I create a bot?), first we add the dependencies, in this case, package nadia; inside file mix.exs, add it like this: def deps do [{:nadia, "~> 0.4.2"}] end Then run $ mix deps.get from inside the project directory to get the dependencies. This will start to get our dependencies and mix always provide clear instructions about what to do if something did not took place as expected. Now head over to file config/config.exs and set the bot token you’ve got when creating your bot: config :nadia, token: "bot token" Other options are also available for nadia, like connection timeout, environment variable and the like. And finally since all packages (almost all) are some sort of services, supervised ones, we have to tell our app to start nadia when starting. Head back to mix.exs and add :nadia to list of applications (services you could read) that should get started at starting point: def application do # Specify extra applications you'll use from Erlang/Elixir [extra_applications: [:logger, :nadia], mod: {Acrobot.Application, []}] end As you see the other application that will start, is :logger which we will use to log things. To start a REPL, type $ iex -S mix. Some compilations would go on (a bit longer the first time) and to see that we are actually connecting to Telegram Bot API, we call Nadia.get_me function: iex(1)> Nadia.get_me {:ok, %Nadia.Model.User{first_name: "MyAcrobot", id: 123456789, last_name: nil, username: "MyAcrobotBot"}} To see if there are any updates (new messages) we call Nadia.get_updates function: iex(2)> Nadia.get_updates limit: 5 {:ok, [%Nadia.Model.Update{callback_query: nil, chosen_inline_result: nil, edited_message: nil, inline_query: nil, message: %Nadia.Model.Message{audio: nil, caption: nil, channel_chat_created: nil, chat: %Nadia.Model.Chat{first_name: "Kaveh", id: 123456789, last_name: "Shahbazian", title: nil, type: "private", username: "idc0d"}, contact: nil, date: 1490177869, delete_chat_photo: nil, document: nil, edit_date: nil, entities: nil, forward_date: nil, forward_from: nil, forward_from_chat: nil, from: %Nadia.Model.User{first_name: "Kaveh", id: 123456789, last_name: "Shahbazian", username: "idc0d"}, group_chat_created: nil, left_chat_member: nil, location: nil, message_id: 3085, migrate_from_chat_id: nil, migrate_to_chat_id: nil, new_chat_member: nil, new_chat_photo: [], new_chat_title: nil, photo: [], pinned_message: nil, reply_to_message: nil, sticker: nil, supergroup_chat_created: nil, text: "Aloha!", venue: nil, video: nil, voice: nil}, update_id: 45285403}]} As you see we got a message Aloha!! The BotThe Bot First let’s add another dependency application credo, which helps us write clean Elixir code: defp deps do [ {:nadia, "~> 0.4.2"}, {:credo, "~> 0.7", only: [:dev, :test]} ] end And to get this dependency too, we run again $ mix deps.get. To see what credo would suggest to improve our code quality, we just run $ mix credo. (from credo GitHub page) Since we have not much code yet, credo would not tell us much about the codebase - yet. What do we like our bot do? We could go for a full blown Bot that will have a separate agent to handle each user concurrently (probably containing a state machine handling some logic) and the like. In which case we have to manage/supervise our swarm of users and monitor them if they get disconnected or crashed and the like. And maybe a database for tracing our users and send them different messages occasionally or provide them some data of their interest. We should be able to answer to callback requests or even inline requests. But for now we just provide the server time to each user that connects to our bot. From this point forward the only remaining concepts besides those three essential ones, are normal, mostly familiar sequential Elixir syntax. We use tuples, lists and maps and special forms of map like structs/records. Some might not encounter pattern matching before. It’s just a technique for expanding the structure of data and decompose it to some child elements and then use those elements. We still can access “members” of a struct using a dot syntax (like in JavaScript myObject.member). But pattern matching gives us the opportunity to say if an object has a member named member, then put it inside a variable and give it to me! Very much like duck typing, but instead of using just names (of members), we use the structure of the data - like TypeScript and interfaces in Go. Getting the chat_id Create file /lib/acrobot/bot.ex. This is a function that gives us the chat id: defp get_chat_id(%{:chat => %{:id => id}}) when id != nil do {:ok, id} end defp get_chat_id(msg) do Logger.warn "unknown #{inspect msg}" {:unknown_message} end defp means we are defining get_chat_id as a private function inside this module. The %{:chat => %{:id => id}} is a pattern for the argument. The argument should have this pattern, which means the argument should be a map ( %{}) which contains the :chat key and the value of that key should be another map, containing a :id key. Then the value will be put inside identifier id. As you see we can put some guards on our arguments like when id != nil. The get_chat_id function, will return a tuple {:ok, id}, which says :ok, here is id. Did we defined get_chat_id twice? While that’s meaningless in other programming languages, here it has a very interesting meaning. Those are different parts of get_chat_id function! As you see the second declaration has no restriction on it’s argument. So every data, that would not match the pattern declared in first clause of get_chat_id function, would go to the second clause, and there we will log it as a warning since there should not be an argument, not matching our desired pattern! update_id We also need to tell Telegram that we already got the updates to some point and we are interested in received messages/updates that came after that. By passing an update_id to Telegram we tell it after which point it show fetch updates for us. For that we define a find_max_id function which actually gives us the biggest update_id in a list of updates. defp find_max_id(max_id, []) do max_id end defp find_max_id(max_id, [h|t]) do id = if h.update_id > max_id do h.update_id else max_id end find_max_id id, t end Again we use multi-clauses to have a clear declaration of our function. In the first clause we say if the list of updates is empty ( []) then just return the previous max_id. Easy to read and understand! In the second clause we say if the list of updates is not empty and has a head item ( h), then put the rest of the list inside t (employing [h|t] pattern). If the list had just one item, then t would match as empty list []. Body of the second clause is clear. We pick the largest of h.update_id and max_id, then we continue our search inside the rest of the list ( t as in tail) by calling find_max_id recursively. We define a helper function to append new updates to the list of previous updates (our state) and at the same time find max update_id: defp append_update(max_id, old_list, new_list) do res = old_list ++ new_list {find_max_id(max_id, res), res} end Answer incoming messagesAnswer incoming messages Telegram Bot API calls an incoming message, an update. We just want to tell the date and time as an answer to the user. So we write a function and pass all incoming messages to it (we are ignoring many details here like Telegram has a max 30 outgoing messages/second): defp answer_incoming([]) do end defp answer_incoming([h|t]) do case get_chat_id(h.message) do {:ok, chat_id} -> dt = :calendar.local_time() Nadia.send_message chat_id, "#{inspect dt}", parse_mode: :html err -> Logger.error "#{inspect err}" end answer_incoming t end We read it as, if the list of incomings is empty then do nothing, else, try to get the chat id, and if you got it, send back the date and time, then do the same for the rest of the incomings. V1 No OTPV1 No OTP To understand better, how OTP works, we start with a simple process. What we can do with processes? We can start them - which in Elixir world is called spawning -, we can send message to them and we can receive message from them. Also we can wire-up processes together, which is called linking, so if one process failed, the other one would fail too, or get notified - depending on how we linked them. This is the basics of fantastic supervision trees that creates a robust, fault tolerant app! To schedule getting updates from Telegram and also keeping track of last update id (the offset), we add this function: defp schedule_updates(offset, sleep_ms \\ 0) do s = self() Task.start(fn -> if sleep_ms > 0 do Process.sleep(sleep_ms) end res = Nadia.get_updates offset: offset, timeout: @send_timeout case res do {:ok, updates} -> send(s, {:updates, updates}) _ -> send s, res end end) end Task.start is just calling builtin function, spawn, to create a process - with some ceremonial helper properties that we ignore them for now. self() is the pid/process-id of the current running process that we are inside. Very much like this or self in other Object Oriented Programming Languages. First version of our handler would be: def handle_v1({:updates, []}, state) do schedule_updates(0) {:noreply, state} end def handle_v1({:updates, updates}, state) do l = state {max_id, res} = append_update 0, l, updates answer_incoming res schedule_updates(max_id + 1) # if succeeded, state would be empty list state = [] {:noreply, state} end And our main recursive loop would be: def handle_v1_loop(state) do state = if state == :start do schedule_updates(0) [] else state end receive do {:updates, []} -> {:noreply, state} = handle_v1({:updates, []}, state) handle_v1_loop(state) {:updates, updates} -> {:noreply, state} = handle_v1({:updates, updates}, state) handle_v1_loop(state) end end To run our app, go to command line and type $ iex -S mix. The Elixir REPL will start, running our application. To start the main loop, inside the REPL, enter: iex(1)> spawn fn -> Acrobot.Bot.handle_v1_loop(:start) end Now if you send something to this bot, it will return current date and time. As you see inside the body of handle_v1_loop(...) function, there are some concerns. First we have to initialize the starting state. Second, we need to handle different kinds of received messages, using different handlers. This is OTP! Instead of stuffing everything inside a recursive loop, OTP will create that recursive loop for us. We just have to hand over a bunch of callbacks to OTP for initialization and handling different kinds of messages. It’s very much like implementing an interface in other OOP languages. The way our code is written, it’s not fault tolerant and if it fails, it brings down the whole app. Let’s instead just write some callbacks and let the OTP take over controlling things. V2 OTPV2 OTP Inside file /lib/acrobot/application.ex resides the root supervisor of our application - a bit like main function in other languages, just far more powerful. First let’s add a supervisor for all Tasks in the application. Fortunately there is a builtin one which we will add it to the children inside application.ex - the Acrobot.Application module. children = [ # Starts a worker by calling: Acrobot.Worker.start_link(arg1, arg2, arg3) # worker(Acrobot.Worker, [arg1, arg2, arg3]), supervisor(Task.Supervisor, [[name: Acrobot.TaskSupervisor]]) ] Here we added Task.Supervisor to the children list of our application supervisor. Yeah! Supervisors can supervise other supervisors too! Acrobot.TaskSupervisor is just an alias name, for convenience. Now we redefine schedule_updates function to take advantage of this supervisor: defp schedule_updates(offset, sleep_ms \\ 0) do s = self() Task.Supervisor.start_child(Acrobot.TaskSupervisor, fn -> if sleep_ms > 0 do Process.sleep(sleep_ms) end res = Nadia.get_updates offset: offset, timeout: @send_timeout case res do {:ok, updates} -> send(s, {:updates, updates}) _ -> send s, res end end) end And the callbacks that we will pass to OTP, inside /lib/acrobot/bot.ex: defmodule Acrobot.Bot do use GenServer require Logger @moduledoc """ Our fantastic bot! """ @error_delay 15 # seconds @start_delay 5 # seconds @rcvd_timeout 30 # seconds def start_link() do GenServer.start_link( __MODULE__ , [], []) end ## server callbacks def init(state) do schedule_updates(0, @start_delay) {:ok, state} end def handle_info({:failed, update}, state) do l = state state = l ++ [update] {:noreply, state} end def handle_info({:updates, []}, state) do schedule_updates(0) {:noreply, state} end def handle_info({:updates, updates}, state) do l = state {max_id, res} = append_update 0, l, updates answer_incoming res schedule_updates(max_id + 1) # if succeeded, state would be empty list state = [] {:noreply, state} end def handle_info({:error, msg}, state) do Logger.error "#{inspect msg}" schedule_updates(0, @error_delay) {:noreply, state} end def handle_info(msg, state) do Logger.warn "unknown #{inspect msg}" schedule_updates(0, @error_delay) {:noreply, state} end ## helpers # helpers we've added so far, do here ... end As you see we are implementing a behaviour (which is like an interface in OOP); by use GenServer we mean this module implements GenServer behaviour. start_link help link and start this module as a new process, init does the initialization and handle_info handles (receives) updates. There are other handlers we can add that have different usage, which we could read about them inside GenServer docs and samples - read the docs! And we have to add it to the children of our root supervisor - our Application - inside application.ex - the Acrobot.Application module. children = [ # Starts a worker by calling: Acrobot.Worker.start_link(arg1, arg2, arg3) # worker(Acrobot.Worker, [arg1, arg2, arg3]), supervisor(Task.Supervisor, [[name: Acrobot.TaskSupervisor]]), worker(Acrobot.Bot, []) ] Now if anything crashes beyond our expectations, we will see it inside the log, and our processes will simply get restarted (and yes there are options one can modifies!). This was the essence of Elixir programming! ConclusionConclusion Of-course the original bot I’ve created, spawns new processes per user, does the bookkeeping of processes using gproc and other things. But these three were the essential tools one needs to think in Elixir. Also I’ve played with dyalizer, a fantastic tool that brings compile-time code analysis to Elixir. Overall a pleasant experience but I wasn’t going on as fast as I’d like due to: I’ve never implemented a large code base in a dynamic language. It was hard for me to find my way around. To be fair, Elixir was far less painful than the others (with some help from Atom). Finding things, libraries, functions was going on slowly - (My Side Problem - not familiar with ecosystem). Writing TDD - again I’m not that accustomed to TDD in general (Except for main functionality, My Side Problem - not familiar with ecosystem). Multi clause functions; the debugging; it was hard for me to find out which data is malformed or which clause is wrong - though it was amazing! Handling state; pulling state by your teeth every where - getting used to GenServer could eliminate this (My Side Problem - not familiar with ecosystem). Finding spec of functions - what does these parameters, that start_link accepts in each case, mean? (My Side Problem - not familiar with ecosystem) Non-pleasant corner cases like that Task (and to some extend Agent) are not very cooperative when called from OTP - I did not expect that and finding out what’s wrong was not going on fast enough (Probably My Side Problem - not familiar with ecosystem, but I do not like this). Things I liked most, multi clause functions, pattern matching, pipe function chains (F# developers love this and to some extent it resembles LINQ for C# developers) and :observer.start shows your app as an alive organism before your eyes! Elixir ecosystem is not that young, but you might find yourself in need for something that you should create, though you can use many existing Erlang libraries - I’ve use couchbeam for connecting to CouchDB without a hitch! Complete code can be found here.
https://www.codementor.io/kavehshahbazian/elixir-to-start-with-9pkd2vbyy
CC-MAIN-2018-09
refinedweb
3,343
63.59
Introducing the Command Line Parser Library to make parsing command line arguments easier November 10, 2015 3 Comments If you’ve worked extensively with .NET console applications then you’ve probably encountered difficulties with parsing the command line arguments. They are passed into the args argument of the Main function. Then it’s your task to investigate if the caller has passed in all necessary arguments: - Have all the mandatory arguments been passed in? - What default value do we take for optional arguments? - What about the ordering of arguments? …et cetera, the list could grow a lot longer. Fortunately there are libraries that can help you parse the arguments. One such library is called Command Line Parser Library available from NuGet here. You can find its project page here with some initial code examples. You can install the library from within Visual Studio: Upon installation you’ll see a readme.txt file in Visual Studio with some extra code examples. The most basic usage of the library is that you create a custom class that will hold the argument properties. E.g. if your application requires a name and an age argument then you create a class with those properties and decorate them with attributes from the parser library. Let’s see how it works in code. Consider the following class: public class ProgramArguments { [Option('n')] public string Name { get; set; } [Option('a')] public int Age { get; set; } } The Option attribute has a range of overloaded versions and named arguments. The above example means that Name will be populated with the argument preceded by “-n”. The same is “-a” for the Age. It is very common to indicate the role of an argument: myapplication -n “Andras” -a 36 The ordering shouldn’t matter: myapplication -a 36 -n “Andras” The parser library can handle that of course. You can populate the ProgramArguments object properties as follows: static void Main(string[] args) { ProgramArguments arguments = new ProgramArguments(); CommandLine.Parser.Default.ParseArguments(args, arguments); } Providing the arguments… -n “Andras” -a 36 …to the application will in fact correctly populate the Name and Age properties of the ProgramArguments object. The library can handle a lot of different cases. View all various C# language feature related posts here. Pingback: Introducing the Command Line Parser Library to make parsing command line arguments easier | Dinesh Ram Kali. Thanks Andras, your code worked like a charm It’s telling me it can’t convert from my version of Program Arguments to System.type.
https://dotnetcodr.com/2015/11/10/introducing-the-command-line-parser-library-to-make-parsing-command-line-arguments-easier/
CC-MAIN-2021-49
refinedweb
414
55.44
Hello everyone, here is part 10 continues to focus on the client and walks through the detailed flow of events that takes place when a sample application is installed. The application installation is tracked in the logs from acquisition during policy update through full execution. In addition, relevant WMI namespaces and the SQL compact file on the client are discussed. Next in the series Steve will talk about task sequencing as a mechanism for deploying applications. Posts in the series Go straight to the playlist You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
https://techcommunity.microsoft.com/t5/configuration-manager-blog/video-tutorial-clients-and-applications-behind-the-scenes/ba-p/1475669
CC-MAIN-2022-27
refinedweb
107
64.61
In GTM, it's usually by replacing the var name with {{var name}}. How do I do in this Adobe launch? I have a custom JS that's simply not reading directly from the console log. However, if I separately declare a Data Element that's a JS variable that reads from performance.timing.requestStart, I can see the value in Cloud Debugger. How can I apply such variables here for startTime and endTime var in below code? thanks. function getPageLoadTime() { if (typeof(performance) !== 'undefined' && typeof(performance.timing) == 'object') { var timing = performance.timing; // fall back to less accurate milestones var startTime = performance.timing.requestStart; var endTime = performance.timing.loadEventEnd; if (startTime && endTime && (startTime < endTime)) { return (endTime - startTime); } } return 'data not available'; } AlexisCazes MVP AlexisCazes MVP 09-04-2019 You do not run your code at the time. It needs to be run at the right time of the page lifecycle. Ideally you would want to run performance code at unload time that way you know that your page is fully loaded (unless people nevigate before the page is fully loaded...). We do it in this way: sanmeetw1519854 09-04-2019 What Alexis has suggested is correct. The only downside is you wont get data for the exit pages I am not exactly sure about your code to execute this. I can suggest best practices, but providing a granular solution will be difficult sanmeetw1519854 sanmeetw1519854 An event will add up all the values that you pass to it. You wont be able to achieve the objective. Pass the value to an eVar. You will need to do this analysis in excel sanmeetw1519854 Adil, it will be custom JS, you will use _satellite.getVar(<name of data element>) function in your to get the value of each data element, perform your operation on it and return the final value as output of the JS data element. Hope this helps. Sanmeet sanmeetw1519854 Hey Adil, 1) Go to data elements 2) Create a new one with core extension and data element type as custom code 3) open editor 4) Just enter the code without the requirement to put everything as function but still ending with a return statement 5) Call this data element wherever you want in Launch using the "%" sign, it will do something similar to "{{" in GTM Hope this helps Sanmeet adilk Hi Alexis, If I had to configure the below in Adobe Launch, how would I go about with this? In Rules section, I can't find an event for unload. How can this be done via Adobe Launch? Should all of the above steps happen in the same Rule? Wait for unload, save to cookies and then set variables > Send beacon ? Thanks adilk ok, here's how cloud debugger is reading my events after setting up the below in AA report suite settings: event 55 = counter = page load time denominator, always 1 eventt56 = numeric = %SiteSpeed: Page Load Time% event57 = numeric = %SiteSpeed: fetchStart% event58 = numeric = %SiteSpeed: eventLoadEnd% values in debugger: event55=1 event56=-1554752941276 event57=1554752941276 event58 -- event 57 is correctly pulling value for performance.timing.fetchStart from the console event 58 is supposed to pull performance.timing.eventLoadEnd but is coming out as blank, leading to event 56 getting a negative value event 56 is a Custom code as a data element: return _satellite.getVar('SiteSpeed: loadEventEnd') - _satellite.getVar('SiteSpeed: fetchStart'); If I made the change in AA report suite settings for event58 as numeric type an hour ago, should it immediately show in Cloud Debugger when I reload the page? What else could be wrong here. adilk Yes, so if event 56 = sum of all the timestamp differences and event event 55 = 1 (which is actually a page load counter) and will be a constant at 1 , I could create a calculated metric in AA that adds up the sum of event 56 and divides it by the sum of event 55 to get an average of load time. I'm following this article for context: What do you think about this approach? and why isn't event 56 showing the timestamp difference as an integer in cloud debugger? adilk Hi Sanmeet, In my Custom JS, here's what I have as the code: return _satellite.getVar('SiteSpeed: loadEventEnd') - _satellite.getVar('SiteSpeed: fetchStart'); When I check Cloud Debugger to know if the var value got passed as an event in a rule that I setup, it shows as blank. It would be event 56 here - which I have configured to accept numeric values instead of a counter. What could be the reason for this? Thanks. adilk Hi Sanmeet, I'm not a 100% clear but let's try with an example as it'll make it easier for me: I have two separate data elements in Adobe Launch: 1. SiteSpeed: fetchStart JS variable This pulls the timestamp (including ms) from the browser console log: performance.timing.fetchStart 2. SiteSpeed:loadEventEnd JS variable This pulls the timestamp (including ms) from the browser console log: performance.timing.loadEventEnd If I wanted to create a third data element that showed the timestamp by doing this operation: SiteSpeed:loadEventEnd - SiteSpeed: fetchStart and return the value as an integer. Would the third variable be a Custom JS and what would the code look like? Thanks.
https://experienceleaguecommunities.adobe.com/t5/adobe-experience-platform-launch/how-to-use-a-js-variable-in-another-custom-js-script/qaq-p/307723
CC-MAIN-2021-17
refinedweb
881
61.16
Hello again. I am trying to code a specific target depth. I am using pymavlink to send a target depth command as per the code below. It seems to try to go down to the specified depth but the motors aren’t running continuously. Our vehicle has a density lower than water so our vehicle goes down and up without actually reaching the target depth. I will post a link to a video of the vehicle to maybe help with diagnosing as well as the code. I also ran a modified version of this code where the depth target command is sent inside the while loop.-Same thing happened. Also after the execution of the code, when it comes time to disarm the vehicle, it doesn’t respond. The code waits in the master.motors_disarmed_wait() section until I manually interrupt the code. has anyone else experienced a similar problem? I am also sending a yaw value of 60%clockwise and it is not performing a yaw rotation at all. The Code: from pymavlink import mavutil import time master = mavutil.mavlink_connection("udpin:192.168.2.1:14550") master.wait_heartbeat() boot_time = time.time() print("Successful Connection") def set_target_depth(depth): master.mav.set_position_target_global_int_send( int(1e3 * (time.time() - boot_time)), # ms since boot master.target_system, master.target_component, coordinate_frame=mavutil.mavlink.MAV_FRAME_GLOBAL_INT, type_mask=0xdfb, lat_int=0, lon_int=0, alt=depth, vx=0, vy=0, vz=0, afx=0, afy=0, afz=0, yaw=0, yaw_rate=0 ) def send_pwm(x =0, y=0 , z = 500, yaw=0 , buttons=0): """Send manual pwm to the axis of a joystick. Relative to the vehicle x for right-left motion y for forward-backwards motion z for up-down motion, z -> {0-1000} r for the yaw axis clockwise is -1000 counterclockwise is 1000 buttons is an integer with """ print(f"running for seconds, with pwm x:{x},y={y}, z={z} \n yaw:{yaw}, buttons:{buttons}") master.mav.manual_control_send(master.target_system, x,y,z,yaw,buttons) ##Arm Vehicle master.arducopter_arm() master.motors_armed_wait() #Flight Mode Setup FLIGHT_MODE = 'ALT_HOLD' FLIGHT_MODE_ID = master.mode_mapping()[FLIGHT_MODE] while not master.wait_heartbeat().custom_mode == FLIGHT_MODE_ID: master.set_mode(FLIGHT_MODE) ##Run motors for 20 seconds tstart = time.time() set_target_depth(-1.5) while time.time()<tstart+20: send_pwm(yaw = 600) master.arducopter_disarm() master.motors_disarmed_wait() The Video Link: IMG_3424.MOV - Google Drive Our Power Setup: We are using a 12V 60A adapter and powering the vehicle directly from the wall. a further voltage regulator brings the voltage to 5V for use in the raspberry and pixhawk. We are using a XT90 pixhawk power module to power the 6 T200 thrusters. Control setup. we are using a raspberry as a companion, the Pixhawk as the autopilot and ardusub. I am running pymavlink on my ubuntu computer with python 3.8.10 I can provide further information if necessary. I had asked this question as a reply to one of the posts I had made earlier so I am putting it here so it can be found easier.
https://discuss.bluerobotics.com/t/vehicle-isnt-executing-target-depth-command-correctly/10539
CC-MAIN-2021-39
refinedweb
495
50.63
Kubernetes: It's alive! Daniel Albuschat Jan 20 Updated on Mar 08, 2018 I recently found an interest in Kubernetes and learned about it at night, while working at something not web-related at day. As part of my learning journey I wanted to quickly see and experience how Kubernetes actually works in action. So I decided to write a few services that can be used to trigger and observe certain behavior of Kubernetes. I started with Load Balancing, Self Healing of Services and Auto Scaling depending on CPU utilization. In this blog post I will explain how each service works and how Kubernetes behaves in practice. Note that this was the first time I wrote Go, so I take no guarantee that the code is not shitty or against Go conventions and best practices that I do not yet know. :-) This blog post addresses anyone who already has a Kubernetes cluster up and running. You should know what a Pod is, a Replica Set or a Deployment, and can build Docker containers and have used a Docker Registry. If you do not run a Kubernetes cluster already, I can recommend the book "Kubernetes: Up & Running" and/or the blog post "How to Build a Kubernetes Cluster with ARM Raspberry Pi" by Scott Hanselman. If you don't know what Kubernetes is or how it works, you can read the excellent series of blog posts "Understanding Basic Kubernetes Concepts" by Puja Abbassi from giantswarm.io. For the impatient Before running kube-alive on your cluster, make sure that you have the following: - kubectl installed and configured to a running cluster (check that "kubectl get nodes" gives you a list of at least one node in state "Ready") - bash - Your cluster runs on Linux on amd64 or ARM CPUs If you do not have a cluster up and running already, I recommend the already mentioned article by Scott Hanselman to start a cluster on Raspberry Pis, or you can use Minikube to run a local cluster on your PC or Mac. If you just want to deploy kube-alive to your cluster and see it in action, you can do this with this single command: curl -sSL | bash Using 192.168.178.79 as the exposed IP to access kube-alive. deployment "getip-deployment" created service "getip" created deployment "healthcheck-deployment" created service "healthcheck" created deployment "cpuhog-deployment" created service "cpuhog" created horizontalpodautoscaler "cpuhog-hpa" created deployment "frontend-deployment" created service "frontend" created FINISHED! You should now be able to access kube-alive at. Load-Balancing The most basic capability of Kubernetes is load balancing between multiple services of the same kind. To observe whether the request was served from the same or from different instances, I decided to let the service return it's host's IP address. In order to run a service in Kubernetes, you need to a) write the service, b) build a container hosting the service, c) push the container to a registry, d) create an object in Kubernetes that runs your container and finally e) make the service accessible from outside the cluster. Phase A: Writing the Service So let's dig into the code. I wrote a server in Go that serves on port 8080, parses the output of the command "ip a" and returns the container's IP address. package main import "fmt" import "bufio" import "os/exec" import "log" import "strings" import "net/http" /** getip starts an HTTP server on 8080 that returns nothing but this container's IP address (the last one outputted by "ip a"). **/ func getIP() string { // Left out for brevity, see } func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, getIP()) }) fmt.Printf("'getip' server starting, listening to 8080 on all interfaces.\n") http.ListenAndServe(":8080", nil) } Phase B: Building the Container Since everything running in Kubernetes must be a container, I wrote a Dockerfile to run this service: FROM golang COPY main.go /go/src/getip/main.go RUN go install getip ENTRYPOINT /go/bin/getip This Dockerfile is simple: It uses a golang base container that is prepared to compile and run Go code. It then copies over the only source code file, main.go and compiles and installs it to /go/bin/ using "go install". The installed binary /go/bin/getip is set as the Entrypoint, so that when no argument is given to docker run, it executes our service. You can build the container using: docker build . Note that there is a "." at the end of the command, meaning that you must have cd'ed to the getip source directory before executing docker build. After docker build finishes, you will be able to see the new container with a new, randomly generated image id via docker images The container is only available locally on the machine that it has been built. Since Kubernetes will run this container on any node that it sees fit, the container must be made available on all nodes. That's where a Docker Registry steps into the game, which is basically a remote repository for Docker containers that is available from all nodes. Phase C: Pushing the Container to a Registry I first tried to set up a local registry, which can be done, but the setup is not portable across clusters. That's why I decided to simply use Docker's own registry,. To push your freshly built container, you first need to register at Docker Hub, then tag the container with the repository, desired container name and an optional tag. If no tag is given, "latest" is assumed. docker tag <your-repository>/getip <image id> # tag the docker image with your repository name and the service name, such as "getip" docker login # enter your username and password of now. docker push <your-repository>/getip # and then push your container It is now available to be pulled (without authorization) by anyone - including your Kubernetes nodes. Phase D: Define a Replica Set To let Kubernetes know that it should run this container as a service, and to run multiple instances of this service, you should use a Replica Set. I wrapped the Replica Set into a Deployment to easily upgrade the service later: apiVersion: apps/v1beta2 kind: Deployment metadata: name: getip-deployment labels: app: getip spec: replicas: 4 selector: matchLabels: app: getip template: metadata: labels: app: getip spec: containers: - name: getip image: <your-repository>/getip ports: - containerPort: 8080 I set the number of replicas to 4, which means that Kubernetes will do everything it can to always have exactly 4 instances running at any time. However, this does not give us a single URL to connect to these instances. We will use a Service to Load Balance between these instances: kind: Service apiVersion: v1 metadata: name: getip spec: selector: app: getip ports: - protocol: TCP port: 80 targetPort: 8080 This service provides a single, load-balanced URL to access the individual service instances. It remaps default HTTP port 80 to the service's own port 8080 in the process. The service will be available as or, even shorter, as on any running Kubernetes Pod. However, this service is only available from inside Kubernetes and not from "outside" the cluster. Phase E: Publish the Service I decided to build my own nginx container to serve the static HTML and JavaScript files that make up the frontend and publish the services from a specific IP. events { # empty } http { server { root /www/data; location / { # for the frontend SPA } # Forward traffic to <yourip>/getip to the getip service. location /getip { proxy_pass; } # I have left out the other services like "cpuhog" and "healthcheck" here for brevity. # See their code on # Allow WebSocket connections to the Kubernetes API: location /api { proxy_pass; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_set_header Authorization "Bearer %%SERVICE_ACCOUNT_TOKEN%%"; } } } So we see that nginx expects the SPA in /www/data/, which will be the target of COPY commands in our Dockerfile. The service getip is reached via Kubernetes DNS, which will automatically resolve a service's name to it's Cluster IP, which in turn load-balances requests to the service instances. The third location /api is used by the frontend to receive information about running pods. (Currently, the full API is exposed with full admin privileges, so this is highly insecure - do it in isolated environments only! I will fix this in the near future.) Here's the Dockerfile for the frontend service: FROM nginx COPY nginx.conf /etc/nginx/ COPY index.html /www/data/ COPY output/main.js /www/data/output/main.js COPY run_nginx_with_service_account.sh /kube-alive/ CMD /kube-alive/run_nginx_with_service_account.sh The shell script run_nginx_with_service_account.sh will substitute variables in the nginx.conf to use the Kubernetes Service Account token in the authorization header to let nginx handle the authorization so that the frontend does not have to. So now we are prepared to put the last piece of the puzzle into place: A Replica Set to run the frontend and a Service that externally publishes the frontend. Note that I wrapped the Replica Set into a Deployment again: apiVersion: apps/v1beta2 kind: Deployment metadata: name: frontend-deployment labels: app: frontend spec: replicas: 1 selector: matchLabels: app: frontend template: metadata: labels: app: frontend spec: containers: - name: frontend imagePullPolicy: Always image: <your-repository>/frontend_amd64 ports: - containerPort: 80 -------- kind: Service apiVersion: v1 metadata: name: frontend spec: selector: app: frontend externalIPs: - <put your external IP, e.g. of your cluster's master, here> ports: - protocol: TCP port: 80 targetPort: 80 That's it! You can kubectl apply this after you inserted a valid externalIP and everything should be up and running to execute your first experiment with Kubernete's load balancing. Reaching to the IP that your "kubectl" is configured against, should give you this UI: … followed by more experiments. These all follow the same concept as getip, you can have a look at their code and deployment yamls here: Self-Healing The code of the Self-Healing experiment is here: Rolling Updates The code of the Rolling Updates experiment is here: Auto Scaling (cpu-based) The code of the Auto Scaling experiment is here: I named the service "cpuhog" because it uses as much CPU as it can for 2 seconds for every request. I plan to add more experiments in the future, such as an experiment for rolling updates using Deployments. I hope that you found this blog post and the kube-alive services useful and would be thankful if you could leave feedback in the comments. Maybe one day kube-alive will be a starting point to see Kubernetes behaviour live in action for many starters and engineers that are evaluating Kubernetes for their own use. Update from 01/25/2018: I removed the security warning, because security on the latest version of kube-alive has been tightened. Only a portion of the API is exposed (pods in the kube-alive namespace), and the frontend runs with a service account that has access only to the dedicated kube-alive namespace and only to read and list Pods. Hence, there is not much more information available via the API than is visible in the frontend anyways. Update from 03/08/2018: Updated the gifs to the new, improved visuals and added the rolling updates experiment. Creating a CI/CD pipeline with a git repository in ~30 seconds using Terraform and AWS Kyle Galbraith - May 14 What's your server-side speed target? Robb Shecter - May 14 GraphCool Continuous Deployment with Bitbucket Pipeline John Paul Ada - May 14 Deploy a RESTful API using Laravel and Docker José Fernando Cordova - May 13 Daniel, my team and I are Deploying microservices and since you have a developer background maybe you can help. Our problem is we do not have a service discovery built out and all our calls to other microservices have to exit our cloud network get NATed and then come back in to reach other microservices. Is there a poor man's way to implement service discovery without creating a service registry. Making hundreds of outbound calls sometimes exhausts all outbound ports or causes unwanted latency. I have seen NGINX used along with something called console. We also looked at creating a DNS server for internal communication and separate outbound and inbound traffic but that would require maintaining internal DNS, adding internal and external endpoints to everything. Any other options ? Mobeus Ingress in the right way, such as Traefik of nginx ingress controller. I recommend taking a look at this project istio.io service mesh. From what I read on istio.io, it seems to run on top of Kubernetes? For service discovery, wouldn't raw Kubernetes be sufficient? However, this would mean to re-architect the infrastructure anyways, especially when it does not yet run on containers. Maybe there is something more lightweight if you don't want to go all the way? (Although, when there are more problems to solve, such as load balancing, failure recovery or scaling, it might be totally worth it.) I'm not working in the web space, so I can not give a recommendation. Kubernetes has been a free-time endeavor so far. Sorry this is pre k8s. I am aware that K8s will solve this issue. We will be jumping on ACS soon to be AKS but need a tactical solution until that materializes. Thx... Mobeus Why build your own Nginx service, as opposed to writing an Ingress and deploying an Ingress controller? I honestly think that the Ingress is way more complicated for beginners to understand then a service type LoadBalancer routing to a reverse proxy. At least I had a hard time in the beginning understanding the Ingress really works. From what I understand, Ingresses are just a way of saying "Here's a path, it corresponds to this service." However, setting up an Ingress controller is, in some cases, needlessly complicated imo. I like that minikube and GKE ship with one by default, but that didn't prepare me for having to set one up on my own, especially given if I want it to use HTTPS. Like Michael already answered, the Service with an externalIP was a very simple solution, while an Ingress is much more complex. Actually, I wouldn't even know how to use an Ingress e.g. on a minikube or a local cluster that does not have a dedicated load balancer. It might be worth a look, but currently my priority is: 1) finish CI for multiarch images, so that you can deploy kube-alive on ARM and amd64 without changing anything in the manifests (almost done) 2) fix the security problems I mentioned in the article and 3) add more experiments, like observing live how a rolling update happens. Then, at prio 4) I might add support for GKE, AKS and EKS.
https://dev.to/danielkun/kubernetes-its-alive-2ndc
CC-MAIN-2018-22
refinedweb
2,475
59.03
react-plotly.js A plotly.js React component from Plotly. The basis of Plotly's React component suite. Installation $ npm install react-plotly.js plotly.js Quick start The easiest way to use this component is to import and pass data to a plot component: import React from 'react'; import Plot from 'react-plotly.js'; class App extends React.Component { render() { return ( <Plot data={[ { x: [1, 2, 3], y: [2, 6, 3], type: 'scatter', mode: 'lines+markers', marker: {color: 'red'}, }, {type: 'bar', x: [1, 2, 3], y: [2, 5, 3]}, ]} layout={{width: 320, height: 240, title: 'A Fancy Plot'}} /> ); } } You should see a plot like this: For a full description of Plotly chart types and attributes see the following resources: State management. Here is a simple example of how to capture and store state in a parent object: class App extends React.Component { constructor(props) { super(props); this.state = {data: [], layout: {}, frames: [], config: {}}; } render() { return ( <Plot data={this.state.data} layout={this.state.layout} frames={this.state.frames} config={this.state.config} onInitialized={(figure) => this.setState(figure)} onUpdate={(figure) => this.setState(figure)} /> ); } } Refreshing the Plot This component will refresh the plot via Plotly.react if any of the following are true: - The revisionprop is defined and has changed, OR; - One of data, layoutor confighas changed identity as checked via a shallow ===, OR; - The number of elements in frameshas changed Furthermore, when called, Plotly.react will only refresh the data being plotted if the identity of the data arrays (e.g. x, y, marker.color etc) has changed, or if layout.datarevision has changed. In short, this means that simply adding data points to a trace in data or changing a value in layout will not cause a plot to update unless this is done immutably via something like immutability-helper if performance considerations permit it, or unless revision and/or layout.datarevision are used to force a rerender. API Reference Basic Props Warning: for the time being, this component may mutate its layout and data props in response to user input, going against React rules. This behaviour will change in the near future once is completed. Note: To make a plot responsive, i.e. to fill its containing element and resize when the window is resized, use style or className to set the dimensions of the element (i.e. using width: 100%; height: 100% or some similar values) and set useResizeHandler to true while setting layout.autosize to true and leaving layout.height and layout.width undefined. This can be seen in action in this CodePen and will implement the behaviour documented here: Callback signature: Function(figure, graphDiv) The onInitialized, onUpdate and onPurge props are all functions which will be called with two arguments: figure and graphDiv. figureis a serializable object with three keys corresponding to input props: data, layoutand frames. - As mentioned above, for the time being, this component may mutate its layoutand dataprops in response to user input, going against React rules. This behaviour will change in the near future once is completed. graphDivis a reference to the (unserializable) DOM node into which the figure was rendered. Event handler props Event handlers for specific plotly.js events may be attached through the following props: Customizing the plotly.js bundle By default, the Plot component exported by this library loads a precompiled version of all of plotly.js, so plotly.js must be installed as a peer dependency. This bundle is around 6Mb unminified, and minifies to just over 2Mb. If you do not wish to use this version of plotly.js, e.g. if you want to use a different precompiled bundle or if your wish to assemble you own customized bundle, or if you wish to load plotly.js from a CDN, you can skip the installation of as a peer dependency (and ignore the resulting warning) and use the createPlotComponent method to get a Plot component, instead of importing it: // simplest method: uses precompiled complete bundle from `plotly.js` import Plot from 'react-plotly.js'; // customizable method: use your own `Plotly` object import createPlotlyComponent from 'react-plotly.js/factory'; const Plot = createPlotlyComponent(Plotly); <script> tag For quick one-off demos on CodePen or JSFiddle, you may wish to just load the component directly as a script tag. We don't host the bundle directly, so you should never rely on this to work forever or in production, but you can use a third-party service to load the factory version of the component from, for example,[email protected]/dist/create-plotly-component.js. You can load plotly.js and the component factory with: <script src=""></script> <script src="[email protected]/dist/create-plotly-component.js"></script> And instantiate the component with const Plot = createPlotlyComponent(Plotly); ReactDOM.render( React.createElement(Plot, { data: [{x: [1, 2, 3], y: [2, 1, 3]}], }), document.getElementById('root') ); You can see an example of this method in action here. Development To get started: $ npm install To transpile from ES2015 + JSX into the ES5 npm-distributed version: $ npm run prepublishOnly To run the tests: $ npm run test
https://reactjsexample.com/a-plotly-js-react-component-from-plotly/
CC-MAIN-2021-21
refinedweb
844
56.45
By John P Mechalas, Isayah Reed Published:08/29/2016 Last Updated:08/29/2016 In Part 3 of the Intel® Software Guard Extensions (Intel® SGX) tutorial series we’ll talk about how to design an application with Intel SGX in mind. We’ll take the concepts that we reviewed in Part 1, and apply them to the high-level design of our sample application, the Tutorial Password Manager, laid out in Part 2. We’ll look at the overall structure of the application and how it is impacted by Intel SGX and create a class model that will prepare us for the enclave design and integration. You can find the list of all of the published tutorials in the article Introducing the Intel® Software Guard Extensions Tutorial Series. While we won’t be coding up enclaves or enclave interfaces just yet, there is source code provided with this installment. The non-Intel SGX version of the application core, without its user interface, is available for download. It comes with a small test program, a console application written in C#, and a sample password vault file. This is the general approach we’ll follow for designing the Tutorial Password Manager for Intel SGX: The first step in designing an application for Intel SGX is to identify the application’s secrets. A secret is anything that is not meant to be known or seen by others. Only the user or the application for which it is intended should have access to a secret, and it should not be exposed to others users or applications regardless of their privilege level. Potential secrets can include financial information, medical records, personally identifiable information, identity data, licensed media content, passwords, and encryption keys. In the Tutorial Password Manager, there are several items that are immediately identifiable as secrets, shown in Table 1. Secret The user’s account passwords The user’s account logins The user’s master password or passphrase The master key for the password vault The encryption key for the account database Table 1: Preliminary list of application secrets. These are the obvious choices, but we’re going to expand this list by including all of the user’s account information and not just their logins. The revised list is shown in Table 2. Secret The user’s account passwords The user’s account logins information The user’s master password or passphrase The master key for the password vault The encryption key for the account database Table 2: Revised list of application secrets. Even without revealing the passwords, the account information (such as the service names and URLs) is valuable to attackers. Exposing this data in the password manager leaks valuable clues to those with malicious intent. With this data, they can choose to launch attacks against the services themselves, perhaps using social engineering or password reset attacks, to obtain access to the owner’s account because they know exactly who to target. Once the application’s secrets have been identified, the next step is to determine their origins and destinations. In the current version of Intel SGX, the enclave code is not encrypted, which means that anyone with access to the application files can disassemble and inspect it. By definition, something cannot be a secret if it is open to inspection, and that means that secrets should never be statically compiled into enclave code. An application’s secrets must originate from outside its enclaves and be loaded into them at runtime. In Intel SGX terminology, this is referred to as provisioning secrets into the enclave. When a secret originates from a component outside of the Trusted Compute Base (TCB), it is important to minimize its exposure to untrusted code. (One of the main reasons why remote attestation is such a valuable component of Intel SGX is that it allows a service provider to establish a trusted relationship with an Intel SGX application, and then derive an encryption key that can be used to provision encrypted secrets to the application that only the trusted enclave on that client system can decrypt.) Similar care must be taken when a secret is exported out of an enclave. As a general rule, an application’s secrets should not be sent to untrusted code without first being encrypted inside of the enclave. Unfortunately for the Tutorial Password Manager application, we do need to send secrets into and out of the enclave, and those secrets will have to exist in clear text at some point. The end user will be entering his or her account information and password via a keyboard or touchscreen, and recalling it at a future time as needed. Their account passwords will need to be shown on the screen, and even copied to the Windows* clipboard on request. These are core requirements for a password manager application to be useful. What that means for us is that we can’t completely eliminate the attack surface: we can only minimize it, and we’ll need some mitigation strategy for dealing with secrets when they exist outside the enclave in plain text. Table 3: Application secrets, their sources, and their destinations. Potential security risks are denoted with an asterisk (*). Table 3 adds the sources and destinations for the Tutorial Password Manager’s secrets. Potential problems—areas where secrets may be exposed to untrusted code—are denoted with an asterisk (*). Once the secrets have been identified, it’s time to determine the boundary for the enclave. Start by looking at the data flow of secrets through the application’s core components. The enclave boundary should: The data flows and chosen enclave boundary for the Tutorial Password Manager application are shown in Figure 1. Figure 1: Data flow for secrets in the Tutorial Password Manager. Here, the application secrets are depicted as circles, with blue circles representing secrets that will exist in plain text (unencrypted) at some point during the application’s execution and green circles representing secrets that are encrypted by the application. The enclave boundary has been drawn around the encryption and decryption routines, the key derivation function (KDF) and the random number generator. This does several things for us: Unfortunately, we have issues with unencrypted secrets crossing the enclave boundary that we simply can’t avoid. At some point during the Tutorial Password Manager’s execution, a user will have to enter a password on the keyboard or copy a password to the Windows clipboard. These are insecure channels that can’t be placed inside the enclave, and the operations are absolutely necessary for the functioning of the application. This is potentially a huge problem, which is compounded by the decision to build the application on top of a managed code base. There are no complete solutions for securing unencrypted secrets outside the enclave, only mitigation strategies that reduce the attack surface. The best we can do is minimize the amount of time that this information exists in a form that is easily compromised. Here is some general advice for handling sensitive data in untrusted code: For the Tutorial Password Manager project, we have to work with both native and managed code. In native code, we’ll allocate wchar_t and char buffers, and use SecureZeroMemory to wipe them clean before freeing them. In the managed code space, we’ll employ .NET’s SecureString class. When sending a SecureString to unmanaged code, we’ll use the helper functions from System::Runtime::InteropServices to marshal the data. using namespace System::Runtime::InteropServices; LPWSTR PasswordManagerCore::M_SecureString_to_LPWSTR(SecureString ^ss) { IntPtr wsp= IntPtr::Zero; if (!ss) return NULL; wsp = Marshal::SecureStringToGlobalAllocUnicode(ss); return (wchar_t *) wsp.ToPointer(); } When marshaling data in the other direction, from native code to managed code, we have two methods. If the SecureString object already exists, we’ll use the Clear and AppendChar methods to set the new value from the wchar_t string. password->Clear(); for (int i = 0; i < wpass_len; ++i) password->AppendChar(wpass[i]); When creating a new SecureString object, we’ll use the constructor form that creates a SecureString from an existing wchar_t string. try { name = gcnew SecureString(wname, (int) wcslen(wname)); login = gcnew SecureString(wlogin, (int) wcslen(wlogin)); url = gcnew SecureString(wurl, (int) wcslen(wurl)); } catch (...) { rv = NL_STATUS_ALLOC; } Our password manager also supports transferring passwords to the Windows clipboard. The clipboard is an insecure storage space that can potentially be accessed by other users and for this reason Microsoft recommends that sensitive data never be placed on there. The point of a password manager, though, is to make it possible for users to create strong passwords that they do not have to remember. It also makes it possible to create lengthy passwords consisting of randomly generated characters which would be difficult to type by hand. The clipboard provides much needed convenience in exchange for some measure of risk. To mitigate this risk, we need to take some extra precautions. The first is to ensure that the clipboard is emptied when the application exits. This is accomplished in the destructor in one of our native objects. PasswordManagerCoreNative::~PasswordManagerCoreNative(void) { if (!OpenClipboard(NULL)) return; EmptyClipboard(); CloseClipboard(); } We’ll also set up a clipboard timer. When a password is copied to the clipboard, set a timer for 15 seconds and execute a function to clear the clipboard when it fires. If a timer is already running, meaning a new password was placed on the clipboard before the old one was expired, that timer is cancelled and the new one takes its place. void PasswordManagerCoreNative::start_clipboard_timer() { // Use the default Timer Queue // Stop any existing timer if (timer != NULL) DeleteTimerQueueTimer(NULL, timer, NULL); // Start a new timer if (!CreateTimerQueueTimer(&timer, NULL, (WAITORTIMERCALLBACK)clear_clipboard_proc, NULL, CLIPBOARD_CLEAR_SECS * 1000, 0, 0)) return; } static void CALLBACK clear_clipboard_proc(PVOID param, BOOLEAN fired) { if (!OpenClipboard(NULL)) return; EmptyClipboard(); CloseClipboard(); } With the secrets identified and the enclave boundary drawn, it’s time to structure the application while taking the enclave into account. There are significant restrictions on what can be done inside of an enclave, and these restrictions will mandate which components live inside the enclave, which live outside of it, and when porting an existing applications, which ones may need to be split in two. The biggest restriction that impacts the Tutorial Password Manager is that enclaves cannot perform any I/O operations. The enclave can’t read from the keyboard or write to the display so all of our secrets—passwords and account information—must be marshaled into and out of the enclave. It also can’t read from or write to the vault file: the components that parse the vault file must be separated from components that perform the physical I/O. That means we are going to have to marshal more than just our secrets across the enclave boundary: we have to marshal the file contents as well. Figure 2: Class diagram for the Tutorial Password Manager. Figure 2 shows the basic class diagram for the application core (excluding the user interface), including which classes serve as the sources and destinations for our secrets. Note that the PasswordManagerCore class is considered the source and destination for secrets which must interact with the GUI in this diagram for simplicity’s sake. Table 4 briefly describes each class and its purpose. Table 4: Class descriptions. Note that we had to split the handling of the vault file into two pieces: one that does the physical I/O, and one that stores its contents once they are read and parsed. We also had to add serialization and deserialization methods to the Vault object as intermediate sources and destinations for our secrets. All of this is necessary because the VaultFile class can’t know anything about the structure of the vault file itself, since that would require access to cryptographic functions that are located inside the enclave. We’ve also drawn a dotted line when connecting the PasswordManagerCoreNative class to the Vault class. As you might recall from Part 2, enclaves can only link to C functions. These two C++ classes cannot directly communicate with one another: they must use an intermediary which is denoted by the Bridge Functions box. The diagram in Figure 2 is for the Intel SGX code path. The PasswordManagerCoreNative class cannot link directly to the Vault class because the latter is inside the enclave. In the non-Intel SGX code path, however, there is no such restriction: PasswordManagerCoreNative can directly contain a member of class Vault. This is the only shortcut we’ll take in the application design for the non-Intel SGX code path. To simplify the enclave integration, the non-enclave code path will still separate the vault processing into the Vault and VaultFile classes. Another key difference between the two code paths is that the cryptographic functions in the Intel SGX path will come from the Intel SGX SDK. The non-Intel SGX code path can’t use these functions, so they will draw upon Microsoft’s Cryptography API: Next Generation* (CNG). That means we have to maintain two, distinct copies of the Crypto class: one for use in enclaves and one for use in untrusted space. (We’ll have to do the same with other classes, too; this will be discussed in Part 5.) As mentioned in the introduction, there is sample code provided with this part for you to download. The attached archive includes the source code for the Tutorial Password Manager core DLL, prior to enclave integration. In other words, this is the non-Intel SGX version of the application core. There is no user interface provided, but we have included a rudimentary test application written in C# that runs through a series of test operations. It executes two test suites: one that creates a new vault file and performs various operations on it, and one that acts on a reference vault file that is included with the source distribution. As written, the test application expects the test vault to be located in your Documents folder, though you can change this in the TestSetup class if needed. This source code was developed in Microsoft Visual Studio* Professional 2013 per the requirements stated in the introduction to the tutorial series. It does not require the Intel SGX SDK at this point, though you will need a system that supports Intel® Data Protection Technology with Secure Key. In Part 4 of the tutorial we’ll develop the enclave and the bridge functions. Stay tuned!
https://software.intel.com/content/www/us/en/develop/articles/software-guard-extensions-tutorial-series-part-3.html
CC-MAIN-2020-40
refinedweb
2,399
50.06
Saving “ Marks To File Using TextView TextView - Saving TextView text to a file. Cannot save when text contains a “ quotation mark. All other normal characters can be saved. def SAVE_SCOPEB(sender): jf.open(“Note_Data.py”, ‘w’) jf.write(JWriteNote.text) jf.close() The above function works and saves text to a disk file on cloud, but when a quotation mark is part of the text, the following message is received - ‘ascii’ codec, can’t encode, characters in positions 0-1: ordina.... My first post, Thank you in advance.d @James007 this works(see 'wt') import ui v = ui.View() v.frame = (0,0,400,400) JWriteNote = ui.TextField(name ='JWriteNote') JWriteNote.frame = (10,10,200,32) v.add_subview(JWriteNote) b = ui.ButtonItem() b.title = 'save' def SAVE_SCOPEB(sender): with open('Note_Data.py', 'wt') as jf: jf.write(JWriteNote.text) b.action = SAVE_SCOPEB v.right_button_items = (b,) v.present('sheet') Thanks CVP, I will give it a try ....
https://forum.omz-software.com/topic/5508/saving-marks-to-file-using-textview
CC-MAIN-2020-29
refinedweb
156
72.83
Based on this It’s Alive video and adapted to make a single loaf. Ingredients: 350g white flour 150g Whole Wheat Flour 300g water 100g sourdough starter 10g salt 1 — Mix the flours and 250g of water to start the autolyse. Let it rest for 30min to 2 hours 2 — When the started is ready (floating when dropped in a cup of water), add the starter to the dough by pinching it in. 3 — Add the salt and remaining 50g of water. Water helps dissolve the salt. 4 — Slam the dough on the counter, then fold it… Here are stories of my struggles with this amazing system and how I managed to survive. Things will be added without order for the moment, but I’ll eventually clean it up. There is a lot of step to the actual installation but once it is up and running, to start your virtual machine at the beginning of the day, simply type the following in your /trellis folder vagrant up Once when restarting Vagrant ( typing vagrant up after running vagrant destroy), I was faced with this error: composer was NOT installed successfully: Failed to get data from the API server… For our first projection mapping project we decided to go with a simple workflow, using MadMapper and Blender. Here are the steps that were taken. The space is a 3mx3m room. In one corner, there are three stacked boxes forming the sculpture. In the other corner, the projector will be standing vertically (portrait mode) at an angle. The first step is to model the sculpture. Using Blender, I modeled the 2 stacked boxes into a single object, extruding boxes one by one. I then simplified the 3D model by getting rid of the top, back and bottom faces. To apply… After having used a variety of tools to deploy our websites (the latest one being DeployBot,) I decided it was time to implement a more sustainable simple—and free— solution. Our server is on Dreamhost and the websites’ repositories on Bitbucket. On your local computer, navigate to your user’s ~/.ssh directory: $ cd ~/.ssh If the directory doesn’t exist, create it: $ mkdir ~/.ssh Set up SSH keys by running the following command: $ ssh-keygen -t rsa -b 4096 -C “DreamHost Git repo” Enter a name for the file when prompted, such as ‘dreamhost-git-key’. When prompted to enter a password, click… Google included in its API a pretty easy way to customize icons. But when it comes to interact with those icons, it’s impossible to find a good way to do that in the documentation or on forums. One way some people have been doing it is to add all markers in a layer and use the new DOM id they defined to interact with the layers inside. The whole method is explained here. They then count how many markers are on the map, give them each a number and count the DOM elements to match them with their associated number… The goal of the function was simple: if the user sign-up is successful, redirect to the now unlocked admin page. But finding information about how to do it from the React component using React-Router turned out to be impossible. I did find information at first, but nothing that seemed to be working anymore. context.history.push('/new-location') was probably the one I spent the most time one with no success. Here is the solution that worked for me: import { browserHistory } from 'react-router' browserHistory.push('/success') That looks incredibly easy like that, but finding those two lines of code was the most frustrating couple hours of this project. Simple paths like /current are rendering fine on refresh, but as soon as a second layer is reached, /current/all for example, the console sends the following error: Uncaught SyntaxError: Unexpected token < The problem is caused by the browser using relative urls. The solution is to specify the base URL so that all path are defined relative to /. Adding < in the head fixes the problem. Solution on StackOverflow A month ago, I started the development of my first Node.js/Express/React.js web application. It has been a learning process and is still a work in progress, but I thought I would share the little bits of knowledge I acquired along the way and hopefully help others that have started a similar endeavor. I consider myself a developer. I understand the logic of coding and can make my way through any new code I stumble upon. But by no means am I an expert yet. … Enthusiasm enthusiast. Partner at 13milliseconds
https://medium.com/@13milliseconds
CC-MAIN-2021-17
refinedweb
773
61.36
In the 16.2.4 release, we've added a new Visual Studio extension that helps you to easily lookup the online DevExpress Documentation at: or This gives you the benefit of accessing DevExpress documentation through Visual Studio without having to install the documentation into your local hard drive. A few releases ago, we separated out the documentation from our main DXperience installation to reduce file size and improve the installation experience. Now with this new 'help lookup' extension, you can use the handy 'F1' help lookup key in Visual Studio and it will use the online search without local documentation installed. Here's how it works when you click a DevExpress API member (property, field, etc) and then press 'F1'. Click the play button below the image: [Your browser does not support the video tag.] Download and install the DXperience v16.2.4 release and this new extension will be available in your Visual Studio. This extension works with Visual Studio 2012, 2013, 2015, and 2017 RC. Set Visual Studio's Help Preference to 'Launch in Browser': use HELP –> Set Help Preference –> Launch in Browser menu item: To make sure this feature is set, you may need to switch this setting from 'Launch in Help Viewer' and then back to 'Launch in Browser'. Now when you write code that uses DevExpress API and press F1 on different API members (namespaces, classes, interfaces, enums, methods, properties, events, fields), you'll be directed to the help topic online! Currently, the extension works only with code editors and in the standard 'Properties' window. We plan to support the DevExpress designers later. If you find any issues or have any feedback about this new extension then please contact our support@devexpress.com team and let us know. What do you think about the DevExpress Visual Studio online help extension?). Now. The ASP.NET AJAX Control Toolkit installer now supports the release candidate of Visual Studio 2017. And we'd like your help to test our installer and give us your feedback. Microsoft announced the release candidate for Visual Studio 2017 in November 2016. The new Visual Studio 2017 RC provides feature updates and improvements. If you've installed Visual Studio 2017 RC then please download the installer: ASP.NET AJAX Control Toolkit v17 Preview for VS 2017 RC Note: This preview installer will only work with VS2017 RC and not with the release versions. For the stable version that works with Visual Studio release versions, please check here. This preview install is up to date with this commit. Download this preview and then give us your feedback. Twitter: @mehulharry It's finally below: Good news, we are now offering NuGet packages for our ASP. Use the list below to determine which packages you need for your project: What do you think about the new DevExpress NuGet packages? We'd love to hear your feedback. Please let us know by adding your feedback to this knowledgebase article. The DevExpress ASP.NET Scheduler control is getting some big enhancements for the v16.2 release. As much as we’ve tried over the years, a good scheduler control is not as simple or light as a button. There’s just a lot more “stuff” to take care of and display. Consequently, at the beginning of 2016, we decided that it was high time to start improving our scheduler control's appearance and performance. I'm happy to say that we've achieved both and your end-users will be delighted. Let's start with UI enhancements because they're the first thing that you'll notice. For v16.2, the DevExpress ASP.NET Scheduler control features: These UI enhancements look great, check out the Scheduler with these upcoming changes: To see the difference, compare these two images of v16.1 (left) and v16.2 (right): The performance of our scheduler has also been enhanced significantly with use of client-side rendering improvements: We've tested the difference and you'll be pleased to know that overall performance and feel of the DevExpress ASP.NET Scheduler control has increased. Check out these charts to see the measurements: Scheduler – Render size of two controls w/o appointments Scheduler – Appointment update time Scheduler – Change date time Scheduler – Active view change time With this release, our ASP.NET Scheduler Control can now highlight coordinates of the currently selected time interval within its time ruler and day headers: What do you think of the DevExpress ASP.NET Scheduler control's enhancements for v16.2 release? Drop me a line below. Our flagship ASP.NET control, the DevExpress ASP.NET GridView, is getting some great UI improvements for the v16.2 release. Your end-users will be delighted that their favorite GridView control now provides a few useful client-side interactions and we've also improved its accessibility support. Our ASP.NET Grid Control now offers an alternative client "column alignment" processing mode. In this mode, when an end-user moves a grid column using drag-and-drop, the GridView re-renders itself to reflect new layout changes on the client side using drag and drop operations: For the Accessibility enhancements, I want to thank those customers who called us to task to improve our accessibility support and for working with us to improve it.: Last but not least, we've improved the functionality of fixed columns within our ASP.NET Grid Control so you can provide complex layouts. The following layout features are now fully compatible with fixed columns: Which of the enhancements to the DevExpress ASP.NET GridView Control are you most excited about? Drop me a line below. Mobile devices come in different screen sizes and resolutions and nearly all of them are connected to the world wide web (aka internet). Due to this variety, web developers have a tough job to make sure our websites look good for both desktop and mobile browsers. To help you make responsive websites, these DevExtreme widgets have features that are optimized for use on a mobile device: dxDataGrid, dxForm, dxMenu, dxToolBar and dxScheduler. For example, compare the dxDataGrid on tablet and phone devices: Starting with the v16.1 release, we added options that allow you to control and adjust the appearance of the widgets for different resolutions. In this post, I'll highlight the different widgets and the code you need to take advantage of the new responsive features. Advanced responsive layout is our term for providing you several ways to adapt the dxDataGrid widget for different resolutions. If you have a smaller screen size then you can decrease the overall grid's width by hiding columns: gridOptions: { // … columnHidingEnabled: true } By default, the columns on the right will be hidden first when the widget width is reduced. You can change the order that the columns are hidden in. For example, here the 'State' column will be hidden first, then 'City', and finally it will default back to right most columns hidden first: gridOptions: { // … columns: [{ dataField: "Employee", width: 130 }, { dataField: "OrderNumber", width: 130 }, { caption: "City", dataField: "CustomerStoreCity", hidingPriority: 1 }, { caption: "State", dataField: "CustomerStoreState", hidingPriority: 0 }, { dataField: "OrderDate", dataType: "date" }] } For mobile devices, it's useful to use checkboxes for the 'Column Chooser' dialog: gridOptions: { // … columnChooser: { enabled: true, mode: "select" }, } To group data by a column, typically, you would drag the column header and drop it over the group panel. When you have a larger screen size, this works great. However, this becomes harder when the screens are smaller. Therefore, we added a context menu option for mobile devices which makes grouping easy: gridOptions: { // … grouping: { contextMenuEnabled: true, expandMode: "rowClick" } } The dxDataGrid's pager has also been adapted to display as a dropdown if there are several pages and the screen size is smaller. This saves room and works great for mobile devices: By default, the dxForm widget has the same layout for all screen resolutions. However, you can manually specify the dependency between screen size and column count. In the sample below, we've defined the dxForm to only display a single column when the screen width is less than 600 pixels. formOptions: { // … screenByWidth: function(width) { if( width < 450) return 'xs'; if( width < 600) return 'sm'; if( width < 750) return 'md'; return 'lg'; }, colCountByScreen: { lg: 2, md: 2, sm: 1, xs: 1 }, } By default, the dxMenu widget will collapse the root menu to a list icon (hamburger menu icon). This saves space on mobile devices as all the submenus are displayed as a tree structure similar to dxTreeView widget. To enable it: menuOptions: { // … adaptivityEnabled: true } The dxToolbar provides you the capability to display several items in the toolbar. However, for smaller screens, the dxToolbar may become too wide to fit on the screen. To help you solve this dilemma, dxToolbar can hide its items inside a drop down menu using the default item template. To hide items in a dropdown, assign "auto" to the locateInMenu field of an item object. This will move the item to the context menu if the screen is not wide enough to display all toolbar items. toolbarOptions: { // … items: [{ location: 'center', locateInMenu: 'never', text: "Caption" }, { location: 'after', widget: 'dxButton', locateInMenu: 'auto', options: { icon: "plus", } }, { location: 'after', widget: 'dxButton', locateInMenu: 'auto', options: { icon: "edit", text: "Edit", } }, { locateInMenu: 'always', text: 'Save', }, { locateInMenu: 'always', text: 'Print', }, { locateInMenu: 'always', text: 'Settings', }] } The dxScheduler widget is fantastic for displaying appointments and schedules. However, it can be too large for mobile screens. To help you, the dxScheduler provides the Agenda view that supports small screen sizes: You can learn more about dxScheduler's Agenda view here. The code samples and images above highlight how useful the DevExtreme widgets are in designing a rich client-side website that provides responsive behavior. What do you think about the 'Advanced Responsive Layout' feature of the DevExtreme widgets? Drop me a line below, thanks. We just released DevExtreme v16.1.8 and added a helpful new Visual Studio integration feature. You can now right-click on your Visual Studio project and enable it to start using the DevExtreme MVC wrappers. Here are the steps: DevExpress MVC Wrappers require certain assemblies and resources to be part of your ASP.NET project. Now you can add the required resources and start using the DevExpress MVC Wrappers in a few clicks. Before you begin, please install the DevExtreme v16.1.8 release. Then follow these steps: Right-click on your project in the Visual Studio Solution Explorer and select Add DevExtreme to the Project from the context menu: Add DevExtreme to the Project Next, confirm your action in the dialog box and DevExtreme will begin adding its dependencies to your project. You can see the changes in the Visual Studio Output window: A success message means that your project is set up to use the DevExpress ASP.NET MVC Wrappers. If there are any issues then you'll see them in this window too. It's unlikely that there will be an error but if you find any or need help, then please contact our excellent support department. Now that your project is ready to use DevExpress ASP.NET MVC Wrappers, start and add a Grid or Chart wrapper to it. I recommend that you watch the webinar to learn how to add and use the DevExpress ASP.NET MVC Wrappers: What do you think about the DevExpress ASP.NET MVC Wrappers? Drop me a line below,.
https://community.devexpress.com/blogs/aspnet/
CC-MAIN-2017-09
refinedweb
1,894
61.87
What is the Stochastic Oscillator Indicator for a stock? A stochastic oscillator is a momentum indicator comparing a particular closing price of a security to a range of its prices over a certain period of time. The stochastic oscillator is an indicator for the speed and momentum of the price. The indicator changes direction before the price does and is therefore a leading indicator. Step 1: Get stock data to do the calculations on()) print(ticker) Where we only focus on data from 2020 until today. High Low ... Volume Adj Close Date ... 2020-01-02 300.600006 295.190002 ... 33870100.0 298.292145 2020-01-03 300.579987 296.500000 ... 36580700.0 295.392120 2020-01-06 299.959991 292.750000 ... 29596800.0 297.745880 2020-01-07 300.899994 297.480011 ... 27218000.0 296.345581 2020-01-08 304.440002 297.160004 ... 33019800.0 301.112640 ... ... ... ... ... ... 2020-08-05 441.570007 435.589996 ... 30498000.0 439.457642 2020-08-06 457.649994 439.190002 ... 50607200.0 454.790009 2020-08-07 454.700012 441.170013 ... 49453300.0 444.450012 2020-08-10 455.100006 440.000000 ... 53100900.0 450.910004 2020-08-11 449.929993 436.429993 ... 46871100.0 437.500000 [154 rows x 6 columns] The output does not show all the columns, which are: High, Low, Open, Close, Volume, and Adj Close. Step 2: Understand the calculation of Stochastic Oscillator Indicator The Stochastic Oscillator Indicator consists of two values calculated as follows. %K = (Last Close – Lowest low) / (Highest high – Lowest low) %D = Simple Moving Average of %K What %K looks at is the Lowest low and Highest high in a window of some days. The default is 14 days, but can be changed. I’ve seen others use 20 days, as the stock market is open 20 days per month. The original definition set it to 14 days. The simple moving average was set to 3 days. The numbers are converted to percentage, hence the indicators are in the range of 0% to 100%. The idea is that if the indicators are above 80%, it is considered to be in the overbought range. While if it is below 20%, then it is considered to be oversold. Step 3: Calculate the Stochastic Oscillator Indicator With the above description it is straight forward to do. import pandas_datareader as pdr import datetime as() print(ticker) Resulting in the following output. High Low ... %K %D Date ... 2020-01-02 300.600006 295.190002 ... NaN NaN 2020-01-03 300.579987 296.500000 ... NaN NaN 2020-01-06 299.959991 292.750000 ... NaN NaN 2020-01-07 300.899994 297.480011 ... NaN NaN 2020-01-08 304.440002 297.160004 ... NaN NaN ... ... ... ... ... ... 2020-08-05 441.570007 435.589996 ... 92.997680 90.741373 2020-08-06 457.649994 439.190002 ... 97.981589 94.069899 2020-08-07 454.700012 441.170013 ... 86.939764 92.639677 2020-08-10 455.100006 440.000000 ... 93.331365 92.750906 2020-08-11 449.929993 436.429993 ... 80.063330 86.778153 [154 rows x 10 columns] Please notice that we have not included all columns here. Also, see the the %K and %D are not available for the first days, as it needs 14 days of data to be calculated. Step 4: Plotting the data on a graph We will combine two graphs in one. This can be easily obtained using Pandas DataFrames plot function. The argument secondary_y can be used to plot up against two y-axis. The two lines %K and %D are both on the same scale 0-100, while the stock prices are on a different scale depending on the specific stock. To keep things simple, we also want to plot a line indicator of the 80% high line and 20% low line. This can be done by using the axhline from the Axis object that plot returns. The full code results in the following. import pandas_datareader as pdr import datetime as dt import matplotlib.pyplot as() ax = ticker[['%K', '%D']].plot() ticker['Adj Close'].plot(ax=ax, secondary_y=True) ax.axhline(20, linestyle='--', color="r") ax.axhline(80, linestyle="--", color="r") plt.show() Resulting in the following graph. Step 5: Interpreting the signals. First a word of warning. Most advice from only using one indicator alone as a buy-sell signal. This also holds for the Stochastic Oscillator indicator. As the name suggest, it is only an indicator, not a predictor. The indicator signals buy or sell when the two lines crosses each other. If the %K is above the %D then it signals buy and when it crosses below, it signals sell. Looking at the graph it makes a lot of signals (every time the two lines crosses each other). This is a good reason to have other indicators to rely on. An often misconception is that it should only be used when it is in the regions of 20% low or 80% high. But it is often that low and high can be for quite some time. Hence, selling if we reach the 80% high in this case, we would miss a great opportunity of a big gain.
https://www.learnpythonwithrune.org/pandas-calculate-the-stochastic-oscillator-indicator-for-stocks/
CC-MAIN-2021-25
refinedweb
859
76.62
IQKeyboardManager []() []() []() ## GIF animation []() ## []() | | Language | Minimum iOS Target | Minimum Xcode Version | |————————|———-|——————–|———————–| | IQKeyboardManager | Obj-C | iOS 8.0 | Xcode 8.2.1 | | IQKeyboardManagerSwift | Swift | iOS 8.0 | Xcode 8.2.1 | | Demo Project | | | Xcode 10.2 | **Note** – 3.3.7 is the last iOS 7 supported version. #### Swift versions support | Swift | Xcode | IQKeyboardManagerSwift | |——————-|——-|————————| | 5.0,4.2, 4.0, 3.2, 3.0| 10.2 | >= 6.2.1 | | 4.2, 4.0, 3.2, 3.0| 10.0 | >= 6.0.4 | | 4.0, 3.2, 3.0 | 9.0 | 5.0.0 | | 3.1 | 8.3 | 4.0.10 | | 3.0 (3.0.2) | 8.2 | 4.0.8 | | 2.2 or 2.3 | 7.3 | 4.0.5 | | 2.1.1 | 7.2 | 4.0.0 | | 2.1 | 7.2 | 3.3.7 | | 2.0 | 7.0 | 3.3.3.1 | | 1.2 | 6.3 | 3.3.1 | | 1.0 | 6.0 | 3.3.2 | Installation ========================== #### Installation with CocoaPods []() ***IQKeyboardManager (Objective-C):*** IQKeyboardManager is available through [CocoaPods](). To install it, simply add the following line to your Podfile: ([#9]()) “`ruby pod ‘IQKeyboardManager’ #iOS8 and later pod ‘IQKeyboardManager’, ‘3.3.7’ #iOS7 “` ***IQKeyboardManager (Swift):*** IQKeyboardManagerSwift is available through [CocoaPods](). To install it, simply add the following line to your Podfile: ([#236]()) *Swift 5.0,4.2, 4.0, 3.2, 3.0 (Xcode 10.2)* “`ruby pod ‘IQKeyboardManagerSwift’ “` *Or you can choose the version you need based on Swift support table from [Requirements](README.md#requirements)* “`ruby pod ‘IQKeyboardManagerSwift’, ‘6.3.0’ “` In AppDelegate.swift, just import IQKeyboardManagerSwift framework and enable IQKeyboardManager. “`swift import IQKeyboardManagerSwift } } “` #### Installation with Carthage [Carthage]() is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. You can install Carthage with [Homebrew]() using the following command: “`bash $ brew update $ brew install carthage “` To integrate `IQKeyboardManger` or `IQKeyboardManagerSwift` into your Xcode project using Carthage, add the following line to your `Cartfile`: “`ogdl []() **. “`swift } } “` Migration Guide ========================== – [IQKeyboardManager 6.0.0 Migration Guide]() Other Links ========================== – [Known Issues]() – [Manual Management Tweaks]() – [Properties and functions usage]() ##] Latest podspec { "name": "IQKeyboardManagerSwift", "version": "6.3.0", "source": { "git": "", "tag": "v6.3.0" }, "summary": "Codeless drop-in universal library allows to prevent issues of keyboard sliding up and cover UITextField/UITextView.", "homepage": "", "screenshots": "", "license": "MIT", "authors": { "Iftekhar Qurashi": "[email protected]" }, "platforms": { "ios": "8.0" }, "swift_versions": [ "3.0", "3.2", "4.0", "4.2", "5.0" ], "source_files": "IQKeyboardManagerSwift/**/*.{swift}", "resources": "IQKeyboardManagerSwift/Resources/IQKeyboardManager.bundle", "frameworks": [ "UIKit", "Foundation", "CoreGraphics", "QuartzCore" ], "requires_arc": true } Thu, 02 May 2019 10:23:17 +0000
https://tryexcept.com/articles/cocoapod/iqkeyboardmanagerswift
CC-MAIN-2019-47
refinedweb
416
52.15
C++ API: Locale matcher: User's desired locales vs. More... #include "unicode/utypes.h" #include "unicode/locid.h" #include "unicode/stringpiece.h" #include "unicode/uobject.h" Go to the source code of this file. C++ API: Locale matcher: User's desired locales vs. application's supported locales. Definition in file localematcher.h. Builder option for whether all desired locales are treated equally or earlier ones are preferred. Definition at line 55 of file localematcher.h. Builder option for whether to include or ignore one-way (fallback) match data. The LocaleMatcher uses CLDR languageMatch data which includes fallback (oneway=true) entries. Sometimes it is desirable to ignore those. For example, consider a web application with the UI in a given language, with a link to another, related web app. The link should include the UI language, and the target server may also use the client’s Accept-Language header data. The target server has its own list of supported languages. One may want to favor UI language consistency, that is, if there is a decent match for the original UI language, we want to use it, but not if it is merely a fallback. Definition at line 111 of file localematcher.h. Builder option for whether the language subtag or the script subtag is most important. Definition at line 29 of file localematcher.h.
https://unicode-org.github.io/icu-docs/apidoc/dev/icu4c/localematcher_8h.html
CC-MAIN-2021-39
refinedweb
223
61.12
Python bindings for rrdtool Project description python-rrdtool Python bindings for RRDtool for Python 2 and 3. The bindings are based on the code of the original Python 2 bindings module for rrdtool by Hye-Shik Chang and are now shipped with the RRDtool distribution. This project is maintained separately to provide a more pythonic way to install those bindings via PyPI. Features - Native extension (written in C) for performance reasons. - Uses library functions as exposed by librrd. - Works with Python 2.6, 2.7, 3.3 and any later version. Installation The most convenient way to install (on POSIX-like systems) is to use pip: pip install rrdtool Note: Unless binary versions are available for your target system, the command above requires rrdtool development files (headers, libraries, dependencies) to be installed, otherwise building the module will fail. In case you'd like to build the module on your own (regardless of whether binary versions are available for your system), you can obtain a copy of the source code and run python setup.py install in its destination folder to build the module. Usage import rrdtool # Create Round Robin Database rrdtool.create('test.rrd', '--start', 'now', '--step', '300', 'RRA:AVERAGE:0.5:1:1200', 'DS:temp:GAUGE:600:-273:5000') # Feed updates to the RRD rrdtool.update('test.rrd', 'N:32') Documentation You can find the latest documentation for this project at. License GNU Lesser General Public License version 2.1. Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/rrdtool/
CC-MAIN-2021-43
refinedweb
270
56.96
A Practical Introduction to Docker Container Terminology . Vocabulary Docker daemon is doing some extra work for you. The Docker daemon (not the client tool) is configured with a list of servers to search. In our example above, the damone other registry server. This is because Red Hat works to also list repositories on our partner’s registry serves: specified. In this case, there is a default repository for a given namespace. If a user only specifies the fedora namespace, the latest tag from the default repository will be pulled to the local server. docker pull fedora. First let’s check out what image layers are available in the Red Hat Enterprise Linux 7 repository. Notice that each layer has tag and a Universally Unique Identifier (UUID).” repositorie is actually made up of many images layers. More importantly, notice that a user could potentially “run” a container based off of any one of these layers. The following command is perfectly valid, though not guaranteed to have been test or work: docker run -it 45b3c59b9130 bash This is because when the image builder creates a new image, a new layer is created under certain condition. First, if the image builder is building the image manually, each “commit” creates a new layer. If the image builder is building an image with a Dockerfile, each directive in the file creates a new layer. It is useful to have visibility into what has changed in a container repository between each layer. Base Image Simply put, a base image is an image that has no parent layer. Typically, a base image contains a fresh copy of an operating system. Base images normally include the tools (yum, rpm, apt-get) necessary to install packages or update the image included in them. These special base images can be created yourself, but are typically produced and published by open source projects and vendors like Red Hat. Provenance and trust of these base images is critical. The sole purpose of a base image is to provide a starting place for creating your derivative images. When using a Dockerfile, the choice of which base image you are using is explicit: FROM rhel7 Tag Even though a user can run a container from any of the image layers, they shouldn’t necessarily do that. When an image builder creates a new repository, they will typically label the best image layers to use. These are called tags and typically map to versions of software contained in the repository. To remotely view the available" } To pull all of the available tags to the local container host and then inspect them, run the following commands. Notice that each of the tags maps to a version of RHEL embedded in the particular layer. Understanding this, can help you pull the desired layer to, for example, meet an OS requirement. docker pull -a rhel7 docker images -a | grep rhel7 registry.access.redhat.com/rhel7 7.2 6c3a84d798dc 6 days ago 201.7 MB registry.access.redhat.com/rhel7 7.2-38 6c3a84d798dc 6 days ago 201.7 MB registry.access.redhat.com/rhel7 latest 6c3a84d798dc 6 days ago 201.7 MB registry.access.redhat.com/rhel7 7.2-35 6883d5422f4e 4 weeks ago 201.7 MB registry.access.redhat.com/rhel7 7.1-24 c4f590bbcbe3 5 weeks ago 158.2 MB registry.access.redhat.com/rhel7 7.1-16 82ad5fa11820 12 weeks ago 158.3 MB registry.access.redhat.com/rhel7 7.2-2 58958c7fafb7 3 months ago 201.6 MB registry.access.redhat.com/rhel7 7.1-12 275be1d3d070 4 months ago 158.3 MB registry.access.redhat.com/rhel7 7.1-11 d0a516b529ab 4 months ago 158.2 MB registry.access.redhat.com/rhel7 7.1-9 e3c92c6cff35 5 months ago 158.2 MB registry.access.redhat.com/rhel7 7.1-6 65de4a13fc7c 7 months ago 154.9 MB registry.access.redhat.com/rhel7 7.0-27 8e6704f39a3d 10 months ago 145.1 MB registry.access.redhat.com/rhel7 7.1-4 10acc31def5d 10 months ago 154.1 MB registry.access.redhat.com/rhel7 7.0-23 bef54b8f8a2f 18 months ago 147 MB registry.access.redhat.com/rhel7 7.0-21 e1f5733f050b 18 months ago 140.2 MB Registry Server A registry server, is essentially a fancy file server that is used. By default, Red Hat enterprise Linux is configured to pull repositories from registry.access.redhat.com first, then it will try' Container Host Once an image (aka repository) is pulled from a registry server, to the local container host, it is said to be in the local cache. Determining which repositories are synchronized to the local cache can be determined with the following command: [root@rhel7 ~]# docker images -a REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE registry.access.redhat.com/rhel7 latest 6883d5422f4e 3 weeks ago 201.7 MB Graph Driver Every time a container is created on a container host, all of the dependent image layers are used together read only. Another read/write layer is then added so that you may write data like a normal process. The graph driver is the piece of software that maps the different image layers in the repository to the local storage. The local storage can be a filesystem, or block storage depending on the driver. Drivers include: aufs, devicemapper, btrfs, zfs, and overlayfs. Determining which graph driver you are using can be done with the docker info command: [root@rhel7 ~]#) … Conclusion People often use the words container, image, from based on business rules…. For further reading, check out the Architecting Containers series: - Architecting Containers Part 1: Why Understanding User Space vs. Kernel Space Matters - Architecting Containers Part 2: Why the User Space Matters - Architecting Containers Part 3: How the User Space Affects Your Application As always, if you have comments or questions, please leave a message below..
https://developers.redhat.com/blog/2016/01/13/a-practical-introduction-to-docker-container-terminology/?utm_campaign=containers&intcmp=70160000000h1s6AAA
CC-MAIN-2019-13
refinedweb
973
59.09
Follow the steps below to create, package, and run a simple Java application using Maven, a free automated build tool for Java maintained by the Apache Software Foundation. These instructions assume the computer is running a Microsoft Windows operating system. The code within these instructions is based on samples found at the URL “”. 1. If you have not already done so, download and install Java and a Java Development Kit. 2. In any convenient location, create a new directory named “MavenTest”. 3. Download Maven. As of this writing, the latest download is available at the URL “”. Navigate to that page in a web browser, click the “Binary zip archive” link, and download the file to the newly created MavenTest directory. 4. Inside the MavenTest directory, use an extraction utility to extract the contents of the downloaded Maven archive file. Once the file is extracted, locate the directory containing the file named “mvn.cmd” within the directory structure. For this example, the file was located in the directory “apache-maven-3.3.9-bin/apache-maven-3.3.9/bin”. 5. Create a new text file in the MavenTest directory named “MavenTest-Generate.bat”, containing the text shown below. If a different version of Maven than 3.3.9 is being used, it will be necessary to adjust the command accordingly. "apache-maven-3.3.9-bin/apache-maven-3.3.9/bin/mvn" archetype:generate -DgroupId=com.mycompany.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false 6. Run the script file created in the previous step. If this is the first time Maven has run on the system, it may take a few moments to download several files from the internet. It will then create a new directory within the MavenTest folder, named “my-app”. Within this inner directory Maven will create a tree structure of new files and directories. 7. Navigate through the newly created my-app directory to locate the file App.java. For this example, the file is located in the “my-app/src/main/java/com/mycompany/app” directory. By default, the file App.java contains the following text: package com.mycompany.app; /** * Hello world! * */ public class App { public static void main( String[] args ) { System.out.println( "Hello World!" ); } } 8. Back in the “my-app” directory, create a new text file named “MavenTest-Package.bat”, containing the text below, and run it. The Maven project will be built and packaged. "../apache-maven-3.3.9-bin/apache-maven-3.3.9/bin/mvn" package 9. Still in the “my-app” directory, create a new text file named “MavenTest-Run.bat”, containing the text below, and run it. The application will execute, and the text “Hello World!” will be displayed. java -cp target/my-app-1.0-SNAPSHOT.jar com.mycompany.app.App pause
https://thiscouldbebetter.wordpress.com/2016/05/06/building-a-java-program-with-apache-maven/
CC-MAIN-2018-13
refinedweb
469
52.36
Functions without ”function” With the release of ES2015 comes three new ways to create functions in JavaScript. // Arrow functions const add = (x, y) => { return x + y } // Concise methods const MathUtils = { add (x, y) { return x + y } } // Classes class Point { constructor (x, y) { this.x = x this.y = y } } // Turns out, `Point` is still just a function. People have a great time pointing at JavaScript and sarcastically saying things like “GREAT! Now there are 10 bajillion ways to create a function in JavaScript!” I think there are 5? // The 3 we just saw and ... // Declarations function add (x, y) { return x + y } // Expressions var add = function (x, y) { return x + y } During our React Workshops we throw people into the fire with all three of these new ways to create functions. Invariably, folks want to know our opinion about when to use which form of function. My Answer? Never type the word “function” ever again. I (and most people I know) expect the value of `this` to either be the object who defined the method (or class instance), or the current `this` where the function is defined. I get that if I never type the word “function”. When I make decisions about my code style, I frame my decisions with this question: “What would I teach a complete beginner?” because things that are good for beginners are good for everybody. The best programmers write code beginners understand. I once thought changing the value of `this` was awesome. It could be employed to reuse code by “borrowing” methods — like this trick: function iAmAJSHacker () { var args = Array.prototype.slice.call(arguments, 0) // ... } After several years of writing JavaScript every day, I think `slice` is the only method I’ve ever borrowed in real code. Additionally, in ES2015 there’s a better way with rest parameters: function iAmAJSHacker (...args) { // TADA! } Since I don’t actually have a use-case for borrowing functions, I don’t need to use the expression and declaration forms that make it possible to borrow them: eliminating decisions like that feels great. Additionally, if I just never type the word “function” ever again, I will never have to screw around with binding `this` (should I pass the third arg to `map`? Should I bind at the usage or in the constructor? etc. etc.) See? const buy = (price, taco) => { doAjaxStuff(price, taco) } class CoolThing extends React.Component { buy (taco) { // `this` is what we expect because I used arrows in render buy(this.props.price, taco) } render () { const { tacos } = this.props return ( <ul> {tacos.map((taco) => ( <li> {taco.name} <button onClick={() => this.buy(taco)}/> </li> ))} </ul> ) } } Now, the concise object methods can still be “borrowed”, but if I never type the word function there will be no conversations about function binding, all we have to do is not talk about borrowing functions anymore, and, hopefully, the era of worrying about context is over.
https://medium.com/@ryanflorence/functions-without-function-bc356ed34a2f
CC-MAIN-2017-34
refinedweb
481
72.87
Variables in PHP don't have to be declared, they're automatically created the first time they are used. Nor do they have a specific type, they're typed automatically based on the context in which they are used. This is an extremely convenient way to do things from a programmer's perspective (and is obviously a useful feature in a rapid application development language). Once a variable is created it can be referenced anywhere in the program (except in functions where it must be explicitly included in the namespace by using global). The result of these characteristics is that variables are rarely initialized by the programmer; after all, when they're first created they are empty (i.e ""). Obviously the main function of a PHP based web application is usually to take in some client input (form variables, uploaded files, cookies etc), process the input and return output based on that input. In order to make it as simple as possible for the PHP script to access this input, it's actually provided in the form of PHP global variables. Take the following example HTML snippet: <FORM METHOD="GET" ACTION="test.php"> <INPUT TYPE="TEXT" NAME="hello"> <INPUT TYPE="SUBMIT"> </FORM> Obviously this will display a text box and a submit button. When the user presses the submit button the PHP script test.php will be run to process the input. When it runs, the variable $hello will contain the text the user entered into the text box. It's important to note the implications of this, this means that a remote attacker can create any variable they wish and have it declared in the global namespace. If instead of using the form above to call test.php, an attacker calls it directly with a url like "", not only will $hello = "hi" when the script is run but $setup will be "no" also. An example of how this can be a real problem might be a script that was designed to authenticate a user before displaying some important information. For example: if ($pass = "hello") $auth = 1; ... if ($auth == 1) echo "some important information"; In normal operation the above code will check the password to decide if the remote user has successfully authenticated then later check if they are authenticated and show them the important information. The problem is that the code incorrectly assumes that the variable $auth will be empty unless it sets it. Remembering that an attacker can create variables in the global namespace, a url like '' will fail the password check but the script will still believe the attacker has successfully authenticated. To summarize the above, a PHP script cannot trust ANY variable it has not EXPLICITLY set. When you've got a rather large number of variables, this can be a much harder task than it may sound. Once common approach to protecting a script is to check that the variable is not in the array HTTP_GET/POST_VARS[] (depending on the method normally used to submit the form, GET or POST). When PHP is configured with track_vars enabled (as it is by default) variables submitted by the user are available both from the global variables and also as elements in the arrays mentioned above. However, it's important to note that there are FOUR different arrays for remote user input Later versions of PHP (4 and above) provide built-in support for 'sessions'. Their basic purpose is to be able to save state information from page to page in a PHP application. For example, when a user logs in to a web site, the fact that they are logged in (and who they are logged in) could be saved in the session. When they move around the site this information will be available to all other PHP pages. What actually happens is that when a session is started (it's typically set in the configuration file to be automatically started on first request) a random session id is generated, the session persists as long as the remote browser always submits this session id with requests. This is most easily achieved with a cookie but can also be done by achieved by putting a form variable (containing the session id) on every page. The session is a variable store, a PHP application can choose to register a particular variable with the session, its value is then stored in a session file at the end of every PHP script and loaded into the variable at the start of every script. A trivial example is as follows: session_destroy(); // Kill any data currently in the session $session_auth = "shaun"; session_register("session_auth"); // Register $session_auth as a session variable Any later PHP scripts will automatically have the variable $session_auth set to "shaun", if they modify it later scripts will receive the modified value. This is obviously a very handy facility to have in a stateless environment like the web but caution is also necessary. One obvious problem is with insuring that variables actually come from the session. For example, given the above code, if a later script does the following: if (!empty($session_auth)) // Grant access to site here This code makes the assumption that if $session_auth is set, it must have come from the session and not from remote input. If an attacker specified $session_auth in form input they can gain access to the site. Note that the attacker must use this attack before the variable is registered with the session, once a variable is in a session it will override any form input. Session data is saved in a file (in a configurable location, usually /tmp) named 'sess_<session id>'. This file contains the names of the variables in the session, their loose type, value and other data. On multi host systems this can be an issue since the files are saved as the user running the web server (typically nobody), a malicious site owner can easily create a session file granting themselves access on another site or even examine the session files looking for sensitive information.
http://www-h.eng.cam.ac.uk/help/tpl/languages/php/php_security.html
CC-MAIN-2013-48
refinedweb
1,005
55.68
Hi, this patch series is a prototype for my GSoC project (Michal Privoznik is my mentor). I'm working on virsh auto-completion, trying to make it more "intelligent". At this stage, prototype is capable of command and option completion. Three completer functions are currently implemented so you can test it. If it turns out that this prototype is good enough, I will implement more completer functions. --- v3: * vshReconnect() is now called only when we reach the point that completion is being attempted on commands that needs connection * moved all .completer intializations into the 4/6, 5/6 and 6/6 v2: v1: Tomas Meszaros (6): virsh: C99 style for info_domfstrim and opts_lxc_enter_namespace virsh: Add vshCmdCompleter and vshOptCompleter virsh: Improve readline generators and readline completion virsh: Add vshDomainCompleter virsh: Add vshSuspendTargetCompleter virsh: Add vshRebootShutdownModeCompleter .gnulib | 2 +- tools/virsh-domain-monitor.c | 32 ++- tools/virsh-domain.c | 248 +++++++++++++++++----- tools/virsh-snapshot.c | 45 +++- tools/virsh.c | 480 +++++++++++++++++++++++++++++++++++++++++-- tools/virsh.h | 11 + 6 files changed, 725 insertions(+), 93 deletions(-) -- 1.8.3.1
https://www.redhat.com/archives/libvir-list/2013-August/msg01294.html
CC-MAIN-2014-10
refinedweb
171
51.34
-3 I need to make a score table function which keeps a track of the points. the first player to reach 11 points wins, however the game must be won by aleast a 2 point margin. the players points should be displayed on two halves of the graphic window. for example: the player should clicj on there side of the window to increase the point. after the players wins, a wins message should be displayed under the winner. the next click should close the window def main(): I am not sure how to start the code, any help would be great
https://www.daniweb.com/programming/software-development/threads/241093/scorecard
CC-MAIN-2017-09
refinedweb
101
88.26
How to show extreme gratitude in an email? When contacting universities, in many cases, I find the replies to my emails extremely well detailed and helpful, therefore in such cases I find a simple "Thank you" to be just insufficient. For example, when you have already applied to a program, and then you email the department to ask a simple question about supplementary documents, but they put SO MUCH effort in their response and even analyze your application before the application process has even started and they tell you that they are very certain that you will be accepted. How would you react? Is it rude to say something like: "I'm very glad to hear that." In such situations, I do not really know how to best answer the person to show them that I really appreciate their email very much. If you do get accepted, you may consider sending a note to the people in charge thanking them for the service. They usually only get the complaints. If you're that happy about the help received, then instead of emailing, write a letter, longhand. Are you really grateful for the explanation? Or are you just excited that you're going to get into the program? You can link this question and say "*I have no way of being grateful enough, I had to ask other people how to express my thankfulness*". @TonyEnnis inflicting them the pain of reading a handwritten script? That's more like a punishment! @Lohoris then the OP should take the time to write neatly. "Taking the time" is the demonstration of sincerity, versus blasting off a quick email with extra exclamation points, or perhaps a deluxe smiley. Politeness never hurts. "Thank you for your very detailed and positive information" could be one option or something along those lines. I am sure most people providing this type of response do not expect much in return (not that they do not deserve it). But as with many other instances, keeping the thanks short and concise is necessary, do not overwork it because that just seems suspicious. Remember that the person is doing their work (well) and should be praised for just that. If the school to which you are applying is large then it is not very likely you will be remembered and so the response will have little significance other than to show appreciation. In a smaller school, however, your politeness may be noticed and can help you build good relations with administration for the future so politeness never hurts. I agree with Peter Jansson! Politeness never hurts. I upVote. One thing my English Language and Literature teacher taught me was, "if you want to say it then just say it". I would suggest therefore you put your thanks into written form as I would like to express my most sincere gratitude and appreciation for ... Actually, I find that sounds rather formulaic and insincere. Asserting that something is a sincere statement has something of the opposite effect: it introduces the idea that some things you say might not be sincere. My advice is to examine your own feelings, and understand what exactly you want to express. Then words should come more naturally to you (at least if you're fluent in English). If you just say "I'm very glad to hear that" (I don't know if you meant you would write only this sentence) it sounds to me like you are at least reasonably happy you will likely be admitted, but you're not specific expressing gratitude for the effort they put into your inquiry. In this case, I presume you want to do two things: show excitement/enthusiasm about the news and express appreciation for their effort. For example: "That's great/wonderful news! I really appreciate all of the effort you took to personally examine my application." Or: "I'm excited to hear that. Thank you very much for taking the time look at my application in detail." Note: It appears Peter is Scandanavian, so he may be more reserved than a classless American like me. Anyway, I don't think you need to restrict yourself to 1 sentence. Two or three is fine, though I agree that you should be brief. Consider saying thanks twice, not jsut for the information, but also for the time they spent putting it together for you. Also, like most gifts, people appreciate it when they know you've actually used the product of their effort - it wasn't wasted. So an enthusiastic, but still professional, thank you might be similar to the following: Thank you for all this great information. I really appreciate the time and effort you've given me! The article on [subject] was particularly enlightening, and is proving helpful as I make this decision. I will be careful to [x], [y], and [z], this advice has really clarified a few things for me. Thanks again! I'm going to start by not answering your question: you have no need to express extreme gratitude in this case. The staff at the university are simply exhibiting good customer service: remember that they want you to come to their university and not take your custom to a different university instead and, accordingly, they have taken the time to answer your query effectively. This is doing their job not going above and beyond as you seem to think. Given this I think the appropriate response is simply a polite thank you rather than any effusive expression of extreme gratitude which I would think is likely to come across as a bit odd. To answer the question you actually posed: it rather depends on the country the university is in. In the UK, for example, we tend to find overly exuberant displays of gratitude rather odd and even a bit uncomfortable so you'd want to adopt a relatively mild tone, whereas - judging from the students from that region that I interact with - in the Middle East it is normal to thank people much more effusively. Rather than look for the most extreme adverbs and adjectives to heighten your thanks, another strategy would be to describe clearly and specifically what you found so helpful and why. Extreme expressions can be used insincerely but specific details show you have actually thought about it. If you can, I would suggest sending a thank-you card through snail mail in addition to a thank-you e-mail. Both should be short and concise, but the paper card can be a little longer. The key thing is, while it's very difficult to express the emotion of being especially thankful in words, sending a card is relatively rare these days and carries additional weight. It will not come off as unprofessional or awkward like a poorly-written thank you would, but it will convey your thanks more deeply. Considering that you're sending this note as one professional to another, I would recommend either writing the letter on your current university or company's stationary or writing in a very simple thank-you card that does not have anything pre-printed on the inside. If you would like some advice on what to include in your thank-you note, I recommend these websites. Again, your email response will likely be very short; I would recommend writing just the card like these sites suggest. A simple "Thank you" is definitely insufficient. It shows lack of understanding of how they may have spent significant time answering your questions. On the other hand, responding with almost religious adoration is also ridiculous. Using words to suggest that their response was "the best thing that ever happened to you" is absurd. Here is a general example that will point you in the right direction: "Thank you very much for your response. I'm pleased to receive such a detailed and helpful answer. Your timely efforts are greatly appreciated." This isn't complicated. I really appreciate your help with this. Thank you! Deruijter 6 years ago It might seem unprofessional, but you could add a "wow" or exclamation mark: "Wow, I didn't expect such a thorough explanation. I'm very glad to hear that!".
https://libstdc.com/us/q/academia/37862
CC-MAIN-2021-21
refinedweb
1,369
61.06
Results 1 to 1 of 1 Im trying to write some code to use wide character functions under RedHat 9 with: gcc & g++ version 3.2.2 20030222 glibc version 2.3.2-27.9.7 The following code doesnt work properly ... - Join Date - Jun 2004 - 1 Why cant i do a (w)cout then a (w)printf ? with: gcc & g++ version 3.2.2 20030222 glibc version 2.3.2-27.9.7 The following code doesnt work properly (i couldnt cut and paste from original code which is on another pc, i had to retype.. please excuse syntax errors if any). Code: #include <unistd.h> #include <wctype.h> #include <wchar.h> #include <iostream> int main( int argc, char **argv ) { wchar_t lh[2048]; memset( lh, 0, sizeof( wchar_t ) * 2048 ); wcscpy( lh, L"This is a WIDE string" ); wprintf( L"[WIDESTRING]: %ls", lh ); std::wcout << lh << std::endl; printf( "This is a non-wide printf\n" ); std::cout << "Non-Wide cout" << std::endl; wprintf( L"[WIDESTRING]: %ls", lh ); return 0; } Code: [WIDESTRING]: This is a WIDE string [WIDESTRING]: This is a WIDE string Basically it seems whatever comes first gets printed be it wcout or wprintf, the second one wont print. Infact it seems to lock in the first type and prevent usage of other streams ? The problem with this is it seems to also prevent other functions such as vswprintf() to work which is fairly annoying. Can anyone enlighten me as to why this doesnt work or what i can do to fix it? Many thanks.
http://www.linuxforums.org/forum/programming-scripting/9731-why-cant-i-do-w-cout-then-w-printf.html
CC-MAIN-2014-15
refinedweb
257
81.53
LINQ is a set of features. LINQ extension methods on IEnumerable<T> take actual methods1, whether anonymous methods: //C# Func<int,bool> fn = x => x > 3; var list = new List<int>() {1,2,3,4,5,6}; var query = list.Where(fn); 'VB.NET Dim fn = Function(x As Integer) x > 3 Dim list = New List From {1,2,3,4,5,6}; Dim query = list.Where(fn); or named methods (methods explicitly defined as part of a class): //C# class Program { bool LessThan4(int x) { return x < 4; } void Main() { var list = new List<int>() {1,2,3,4,5,6}; var query = list.Where(LessThan4); } } 'VB.NET Class Program Function LessThan4(x As Integer) As Boolean Return x < 4 End Function Sub Main Dim list = New List From {1,2,3,4,5,6}; Dim query = list.Where(AddressOf LessThan4) End Sub End Class In theory, it is possible to parse the method's IL, figure out what the method is trying to do, and apply that method's logic to any underlying data source, not just objects in memory. But parsing IL is not for the faint of heart. Fortunately, .NET provides the IQueryable<T> interface, and the extension methods at System.Linq.Queryable , for this scenario. These extension methods take an expression tree — a data structure representing code — instead of an actual method, which the LINQ provider can then parse2 and convert to a more appropriate form for querying the underlying data source. For example: //C# IQueryable<Person> qry = PersonsSet(); // Since we're using a variable of type Expression<Func<Person,bool>>, the compiler // generates an expression tree representing this code Expression<Func<Person,bool>> expr = x => x.LastName.StartsWith("A"); // The same thing happens when we write the lambda expression directly in the call to // Queryable.Where qry = qry.Where(expr); 'VB.NET Dim qry As IQueryable(Of Person) = PersonSet() ' Since we're using a variable of type Expression(Of Func(Of Person,Boolean)), the compiler ' generates an expression tree representing this code Dim expr As Expression(Of Func(Of Person, Boolean)) = Function(x) x.LastName.StartsWith("A") ' The same thing happens when we write the lambda expression directly in the call to ' Queryable.Where qry = qry.Where(expr) If (for example) this query is against a SQL database, the provider could convert this expression to the following SQL statement: SELECT * FROM Persons WHERE LastName LIKE N'A%' and execute it against the data source. On the other hand, if the query is against a REST API, the provider could convert the same expression to an API call: There are two primary benefits in tailoring a data request based on an expression (as opposed to loading the entire collection into memory and querying locally): LastName. Loading the objects into local memory and querying in-memory loses that efficiency. Notes 1. Technically, they don't actually take methods, but rather delegate instances which point to methods. However, this distinction is irrelevant here. 2. This is the reason for errors like "LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.". The LINQ provider (in this case the Entity Framework provider) doesn't know how to parse and translate a call to ToString to equivalent SQL. Query syntax and method syntax are semantically identical, but many people find query syntax simpler and easier to read. Let’s say we need to retrieve all even items ordered in ascending order from a collection of numbers. C#: int[] numbers = { 0, 1, 2, 3, 4, 5, 6 }; // Query syntax: IEnumerable<int> numQuery1 = from num in numbers where num % 2 == 0 orderby num select num; // Method syntax: IEnumerable<int> numQuery2 = numbers.Where(num => num % 2 == 0).OrderBy(n => n); VB.NET: Dim numbers() As Integer = { 0, 1, 2, 3, 4, 5, 6 } ' Query syntax: ' Dim numQuery1 = From num In numbers Where num Mod 2 = 0 Select num Order By num ' Method syntax: ' Dim numQuery2 = numbers.where(Function(num) num Mod 2 = 0).OrderBy(Function(num) num) Remember that some queries must be expressed as method calls. For example, you must use a method call to express a query that retrieves the number of elements that match a specified condition. You also must use a method call for a query that retrieves the element that has the maximum value in a source sequence. So that might be an advantage of using method syntax to make the code more consistent. However, of course you can always apply the method after a query syntax call: C#: int maxNum = (from num in numbers where num % 2 == 0 select num).Max(); VB.NET: Dim maxNum = (From num In numbers Where num Mod 2 = 0 Select num).Max(); LINQ requires .NET 3.5 or higher (or .NET 2.0 using LINQBridge). Add a reference to System.Core, if it hasn't been added yet. At the top of the file, import the namespace: using System; using System.Linq; Imports System.Linq In the following examples, we'll be using the following samples: List<Product> Products = new List<Product>() { new Product() { ProductId = 1, Name = "Book nr 1", Price = 25 }, new Product() { ProductId = 2, Name = "Book nr 2", Price = 15 }, new Product() { ProductId = 3, Name = "Book nr 3", Price = 20 }, }; List<Order> Orders = new List<Order>() { new Order() { OrderId = 1, ProductId = 1, }, new Order() { OrderId = 2, ProductId = 1, }, new Order() { OrderId = 3, ProductId = 2, }, new Order() { OrderId = 4, ProductId = NULL, }, }; INNER JOIN Query Syntax var joined = (from p in Products join o in Orders on p.ProductId equals o.ProductId select new { o.OrderId, p.ProductId, p.Name }).ToList(); Method Syntax var joined = Products.Join(Orders, p => p.ProductId, o => o.OrderId, => new { OrderId = o.OrderId, ProductId = p.ProductId, Name = p.Name }) .ToList(); Result: { 1, 1, "Book nr 1" }, { 2, 1, "Book nr 1" }, { 3, 2, "Book nr 2" } LEFT OUTER JOIN var joined = (from p in Products join o in Orders on p.ProductId equals o.ProductId into g from lj in g.DefaultIfEmpty() select new { //For the empty records in lj, OrderId would be NULL OrderId = (int?)lj.OrderId, p.ProductId, p.Name }).ToList(); Result: { 1, 1, "Book nr 1" }, { 2, 1, "Book nr 1" }, { 3, 2, "Book nr 2" }, { NULL, 3, "Book nr 3" } CROSS JOIN var joined = (from p in Products from o in Orders select new { o.OrderId, p.ProductId, p.Name }).ToList(); Result: { 1, 1, "Book nr 1" }, { 2, 1, "Book nr 1" }, { 3, 2, "Book nr 2" }, { NULL, 3, "Book nr 3" }, { 4, NULL, NULL } GROUP JOIN var joined = (from p in Products join o in Orders on p.ProductId equals o.ProductId into t select new { p.ProductId, p.Name, Orders = t }).ToList(); The Propertie Orders now contains an IEnumerable<Order> with all linked Orders. Result: { 1, "Book nr 1", Orders = { 1, 2 } }, { 2, "Book nr 2", Orders = { 3 } }, { 3, "Book nr 3", Orders = { } }, How to join on multiple conditions When joining on a single condition, you can use: join o in Orders on p.ProductId equals o.ProductId When joining on multiple, use: join o in Orders on new { p.ProductId, p.CategoryId } equals new { o.ProductId, o.CategoryId } Make sure that both anonymous objects have the same properties, and in VB.NET, they must be marked Key , although VB.NET allows multiple Equals clauses separated by And : Join o In Orders On p.ProductId Equals o.ProductId And p.CategoryId Equals o.CategoryId
https://riptutorial.com/linq/topic/842/getting-started-with-linq
CC-MAIN-2019-30
refinedweb
1,246
64.61
Testing Redis PUB/SUB in Python / aiohttp with pytest Recently I had to write Python unit tests for the Redis PUB/SUB mechanism. Backend code is written around the async web framework aiohttp and tests are ran with pytest. I was looking for a way to keep test code as compact as possible to make it easy to read while hiding the piping (database connection, async loop manipulation, etc). I also wanted to be able to send a command to Redis and read a resulting message from a PUB topic. Handling Redis connection in a fixture Let's say we want to test the following function store_id: async def store_id(redis, id): return await redis.sadd(KEY, id) Ideally the testing code should not have to deal with opening / closing a connection to a Redis engine: - it makes it easier to replace the redis object by a mock - it keep the test case readable and focused on actual testing and nothing else This is how the test case should look like: async def test_store_id(redis): id = uuid.UUID4() assert await store_id(redis, id) If you are not familiar with pytest, the redis argument here is actually a testing fixture: this value is computed each time a test / module / session (depending of the scope) is ran and injected into each test function. The aiohttp plugin for pytest defines a few fixtures. Here loop (giving access to the current async execution loop) is particularly useful to setup a new Redis connection: aioredis.create_redis is async and will run in the default loop if not specified. However, the fixture function is already running within a loop (not necessarily the default one, we don't know about the implementation details of pytest): create_redis will raise an exception if not passed the current loop. A very nice feature of pytest fixtures is the ability of expressing teardown code in a simple way: if the function yield a value (instead of simply returning it), all the remaining code will be executed at the end of the fixture scope. This is especially convenient to ensure database connections are cleanly closed. This is what the test module looks like: import aioredis import pytest async def start_redis(loop): return await aioredis.create_redis(loop=loop) async def stop_redis(redis): redis.close() await redis.wait_closed() @pytest.fixture() def redis(loop): redis = loop.run_until_complete(start_redis(loop)) yield redis loop.run_until_complete(stop_redis(redis)) async def test_store_id(redis): id = uuid.uuid4() assert await store_id(redis, id) Testing PUB/SUB Now let's say that store_id publishes the newly stored ID through a PUB/SUB channel: async def store_id(redis, id): if await redis.sadd(KEY, id): await redis.publish(CHANNEL, id) return False We want to test if the ID is properly published, but still hide the implementation details around connection setup / teardown. A neat way of achieving this is to have a fixture returning a callable (a closure in our case, but if could be class with a __call__ method), hiding all the piping code. The callable will take another callable as an argument, to be executed when a message is received. @pytest.fixture() def listen(loop): # Setup: open a Redis connection and SUBSCRIBE to a channel redis = loop.run_until_complete(start_redis(loop)) sub = loop.run_until_complete(redis.subscribe(CHANNEL)) # Define the fixture callable async def wrapper(on_message_received): await sub.wait_message() msg = await sub.get() return await on_message_received(msg) yield wrapper # Teardown: close the connection to redis loop.run_until_complete(stop_redis(redis)) Note that we need to open another connection dedicated to SUBSCRIBE to Redis messages: the same connection cannot be used both to emit commands to Redis and listen to PUB/SUB. From Redis doc: A client subscribed to one or more channels should not issue commands, although it can subscribe and unsubscribe to and from other channels. The replies to subscription and unsubscription operations are sent in the form of messages, so that the client can just read a coherent stream of messages where the first element indicates the type of message. The commands that are allowed in the context of a subscribed client are SUBSCRIBE, PSUBSCRIBE, UNSUBSCRIBE, PUNSUBSCRIBE, PING and QUIT. Now the test case just has to define a function that will be executed when a message is received. Result of the tested function and the SUBSCRIBE callbacks are simultaneously awaited with asyncio.gather. async def test_store_id(redis, listen): id = uuid.UUID4() def on_message_received(msg): assert msg == str(id) results = await asyncio.gather( listen(on_message_received), store_id(redis, id) ) assert results[1] # Checking the return value for store_id Full code for this example is available here.
https://charlesfleche.net/en/aiohttp-pytest-redis-pubsub/
CC-MAIN-2018-43
refinedweb
763
52.8
Drawing a Simple Circle - PDF for offline use - - Sample Code: - - Related APIs: - Let us know how you feel about this Translation Quality 0/250 last updated: 2017-03 Learn the basics of SkiaSharp drawing, including canvases and paint This article introduces the concepts of drawing graphics in Xamarin.Forms using SkiaSharp, including creating an SKCanvasView object to host the graphics, handling the PaintSurface event, and using a SKPaint object to specify color and other drawing attributes. The SkiaSharpFormsDemos program contains all the sample code for this series of SkiaSharp articles. The first page is entitled Simple Circle and invokes the page class SimpleCirclePage. This code shows how to draw a circle in the center of the page with a radius of 100 pixels. The outline of the circle is red, and the interior of the circle is blue. The SimpleCirle page class derives from ContentPage and contains two using directives for the SkiaSharp namespaces: using SkiaSharp; using SkiaSharp.Views.Forms; The following constructor of the class creates an SKCanvasView object, attaches a handler for the PaintSurface event, and sets the SKCanvasView object as the content of the page: public SimpleCirclePage() { Title = "Simple Circle"; SKCanvasView canvasView = new SKCanvasView(); canvasView.PaintSurface += OnCanvasViewPaintSurface; Content = canvasView; } The SKCanvasView occupies the entire content area of the page. You can alternatively combine an SKCanvasView with other Xamarin.Forms View derivatives, as you'll see in other examples. The PaintSurface event handler is where you do all your drawing. This method is generally called multiple times while your program is running, so it should maintain all the information necessary to recreate the graphics display: void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args) { ... } The SKPaintSurfaceEventArgs object that accompanies the event has two properties: Infoof type SKImageInfo Surfaceof type SKSurface The SKImageInfo structure contains information about the drawing surface, most importantly, it's width and height in pixels. The SKSurface object represents the drawing surface itself. In this program, the drawing surface is a video display, but in other programs an SKSurface object can also represent a bitmap that you use SkiaSharp to draw on. The most important property of SKSurface is Canvas of type SKCanvas. This class is a graphics drawing context that you use to perform the actual drawing. The SKCanvas object encapsulates a graphics state, which includes graphics transforms and clipping. Here's a typical start of a PaintSurface event handler: void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args) { SKImageInfo info = args.Info; SKSurface surface = args.Surface; SKCanvas canvas = surface.Canvas; canvas.Clear(); ... } The Clear method clears the canvas with a transparent color. An overload lets you specify a background color for the canvas. The goal here is to draw a red circle filled with blue. Because this particular graphic image contains two different colors, the job needs to be done in two steps. The first step is to draw the outline of the circle. To specify the color and other characteristic of the line, you create and initialize an SKPaint object: void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args) { ... SKPaint paint = new SKPaint { Style = SKPaintStyle.Stroke, Color = Color.Red.ToSKColor(), StrokeWidth = 25 }; ... } The Style property indicates that you want to stroke a line (in this case the outline of the circle) rather than fill the interior. The three members of the SKPaintStyle enumeration are as follows: The default is Fill. Use the third option to stroke the line and fill the interior with the same color. Set the Color property to a value of type SKColor. One way to get an SKColor value is by converting a Xamarin.Forms Color value to an SKColor value using the extension method ToSKColor. The Extensions class in the SkiaSharp.Views.Forms namespace includes other methods that convert between Xamarin.Forms values and SkiaSharp values. The StrokeWidth property indicates the thickness of the line. Here it's set to 25 pixels. You use that SKPaint object to draw the circle: void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args) { ... canvas.DrawCircle(info.Width / 2, info.Height / 2, 100, paint); ... } Coordinates are specified relative to the upper-left corner of the display surface. X coordinates increase to the right and Y coordinates increase going down. In discussion about graphics, often the mathematical notation (x, y) is used to denote a point. The point (0, 0) is the upper-left corner of the display surface and is often called the origin. The first two arguments of DrawCircle indicate the X and Y coordinates of the center of the circle. These are assigned half the width and height of the display surface to put the center of the circle in the center of the display surface. The third argument specifies the circle's radius, and the last argument is the SKPaint object. To fill the interior of the circle, you can alter two properties of the SKPaint object and call DrawCircle again. This code also shows an alternative way to get an SKColor value from one of the many fields of the SKColors structure: void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args) { ... paint.Style = SKPaintStyle.Fill; paint.Color = SKColors.Blue; canvas.DrawCircle(args.Info.Width / 2, args.Info.Height / 2, 100, paint); } This time, the DrawCircle call fills the circle using the new properties of the SKPaint object. Here's the program running on iOS, Android, and the Universal Windows Platform: When running the program yourself, you can turn the phone or simulator sideways to see how the graphic is redrawn. Each time the graphic needs to be redrawn, the PaintSurface event handler is called again. An SKPaint object is little more than a collection of graphics drawing properties. These objects are very lightweight. You can reuse SKPaint objects as this program does, or you can create multiple SKPaint objects for various combinations of drawing properties. You can create and initialize these objects outside of the PaintSurface event handler, and you can save them as fields in your page class. Although the width of the circle's outline is specified as 25 pixels — or one-quarter of the radius of the circle — it appears to be thinner, and there's a good reason for that: Half the width of the line is obscured by the blue circle. The arguments to the DrawCircle method define the abstract geometric coordinates of a circle. The blue interior is sized to that dimension to the nearest pixel, but the 25-pixel-wide outline straddles the geometric circle — half on the inside and half on the outside. The next sample in the Integrating with Xamarin.Forms article demonstrates this visually..
https://developer.xamarin.com/guides/xamarin-forms/advanced/skiasharp/basics/circle/
CC-MAIN-2017-30
refinedweb
1,082
55.84
Odoo Help Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps: CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc. Get values from python method - Odoo 8 Hello all Is there a way to call a method in the .py file from the xml without define a new field? E.g.: model.py @api.model def get_companies(self): return self.env['res.partner'].search(['is_company', '=', True]) view.py <field name="get_companies" colspan="4" nolabel="1"> <tree string="Companies"> <field name="id"/> <field name="name"/> <field name="vat"/> </tree> </field> Regards Alejandro If the method does not depends on specific records, you may want to try to use context supplied from fields_view_get. However I think function field is easier to implement. Thank you Ivan, then, I will use a function field to reference those values. Could you please include some source or explanation for fields_view_get usage to accept your answer as the solution? The two samples that you'll find most useful, AFAIK, is from account.voucher (odoo/addons/account_voucher/account_voucher.py) and account.invoice (odoo/addons/account/account_invoice.py). They are a model that is used for several purposes (types) and the view need to be customised for each purpose/type. About This Community Odoo Training Center Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now
https://www.odoo.com/forum/help-1/question/get-values-from-python-method-odoo-8-70941
CC-MAIN-2017-17
refinedweb
236
57.87
WiringPi includes a software-driven PWM handler capable of outputting a PWM signal on any of the Raspberry Pi’s GPIO pins.. To use: #include <wiringPi.h> #include <softPwmP. The return value is 0 for success. Anything else and you should check the global errno variable to see what went wrong. - void softPwmWrite (int pin, int value) ; This updates the PWM value on the given pin. The value is checked to be in-range and pins that haven’t previously been initialised via softPwmCreate will be silently ignored. Notes - Each “cycle” of PWM output takes 10mS with the default range value of 100, so trying to change the PWM value more than 100 times a second will be futile. - Each pin activated in softPWM mode uses approximately 0.5% of the CPU. - There is currently no way to disable softPWM on a pin while the program in running. - You need to keep your program running to maintain the PWM output!
http://wiringpi.com/reference/software-pwm-library/
CC-MAIN-2018-17
refinedweb
160
66.94
Board index » tcl All times are UTC -Dan This is the same way to do things like forcing int on an entry widget. -- Jeffrey Hobbs Office: 503/346-3998 URL: 1. Help on entry widget input encoding 2. Help on entry widget in TK 3. Help with entry widget and name completion. 4. Need help initializing entry widgets within namespaces 5. using entry widget inside tixGrid widget (or list widget) 6. VTCL Entry Widget help! 7. Help on input encoding in entry widget 8. newbie: trying to create password entry widget - help! 9. scan from an entry widget help :( 10. Need Help With tk Entry Widgets 11. Help: scroll in entry widgets 12. Entry widget help
http://computer-programming-forum.com/57-tcl/02c361118262c325.htm
CC-MAIN-2021-04
refinedweb
116
71.71
Subject: Re: [boost] [Boost-users] [typeindex v3.0] Peer review begins Mon 21st ends Wed 30th From: Andrey Semashev (andrey.semashev_at_[hidden]) Date: 2014-04-27 10:30:58 On Wednesday 23 April 2014 11:15:35 Nat Goodspeed wrote: > [Not a review, but a response to one of Paul's comments] > > > On 23 Apr 2014 at 14:33, Paul A. Bristow wrote: > >> Though I'm not enthusiastic about the name of namespace boost::typeind:: > >> but I don't have any much better ideas. Perhaps someone else has? > > > > To clarify the issue to everyone else, TypeIndex is in a rather > > unusual bind with regard to what namespace to use. Ideally I think > > we'd all agree that boost::type_index would be best, but then one of > > the issues raised last peer review was that there shouldn't be a > > boost::type_index type as could conflict with std::type_index, and if > > we hold that to be wise, then surely the same rationale applies for a > > boost::type_index namespace as well. > > > > So we end up with boost::typeind, which I don't think makes anyone > > happy, but it is safe. > > I don't suppose boost::typeindex would be an improvement? That name at > least immediately suggests to the reader which library to look up. Yes, I think that one is ok, too. 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/2014/04/212830.php
CC-MAIN-2019-43
refinedweb
242
74.08
I've been meaning to graft Bayesian classification on to newspipe for months now (probably even years), but never found a usable solution for doing it. The main reason is that it is very tricky to set up a decent training mechanism that newspipe can take advantage of and that doesn't get in the way. From a coding perspective, things are pretty straightforward - it knows that it has incoming feeds, an outbound e-mail address, and a bunch of history files that tell it which items it has seen (and that, conceivably, could be extended to add Bayesian classification). So I tried creating a little web UI to deal with those, but manipulating the files directly was tricky, and setting up an HTTP thread within newspipe itself was altogether too fiddly - not because it was tough to code, but because it was a mess in terms of UI - you viewed a feed item in Mail.app (which is where I want to read and manipulate news), clicked on a training link, and up came Safari, blocking your view of Mail.app. This week, I decided I had had enough with reading RSS feeds - even if altogether I only spent about an hour a day doing so, it was one hour too much, most of which seemed to consist of wading through crap. Since I've been tinkering with IMAP for a while now (for a number of different reasons, one of which consists of exploring ways of using it for a Wiki back-end), I decided to approach the issue from a different angle: On my "news" IMAP account, I set up three folders: - Archive, which has always been there, and where I store everything I want to keep for an extended period of time (including web page archives created with MailArchive.py) - Interesting, for stuff I find interesting, but don't really want to keep. - Junk, which has always been there as well, but which is now used for a different purpose. Then I added corresponding Mail Act-On rules to move messages into each (Archive and Junk had always been there, too, but Iinteresting wasn't), and defined a Flagged folder that listed only flagged items from that INBOX. You may have guessed where this is going - yes, that's the one I read. I have also been thinking about using MailTags, but I wanted a simple, surefire approach. I then grabbed thomas.py from divmod's ancient Python toolkit (the latest is here, I've had a copy on my hard disk for years now), and set to coding something like this: - Check Archive and Interesting for new messages - Train the Bayesian classifier with those (into the flag bucket) - Check Junk for new messages - Train the Bayesian classifier with those (into the junk bucket) - Check INBOX for new messages - Classify each one and set the IMAP \Flagged flag as appropriate. The resulting script runs every 30 minutes and assumes the messages are either HTML mail as generated by newspipe and the rest of my stuff, or plaintext. And since it bases its classification on what I toss into particular IMAP folders, it allows me to train it in a painless, simple fashion, without ever leaving Mail.app. So far, it seems to be working (it seems to be catching on to what I like and don't like), and with luck, I'll be letting it delete RSS items fairly soon. It isn't particularly complex, so I'm posting it inline - apologies in advance to those of you who hate code listings. Oh, and those of you using Plagger might be able to use this as well. Have the appropriate amount of fun. #!/usr/bin/env python """IMAP Bayes Classifier""" __version__ = "0.1" __author__ = "Rui Carmo ()" __copyright__ = "(C) 2006 Rui Carmo. Code under BSD License." import getpass, os, gc, sys, time, platform, getopt import mailbox, rfc822, imaplib, socket import StringIO, re, csv, sha, gzip, bz2 import cPickle, BeautifulSoup from email.Parser import Parser from email.Utils import decode_rfc2231 from thomas import Bayes uidpattern = re.compile("\d+ \(UID (\d+)\)") whitespace = re.compile("\s+", re.MULTILINE) def remap(a): return (a[0], a[1]) class Classifier: def __init__(self, imap, folders = {'archive':'Archive', 'interesting':'Interesting', 'junk':'Junk','inbox':'INBOX'}, path = '.'): self.imap = imap self.bayesState = path + "/bayes.dat" self.imapState = path + "/imap.dat" self.folders = folders self.reverend = Bayes() def run(self): if os.path.exists(self.bayesState): self.reverend.load(self.bayesState) if os.path.exists(self.imapState): self.known = cPickle.load(open(self.imapState,'rb')) else: self.known = {} for key in self.folders.keys(): self.known[self.folders[key]] = [] self.train(self.folders['archive'],'flag') self.train(self.folders['interesting'],'flag') self.train(self.folders['junk'],'junk') self.classify(self.folders['inbox']) def classify(self, folder):: guess = dict(map(remap,self.reverend.guess(self.distillMessage(uid)))) if guess['flag'] > 0.90: typ, data = self.imap.uid("STORE", uid, "FLAGS" ,"(\Flagged)") cPickle.dump(self.known, open(self.imapState,'wb')) def train(self, folder, bucket):: self.reverend.train(bucket,self.distillMessage(uid)) self.reverend.save(self.bayesState) cPickle.dump(self.known, open(self.imapState,'wb')) def distillMessage(self, uid): typ, data = self.imap.uid("FETCH", uid, "RFC822.PEEK") p = Parser() msg = p.parsestr(data[0][1]) for part in msg.walk(): content = part.get_content_type() if content == 'text/html': soup = BeautifulSoup.BeautifulSoup(part.get_payload(decode=True),convertEntities=BeautifulSoup.BeautifulStoneSoup.ALL_ENTITIES,smartQuotesTo=None) plaintext = u' '.join(soup.findAll(text=re.compile('.+'))) break # we assume there is a single html part worth decoding elif content == 'text/plain': plaintext = part.get_payload(decode=True) plaintext = whitespace.sub(' ', plaintext) return plaintext.encode('utf-8') def main(): try: opts, args = getopt.getopt(sys.argv[1:], "c:s:u:p", ["corpus=","server=", "username=","password="]) except getopt.GetoptError: print "Usage: bayesimap.py [OPTIONS]" print "-s HOSTNAME --server=HOSTNAME connect to HOSTNAME" print "-u USERNAME --username=USERNAME with USERNAME" print "-p PASSWORD --password=PASSWORD with PASSWORD (you will be prompted for one if missing)" sys.exit(2) corpus = username = password = server = None clobber = False for option, value in opts: if option in ("-s", "--server"): server = value if option in ("-u", "--username"): username = value if option in ("-p", "--password"): password = value if(server is None): print "ERROR: No server specified." sys.exit(2) if(username is None): print "ERROR: No username specified." sys.exit(2) if(password is None): password = getpass.getpass() server = imaplib.IMAP4(server) server.login(username, password) c = Classifier(server) c.run() server.logout() if __name__ == '__main__': main() Update: Those of you who don't think reading RSS feeds by e-mail is the right way to go will like to know that I also have a simple web interface that accesses my news IMAP account (via browser or mobile phone) and lets me classify items: So I have all the advantages of web-based feed readers, plus being able to archive everything for years (without, say, images going stale), performing full-text search (via Spotlight or anything else that talks to IMAP) and easily forward news items to my friends and colleagues.
http://the.taoofmac.com/space/blog/2006/11/04
crawl-002
refinedweb
1,178
55.24
API documentation of an application is one of the most tedious tasks for all developers. NDoc makes it very easy for everyone. In this article, I will try to explain how we can use NDoc to generate MSDN style documentation for your class libraries. NDoc generates class libraries documentation from .NET assemblies and the XML documentation files generated by the C# compiler (or an add-on tool for VB.NET such as VBCommenter). NDoc uses add-on documenters to generate documentation in several different formats, including the MSDN-style HTML Help format (*.chm), the Visual Studio .NET Help format (HTML Help 2), and MSDN-online style Web pages. The NDoc source code is available under the GNU General Public License. If you are unfamiliar with this license or have questions about it, here is a FAQ. You can download the NDoc utility files from SourceForge.Net. Now open the solution for which you want to generate documentation in Visual Studio 2005. Add a sample class library to test or you can use any existing one. Select the class library for which you want to create documentation. Right click on it and click on “Properties”. You will see the following dialog box. Now click on the ‘Build’ tag. You will see one check box “XML documentation file:” (See the red eclipse part above). Just enable that check box and specify a name for a *.doc file. NDoc uses this file for creating documentation. Now build your class library. Just check the Debug/Release folder (depends on your build configuration). You will see the documentation file in XML format. NDoc’s help will give you a brief idea about how you can document your class library more effectively. Here are some tips from NDoc’s documentation: public class MyClass() { public MyClass( string s ) { } } If you place your cursor just above the MyClass constructor, and hit the '/' character three times in a row, VS.NET will create the skeleton of a code comment block for that member: MyClass public class MyClass() { /// <span class="code-SummaryComment"><summary></span> /// /// <span class="code-SummaryComment"></summary></span> /// <span class="code-SummaryComment"><param name="s"></param></span> public MyClass( string s ) { } } This applies to any type or member that can have code comment tags associated with it. Moreover, once you have a code comment block, when you hit the '<' key to start a new tag, VS.NET will display an intellisense selector showing the appropriate list of code comment tags. Unfortunately this list won't include the additional tags that NDoc supports, but you can still add them manually. NDoc supports a large number of documentation tags. You can use it as per your requirement. Ok… so your project is now ready for documentation. Now just unzip the NDoc file which you have already downloaded from SourceForge.net. I have this version ndoc-bin-1.3.1-v16.zip. Browse the unzipped archive and locate file NDocGui.exe. This gives a better GUI to use NDoc. The same folder contains the command line utility NDocConsole.exe. We can use the command line utility for the automated build process. In this article, I am going to explain the GUI utility only. Double click on NDocGui.exe. You will see the NDoc GUI console. Click on Project->New. Notice the “Select and Configure Documenter” section. Here you can specify the output documentation type. NDoc can generate a document in various formats like MSDN, Linear HTML, JavaDoc etc. Select MSDN for now. Below that you can see various options to configure your documentation output like Copyright text, Output directory etc. The most important settings are in the visibility section. Just check which elements you want to document. For example, private variables, protected variables, Namespaces without summaries etc. (Check out the red eclipse in the following image.) Now click on Add. This will open up the following dialog box. You will see a small command button to specify a value for the key "Assembly" through which you can browse for your assembly path. Select the EXE/DLL file of your application which you want to document. NDoc will automatically take an XML documentation file as per the selected EXE or DLL file. Now save the NDoc project file somewhere. So next time if we modify the source, we can open the saved project in NDoc and then we can do the documentation build again. Now Build the file. You can see the Build button on the left upper corner of the screen shown below. Click on it. All build messages will appear in the “Output” section of the GUI console. You will see the last message as given below: Created c:\Documents and Settings\vinayakc\Desktop\New Folder\doc\ndoc_msdn_temp\Documentation.chm, 57,879 bytes Compression decreased file by 238,719 bytes. Html Help compile complete Done. Now check the output directory specified in the output message. You will find the *.chm file there which will be the compiled documentation for your class library. Just double click it and enjoy your application’s professional documentation..
http://www.codeproject.com/Articles/22737/Documentation-of-NET-Class-Libraries-using-NDoc
CC-MAIN-2015-40
refinedweb
843
68.47
In this article, we won’t be going too deep into Ida scripting. Instead, we’ll present what an IDC is and how it can be used to enhance the capabilities of Ida. We’ll also present the basic structure of the IDC script, not the advanced usage. Then we’ll name the shortcomings of IDC and present a better way to extend Ida with the use of Ida SDK, which is capable of providing much more power when writing an Ida extension. And lastly, we’ll present remote debugging capabilities of Ida, so the article will be more about discussing what Ida has to offer and not just an in-depth overview of the topics. Ida IDC If you’re reading this, I’m sure you know that Ida has a scripting language IDC that can be used to write our own little scripts and that it can be used to automate the things we do most often. Before anything else, we must understand how we can interact with the Ida scripting engine. We can do that by choosing File – IDC Command, which opens a pop-up window where we must enter the command. We can see that window on the picture below: The other option is by loading the Ida script via File – Script File. A pop-up window then asks us to choose the .idc script file from the file system that we wish to execute. We can see that on the picture below: The command dialog is very useful when we want to test specific commands without creating a new file, but if we intend to write a full-blown plugin, it’s better to create a file and execute it as a script rather than as a command. However, there’s another way to simply execute a one-line command which is very similar to the File – IDC Command option. We don’t have to click on anything to bring up a pop-up window where we can enter the command; it’s already present on the bottom of the Ida main window. It looks like the picture below: In that input box, we can essentially write the same information as in the File – IDC Command or even in a standalone script. This is the easiest way to execute one command at a time, which can prove very useful and may also be the quickest way to do it. Actually, we can even execute multiple commands, which must be separated by semicolons. IDC Language The variables in the IDC language are one of the following data types: - signed integers (there are no unsigned integers) - strings - floating point numbers Also, there is no notion of global variables in IDC language; only local variables are supported. We also can’t assign a value to the variable at the same time as we’re declaring the variable. First, we must declare a variable and then assign its value. To declare a variable, we must use the following syntax: auto myaddr; The keyword auto is used to declare the variable, which in this case has the name myaddr. The IDC language supports if statements, if-else statements, for loops, while loops, but not switch statements. There is no printf function in IDC, but a Message function can be used instead, which supports the same format and arguments as the printf function. In IDC, we can declare a function with the use of the static keyword, followed by the function name, followed by the parameters that the function accepts, which are separated by commas. When calling a function, every parameter is copied to the function, so IDC doesn’t support references and pointers. We can also return a value from the function by using the return keyword; if the function doesn’t return anything explicitly then, by default, it returns zero. When creating a standalone script, we must always have the function main, which doesn’t accept any arguments, and we must also include the idc.idc file like this: #include <idc.idc> static main() { } The IDC language supports the same preprocessor directives as C programming language does, namely #include, #define, #ifdef, #else, #endif and #undef. IDC language also provides many functions which we can use to interact with the Ida database. We won’t describe them all in detail here. All available functions and their descriptions can be found in the Ida Help menu, shown below: We can see that we selected the “Alphabetical list of IDC functions” on the index on the left and on the right is the list of all IDC functions. Ida SDK If you’re reading this and, at the same time, you’re wondering why you would want to use Ida SDK, you’ve come to the right place. Imagine that you need some functionality that isn’t already implemented in Ida, either by default or by any other plugins out there. In such cases, the first thing would be to turn to the IDC scripting language and try to write a script that can solve the problem we have. But after a while, you may realize that it’s really awkward to try to do it with IDC because of its limitations, or maybe even because it’s not possible in a reasonable amount of time. If so, it’s best to turn to Ida SDK, which is basically the same as IDC, but is much more powerful. The IDC is built on top of SDK, so by using SDK, we’re bypassing the IDC and using the SDK directly, which gives us much more freedom and possibilities than we’ve ever had in the IDC. Remote Debugging With remote debugging features, we can always work from our main computer and then debug applications on various operating systems remotely. This is a big pro because it gives us access to a compromised machine while we work directly from our main system. In order to make remote debugging work, we need to set-up Ida Pro debugger client and server. Remote Ida Pro Server In order to connect to the Ida remote server with the Ida client, we first need to start the Ida server. To do that, we must run the following command on the operating system on which the process is to be debugged. We can launch one of the following executables on Windows, Linux and OSX: # win32_remote.exe # linux_server # mac_server There are also appropriate 64-bit executables that can be used to start a server like this: # win64_remote64.exe # linux_server64 # mac_server64 The only thing that’s required to start debugging remotely is to start the Ida server on the operating system where we would be debugging the program. This means that we don’t have to install the full version of Ida on the remote platform. After we start the remote Ida server, we then connect to the Ida server with the Ida client from an arbitrary operating system. We can pass various options to the remote Ida server when starting it. On Linux, the linux_server is located under the dbgsrv/ folder in the Ida home directory. The remote Ida server has the following options: # ./dbgsrv/linux_server -h Ida Linux 32-bit remote debug server(ST) v1.15. Hex-Rays (c) 2004-2012 Error: usage: Ida_remote [switches] -p… port number -P… password -v verbose We can see that we can specify the port number to listen on, the password to disable unauthorized access and verbose output. I guess we want to specify the password, since we don’t want anyone connecting to our remote Ida server. We can do that with the command below: # ./dbgsrv/linux_server -Padmin123 Ida Linux 32-bit remote debug server(ST) v1.15. Hex-Rays (c) 2004-2012 Listening on port #23946… We started the remote Ida server on default port 23946 and protected it with the password admin123. Remote Ida Pro Client After the remote Ida server is started, we can connect to it with an Ida client. We can do that by clicking on the Debugger menu, where we have the “Run” option. There are a couple of options we can choose from as seen on the picture below: We can see a number of different available debuggers we can choose from. If we choose one of the local debuggers, we’ll be debugging the executable locally, so no Ida remote server is required. But whenever we’re trying to debug an executable remotely, we need to choose one of the remote debuggers. If we choose remote Linux debugger, the following dialog box will pop up: We can see that we can specify a number of options that we’ll describe below. The first input field is the Application input field, where we need to input the absolute/relative path to the executable being debugged (on the remote filesystem). Usually, we would input the absolute path to the debugged executable, but we chose to enter only a partial path to the executable, which will be searched for in the current working directory. The Directory input field specifies in which directory the executable will be launched. The Parameters input field specifies any command line parameters that will be passed to the program upon starting it. And lastly, we must also specify the Hostname, Port and Password input fields, which are there to connect to the remote Ida server. Specifying the Password is optional and is only required if we started the Ida remote server with the -P switch, which denotes that the Ida client must also specify the password upon connecting to the server. Conclusion If we find ourselves doing something repeatedly, stop! Instead, write an IDC script that can automate this for you. Imagine when you don’t need to do specific actions manually anymore, but you can just press a certain shortcut that was assigned to your script and the script executes providing you with the information that you need. If the IDC isn’t powerful enough, use SDK, which should provide everything we’re ever going to need in order to write extensions in Ida. We’ve also looked at remote debugging, which can be quite handy when we would like to connect to a remote instance of Ida server and start debugging on an arbitrary operating system right from our desktop machine without too much trouble. References [1] Chris Eagle, The IDA Pro Book: The unofficial guide to the world’s most popular disassembler.
http://resources.infosecinstitute.com/ida-idc-sdk-remote-debugging-overview/
CC-MAIN-2015-11
refinedweb
1,743
65.66
Eric W. Biederman wrote:> Hubertus Franke <frankeh@watson.ibm.com> writes:> > ...> >>Actions: The vpid_to_pid will disappear and the check for whether we are in the>>same>>container needs to be pushed down into the task lookup. question remains to>>figure out>>whether the context of the task lookup (will always remain the caller ?).> > > You don't need a same container check. If something is in another container> it becomes invisible to you.> Eric, agreed.... that was implied by me (but poorly worded). What I meant (lets try thisagain) is that the context defines/provides the namespace in which the lookupis performed, hence as you say state.. naturally things in different containers(namespaces) are invisible to you..> >>Doing so has an implication, namely that we are moving over to "system>>containers".>>The current implementation requires the vpid/pid only for the boundary condition>>at the>>top of the container (to rewrite pid=1) and its parent and the fact that we>>wanted>>a global look through container=0.>>If said boundary would be eliminated and we simply make a container a child of>>the>>initproc (pid=1), this would be unnecessary.>>>>all together this would provide private namespaces (as just suggested by Eric).>>>>The feeling would be that large parts of patch could be reduce by this.> > > I concur. Except I think the initial impact could still be large.> It may be worth breaking all users of pids just so we audit them.> > But that will certainly result in no long term cost, or runtime overhead.> > >>What we need is a new system calls (similar to vserver) or maybe we can continue>>the /proc approach for now...>>>>sys_exec_container(const *char container_name, pid_t pid, unsigned int flags,>>const *char argv, const *char envp);>>>>exec_container creates a new container (if indicated in flags) and a new task in>>it that reports to parent initproc.>>if a non-zero pid is specified we use that pid, otherwise the system will>>allocate it. Finally>>it create new session id ; chroot and exec's the specified program.>>>>What we loose with this is the session and the tty, which Cedric described as>>application>>container...>>>>The sys_exec_container(...) seems to be similar to what Eric just called>>clone_namespace()> > > Similar. But I was actually talking about just adding another flag to> sys_clone the syscall underlying fork(). Basically it is just another> resource not share or not-share.> > Eric> That's a good idea .. right now we simply did this through a flag left by the callto the /proc/container fs ... (awkward at best, but didn't break the API).I have a concern wrt doing it in during fork namely the sharing of resources.Whe obviously are looking at some constraints here wrt to sharing. We need toensure that this ain't a thread etc that will share resourcesacross "containers" (which then later aren't migratable due to that sharing).So doing the fork_exec() atomically would avoid that problem.-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
http://lkml.org/lkml/2006/1/23/183
CC-MAIN-2015-11
refinedweb
518
57.27
> So currently the scrollrect only works with mouse scrollwheel and mouse drag. Is there actually a way to get it working with gamepad? Eg right analog or something? Looked at documentation, didnt see anything really useful Answer by SirKurt · Jan 15, 2015 at 03:59 PM You can implement a new class from Scrollrect and IMoveHandler. Also IPinterClickHandler so you can select the object on pointer click. Full code looks like this. You should attach this to your ui object which is going to be ScrollRect. using UnityEngine; using System.Collections; using UnityEngine.UI; using UnityEngine.EventSystems; public class MoveScrollRect : ScrollRect, IMoveHandler, IPointerClickHandler { private const float speedMultiplier = 0.1f; public float xSpeed = 0; public float ySpeed = 0; private float hPos, vPos; void IMoveHandler.OnMove(AxisEventData e) { xSpeed += e.moveVector.x * (Mathf.Abs(xSpeed) + 0.1f); ySpeed += e.moveVector.y * (Mathf.Abs(ySpeed) + 0.1f); } void Update() { hPos = horizontalNormalizedPosition + xSpeed * speedMultiplier; vPos = verticalNormalizedPosition + ySpeed * speedMultiplier; xSpeed = Mathf.Lerp(xSpeed, 0, 0.1f); ySpeed = Mathf.Lerp(ySpeed, 0, 0.1f); if(movementType == MovementType.Clamped) { hPos = Mathf.Clamp01(hPos); vPos = Mathf.Clamp01(vPos); } normalizedPosition = new Vector2(hPos, vPos); } public void OnPointerClick(PointerEventData e) { EventSystem.current.SetSelectedGameObject(gameObject); } public override void OnBeginDrag(PointerEventData eventData) { EventSystem.current.SetSelectedGameObject(gameObject); base.OnBeginDrag(eventData); } } I couldn't find an elegant way to update ScrollRect position. Also as you see I calculate the scrolling speed myself. It can be tweaked to work better. Anyways, if you improve the code, let me know. alright, looking forward to the updated code :) Updated the code. Check it out. cool so I'm assuming this will work for gamepad too? Also, while we are on the subject, is it possible to make it so if gamepad is plugged in, it will scroll to a certain point? I have tested. It works with gamepad. You can set "normalizedPosition" field to scroll the ScrollRect. It should take a value between 0 and 1 if you want it to stay in frame. Input class has methods that tells if a gamepad is connected or not. You can use that to set the position and also select the rectangle when a joystick is connected. I have a problem. The scrolling works fantastically thank you very much now my problem is, if I want to select a button which is further down I cant do that because I scroll to it and then my gamepad actually doesnt want to select any. Multiple Cars not working 1 Answer Distribute terrain in zones 3 Answers Are there any alternatives/fixes to/for ScrollRect? 0 Answers How can I make my scroll list scroll 1 item per button click? 1 Answer Drag on Scroll Rect Non Proportional 0 Answers
https://answers.unity.com/questions/874310/scrollrect-gamepad-support.html
CC-MAIN-2019-22
refinedweb
449
61.73
A new python convert is now looking for a replacement for another perl idiom. In particular, since Perl is weakly typed, I used to be able to use unpack to unpack sequences from a string, that I could then use immediately as integers. In python, I find that when I use struct.unpack I tend to get strings. (Maybe I am using it wrong?) def f(x,y,z): print x+y+z; f( *struct.unpack('2s2s2s','123456')) 123456 (the plus concatenates the strings returned by unpack) But what I want is: f( *map(lambda x: int(x), struct.unpack('2s2s2s','123456'))) 102 But this seems too complicated. I see two resolutions: 1. There is a way using unpack to get out string-formatted ints? 2. There is something like map(lambda x: int(x).... without all the lambda function call overhead. (e.g., cast tuple)? [And yes: I know I can write my own "cast_tuple" function -- that's not my point. My point is that I want a super-native python inline solution like (hopefully shorter than) my "map" version above. I don't like defining trivial functions.] W
https://grokbase.com/t/python/python-list/107w7d0rz3/nice-way-to-cast-a-homogeneous-tuple
CC-MAIN-2022-33
refinedweb
190
76.93
This article will show you how to do it using Mutex. You've built an application and would like it to run a single instance. Here comes Mutex to the rescue! To do that you have to create a Mutex object at startup and when its over release it. First add System.Threading namespace: using System.Threading; Then create a boolean variable and a Mutex object to control if Mutex is owned by application bool isMutexOwned; Mutex mut = null; Then create a Mutex instance and control this Mutex via isMutexOwned boolean var. using(Mutex mut=new Mutex(true,"My Mutex",out isMutexOwned)){ if(isMutexOwned) { //Do Something...Mutex is owned by the application } else { //Mutex isnt owned.So other instances can run. }} public void ReleaseMut(){ mut.ReleaseMutex();} Add a Button Click event and raise ReleaseMut function. See what happens. After that another instance of application will now run. View All
https://www.c-sharpcorner.com/UploadFile/iersoy/running-single-instance-of-the-application/
CC-MAIN-2019-39
refinedweb
149
53.07
Fact is, I just can't follow discussions of mechanism without reference to _some_ more-or-less concrete problem they're intended to solve, and I had no problem with Python's current scope rules before a feature was introduced (namely lambdas) whose use in practice often requires a bit more than Python now allows. One of the first good papers to seriously question the value of classical nested scopes is Dave Hanson's "Is Block Structure Necessary?" (Software Practice & Experience, Vol 11, pp 853-866, 1981). He argues that CSNS creates at least as many problems as it solves, that simple non-nested modules solve the same problems without CSNS's drawbacks, and illustrates with non-trivial programs written idiomatically in both styles. Agree with him or not-- and I mostly do --at least you can figure out what he's talking about <grin>. So the next time a scoping extension is proposed here, would the proposer please illustrate with a semi-realistic example of a problem whose solution, in Python, would be "better" (cleaner, more understandable, safer, more maintainable, whatever ...)? That's not just for my sake -- especially if you're a newcomer to Python, you may discover there's a better way to do it already! Python is clear, but it's not self-evident ... > [ste: > def yyy(): > ... > > I don't think THAT part of the scheme should be very controversial, It might be if you spelled out all the rules <wink>. E.g., is "prompt" visible inside "yyy" short of spelling it "xxx.prompt"? And if the thrust really is to avoid cluttering the exported namespace, perhaps a by-now-classical "export" statement (limiting external visibility, when present, to an explicit list of module-global names) would be more to the point? > but adding other functions to manipulate environments ( like real > versions of my bind() and merge(), etc. ) might be, and I haven't > thought out the implications myself. So let's try to solve a real problem with them -- implications live in the trenches. What do you imagine doing with them? It's at least interesting that Guido's default-argument idea, when (ab?)used to sneak values into the function's local NS, effectively creates a partial closure (the function, + a fixed-for-all-time binding for each of the default-valued arguments). > [guido] > I have also thought of somehow unifying modules and classes ... The only difference I see between Steve's module xxx: prompt = "Hello, sailor!" def yyy(): and class XXX: prompt = "Hello, sailor!" def yyy(): is that XXX.yyy() yields a "unbound method must be called with class instance argument" TypeError, while xxx.yyy() presumably wouldn't. Wonder what multiple inheritance for a _module_ might mean <grin?>. > ... > I still think there is not enough need for CSNS to warrant this kind of > construct, which can easily confuse the human reader when there are > more than two or three scopes involved and some are textually far apart Well, I don't see any need for CSNS (assuming something simpler can be done about lambda), but want to emphasize that CSNS _in Python_ would be 3x more confusing than in Pascal/Ada/whatever. As Steve implied, the lack of declarations means a user has to study the entire text of every enclosing function to figure out where a non-local might get resolved. The pain is much less in Pascal/Ada/whatever, because in those you only have to look "up", and only at declaration statements. security-thru-obscurity-ly y'rs - tim Tim Peters tim@ksr.com not speaking for Kendall Square Research Corp
http://www.python.org/search/hypermail/python-1994q1/0318.html
CC-MAIN-2013-48
refinedweb
601
61.26
#include <CGAL/Interval_nt.h> The class Interval_nt provides an interval arithmetic number type. This behavior of your program depending on these errors. You can find more theoretical information on this topic in [1]. Interval arithmetic is a large concept and we will only consider here a simple arithmetic based on intervals whose bounds are doubles. So each variable is an interval representing any value inside the interval. All arithmetic operations (+, -, \( *\), \( /\), \( \sqrt{}\), square(), min(), max() and abs()) on intervals preserve the inclusion. This property can be expressed by the following formula ( \( x\) and \( y\) are real, \( X\) and \( Y\) are intervals, \( \mathcal{OP}\) is an arithmetic operation): \[ \forall\ x \in X, \forall\ y \in Y, (x\ \mathcal{OP}\ y) \in (X\ \mathcal{OP}\ Y) \] For example, if the final result of a sequence of arithmetic operations is an interval that does not contain zero, then you can safely determine its sign. Parameters The template parameter Protected is a Boolean parameter, which defaults to true. It provides a way to select faster computations by avoiding rounding mode switches, at the expense of more care to be taken by the user (see below). The default value, true, is the safe way, and takes care of proper rounding mode changes. When specifying false, the user has to take care about setting the rounding mode towards plus infinity before doing any computations with the interval class. He can do so using the Protect_FPU_rounding class for example. Example Protecting an area of code that uses operations on the class Interval_nt_advanced can be done in the following way: The basic idea is to use the directed rounding modes specified by the IEEE 754 standard, which are implemented by almost all processors nowadays. It states that you have the possibility, concerning the basic floating point operations ( \( +,-,*,/,\sqrt{}\)) to specify the rounding mode of each operation instead of using the default, which is set to 'round to the nearest'. This feature allows us to compute easily on intervals. For example, to add the two intervals [a.i;a.s] and [b.i;b.s], compute \( c.i=a.i+b.i\) rounded towards minus infinity, and \( c.s=a.s+b: CGAL_IA_NO_X86_OVER_UNDER_FLOW_PROTECT. Other platforms are not affected by this flag. CGAL_IA_DONT_STOP_CONSTANT_PROPAGATION. The type used by the following functions to deal with rounding modes. This is usually an int. A type whose default constructor and destructor allow to protect a block of code from FPU rounding modes necessary for the computations with Interval_nt<false>. It does nothing for Interval_nt<true>. It is implemented as Protect_FPU_rounding<!Protected>.
https://doc.cgal.org/4.7/Number_types/classCGAL_1_1Interval__nt.html
CC-MAIN-2019-30
refinedweb
426
55.13
Chapter 1. Your Toolkit This chapter shows you how to install the Android software development kit (SDK) and all the related software you’re likely to need. By the end, you’ll be able to run a simple “Hello World” program on an emulator. Windows, Mac OS X, and Linux systems Android information on using other IDEs is provided in the Android documentation at. enables Caution If this command reports that the JDK package is not available, you may need to enable the “partner” repositories using the Synaptic Package Manager utility in the System→Administration menu. The “partner” repositories are listed on the Other Software tab after you choose Settings Caution (ADT) plug-in to your Eclipse installation. The System Requirements article on the Android Developers site lists three choices of Eclipse packages as a basis for an Eclipse installation for Android software development: Any of these will work, though unless you are also developing Eclipse plug-ins, choosing. Caution We really mean it about installing Eclipse in your home folder (or another installation, because most of the time, your distribution’s repositories will have older versions of Eclipse. To confirm that Eclipse is correctly installed and that you have a JRE that supports Eclipse, launch the executable file in the Eclipse folder. You may want to make a shortcut downloading. Warning possibly- with the full path to your Android SDK install): ARCH Command The screenshot in Figure 1-2 shows the SDK and AVD Manager, with all the available SDK versions selected for installation. Android emulator, connect to debugging services on the emulator, edit Android XML files, edit and compile Android Interface Definition Language (AIDL) files, create Android application packages (.apk files), and perform other Android-specific tasks.). Note More information on installing the ADT plug-in using the Install New Software Wizard can be found on the Android Developers site, at. Eclipse documentation on this wizard can be found on the Eclipse documentation site, at.. Note Figure 1-5. Click Apply. Note that the build targets you installed, as described in Adding Build Targets to the SDK, are listed here as well. Android project, you tell Eclipse that the ADT plug-in and other Android tools are going to be used in conjunction with this project. Note Reference information and detailed online instructions for creating an Android project can be found at. Start your new project with the File→New→Android Project menu command. Locate the Android Project option in the New Project dialog (it should be under a section named Android). Click Next, and the New Project dialog appears as shown in Figure, platform (Android OS version number), and API level as the target for which your application is built. The platform and API level are the most important parameters here: they govern the Android platform library that your application will be compiled packages in your application, and must also uniquely identify your whole Android application among all other installed applications. It consists of a unique domain name—the application publisher’s domain name—plus a name specific to the application. Not all package namespaces are unique in Java, but the conventions used for Android applications make namespace conflicts less likely. In our example we used com.oreilly.testapp, but you can put something appropriate for your domainattribute in the application’s manifest, which is a file that stores application attributes. See The Android Manifest Editor.. If you expand the view of the project hierarchy by clicking the “+” (Windows) or triangle documentation on the emulator is found here:. memory indicating, displaying both the Android device you have connected and the AVD. Select the device, and the Android application will be loaded and run on the device. Troubleshooting SDK Problems: No Build Targets If you are unable to make a new project or import an example project from the SDK, you may have missed installing build targets into your SDK. Reread the instructions in Adding Build Targets to the SDK components interface or through an interface embedded in Eclipse via the ADT plug-in. When you invoke the DDMS from the command line, you will see something similar to the window shown in Figure 1-12. information filesystem explorer, accessible through the “File explorer” menu item in the Devices menu. It displays the file hierarchy in a window similar to the one shown in Figure 1-13. - specialized editors that are opened when you open these files. Building Android apps Eclipse projects are usually built automatically. That means you will normally not encounter interchangeable emulation in ways unsupported by the SDK tools, or you may be curious about the capabilities and limitations of QEMU. Luckily, QEMU has a large and vibrant developer and user community, which you can find at. development projects, there are several other tools in the SDK, and those that are used or invoked directly by developers are described here. Still more components of the SDK are listed in the Tools Overview article in the Android documentation found at. Hierarchy Viewer The Hierarchy Viewer displays and enables analysis of the view hierarchy of the current activity of a selected Android device. This enables you to see and diagnose problems with your view hierarchies as your application is running, or to examine the view hierarchies of other applications to see how they are designed. It also lets you examine a magnified view of the screen with alignment guides that help identify problems with layouts. Detailed information on the Hierarchy Viewer is available at. Layoutopt Layoutopt is a static analyzer that operates on XML layout files and can diagnose some problems with Android layouts. Detailed information on Layoutopt is available at. Android introduce sqlite3 in Example Database Manipulation Using sqlite3. keytool keytool generates encryption keys, and is used by the ADT plug-in to create temporary debug keys with which it signs code for the purpose of debugging. In most cases, you will use this tool to create a signing certificate for releasing your applications, as described in Creating a self-signed certificate. Zipalign Zipalign enables optimized access to data for production releases of Android applications. This optimization must be performed after an application is signed for release, because the signature affects byte alignment. Detailed information on Zipalign is available at. Draw9patch A 9 patch is a special kind of Android resource, composed of nine images, and useful when you want, for example, buttons that can grow larger without changing the radius of their corners. Draw9patch is a specialized drawing program for creating and previewing these types of resources. Details on draw9patch are available at. android The command named android can be used to invoke the SDK and AVD Manager from the command line, as we described in the SDK installation instructions in The Android SDK.. Usually, you will want to install all available updates.. Normally, you will want to use the Select All button to install all available updates. The updates you see listed on your system depend on what Eclipse modules you have installed distribution installation,. Caution examples to code you engineer to create high-quality products. Get Programming Android now with O’Reilly online learning. O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.
https://www.oreilly.com/library/view/programming-android/9781449309473/ch01.html
CC-MAIN-2022-05
refinedweb
1,207
52.49
. A new look for diagnostics By way of example, let’s look at how GCC 8 reports an attempt to use a missing binary “+” in C++: $ gcc-8 t.cc t.cc: In function ‘int test(const shape&, const shape&)’: t.cc:15:4: error: no match for ‘operator+’ (operand types are ‘boxed_value<double>’ and ‘boxed_value<double>’) return (width(s1) * height(s1) ~~~~~~~~~~~~~~~~~~~~~~ + width(s2) * height(s2)); ^~~~~~~~~~~~~~~~~~~~~~~~ Here’s what it looks like in GCC 9: $ gcc-9 t.cc t.cc: In function ‘int test(const shape&, const shape&)’: t.cc:15:4: error: no match for ‘operator+’ (operand types are ‘boxed_value<double>’ and ‘boxed_value<double>’) 14 | return (width(s1) * height(s1) | ~~~~~~~~~~~~~~~~~~~~~~ | | | boxed_value<[...]> 15 | + width(s2) * height(s2)); | ^ ~~~~~~~~~~~~~~~~~~~~~~ | | | boxed_value<[...]> There are a few changes here. I’ve added a left-hand margin, showing line numbers. The “error” line mentions line 15, but the expression in question spans multiple lines, and we’re actually starting with line 14. I think it’s worth a little extra horizontal space to make it clear which line is which. It also helps distinguish your source code from the annotations that GCC emits. I believe they also make it a little easier to see where each diagnostic starts, by visually breaking things up at the leftmost column. Speaking of annotations, this example shows another new GCC 9 feature: diagnostics can label regions of the source code to show pertinent information. Here, what’s most important are the types of the left-hand and right-hand sides of the “+” operator, so GCC highlights them inline. Notice how the diagnostic also uses color to distinguish the two operands from each other and the operator. The left margin affects how we print things like fix-it hints for missing header files: $ gcc-9 -xc++ -c incomplete.c incomplete.c:1:6: error: ‘string’ in namespace ‘std’ does not name a type 1 | std::string test(void) | ^~~~~~ incomplete.c:1:1: note: ‘std::string’ is defined in header ‘<string>’; did you forget to ‘#include <string>’? +++ |+#include <string> 1 | std::string test(void) I’ve turned on these changes by default; they can be disabled via -fno-diagnostics-show-line-numbers and -fno-diagnostics-show-labels, respectively. Another example can be seen in the type-mismatch error from the article I wrote last year, Usability improvements in GCC 8: extern int callee(int one, const char *two, float three); int caller(int first, int second, float third) { return callee(first, second, third); } where the bogus type of the expression is now highlighted inline: $ gcc-9 -c param-type-mismatch.c param-type-mismatch.c: In function ‘caller’: param-type-mismatch.c:5:24: warning: passing argument 2 of ‘callee’ makes pointer from integer without a cast [-Wint-conversion] 5 | return callee(first, second, third); | ^~~~~~ | | | int param-type-mismatch.c:1:40: note: expected ‘const char *’ but argument is of type ‘int’ 1 | extern int callee(int one, const char *two, float three); | ~~~~~~~~~~~~^~~ Yet another example can be seen in this bad printf call: $ g++-9 -c bad-printf.cc -Wall bad-printf.cc: In function ‘void print_field(const char*, float, long int, long int)’: bad-printf.cc:6:17: warning: field width specifier ‘*’ expects argument of type ‘int’, but argument 3 has type ‘long int’ [-Wformat=] 6 | printf ("%s: %*ld ", fieldname, column - width, value); | ~^~~ ~~~~~~~~~~~~~~ | | | | int long int bad-printf.cc:6:19: warning: format ‘%ld’ expects argument of type ‘long int’, but argument 4 has type ‘double’ [-Wformat=] 6 | printf ("%s: %*ld ", fieldname, column - width, value); | ~~~^ ~~~~~ | | | | long int double | %*f which contrasts “inline” the type expected by the format string versus what was passed in. (Embarrassingly, we didn’t properly highlight format string locations in older versions of the C++ front end; for GCC 9, I’ve implemented this so it has parity with that of the C front end, as shown here). Not just for humans One concern I’ve heard when changing how GCC prints diagnostics is that it might break someone’s script for parsing GCC output. I don’t think these changes will do that: most such scripts are set up to parse the "FILENAME:LINE:COL: error: MESSAGE" lines and ignore the rest, and I’m not touching that part of the output. But it made me think it was about time we had a machine-readable output format for diagnostics, so for GCC 9, I’ve added a JSON output format: -fdiagnostics-format=json. Consider this warning: $ gcc-9 -c cve-2014-1266.c -Wall cve-2014-1266.c: In function ‘SSLVerifySignedServerKeyExchange’: cve-2014-1266.c:629:2: warning: this ‘if’ clause does not guard... [-Wmisleading-indentation] 629 | if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0) | ^~ cve-2014-1266.c:631:3: note: ...this statement, but the latter is misleadingly indented as if it were guarded by the ‘if’ 631 | goto fail; | ^~~~ With -fdiagnostics-format=json, the diagnostics are emitted as a big blob of JSON to stderr. Running them through the handy python -m json.tool to format them gives an idea of the structure: $ (gcc-9 -c cve-2014-1266.c -Wall -fdiagnostics-format=json 2>&1) | python -m json.tool | pygmentize -l json [ { "children": [ { "kind": "note", "locations": [ { "caret": { "column": 3, "file": "cve-2014-1266.c", "line": 631 }, "finish": { "column": 6, "file": "cve-2014-1266.c", "line": 631 } } ], "message": "...this statement, but the latter is misleadingly indented as if it were guarded by the \u2018if\u2019" } ], "kind": "warning", "locations": [ { "caret": { "column": 2, "file": "cve-2014-1266.c", "line": 629 }, "finish": { "column": 3, "file": "cve-2014-1266.c", "line": 629 } } ], "message": "this \u2018if\u2019 clause does not guard...", "option": "-Wmisleading-indentation" } ] In particular, the supplementary “note” is nested within the “warning” at the JSON level, allowing, for example, IDEs to group them. Some of our C++ diagnostics can have numerous child diagnostics giving additional detail, so being able to group them, for example, via a disclosure widget, could be helpful. Simpler C++ errors C++ is a complicated language. For example, the rules for figuring out which C++ function is to be invoked at a call site are non-trivial. The compiler could need to consider several functions at a given call site, reject all of them for different reasons, and g++‘s error messages have to cope with this generality, explaining why each was rejected. This generality can make simple cases harder to read than they could be, so for GCC 9, I’ve added special-casing to simplify some g++ errors for common cases where there’s just one candidate function. For example, GCC 8 could emit this: $ g++-8 param-type-mismatch.cc param-type-mismatch.cc: In function ‘int test(int, const char*, float)’: param-type-mismatch.cc:8:45: error: no matching function for call to ‘foo::member_1(int&, const char*&, float&)’ return foo::member_1 (first, second, third); ^ param-type-mismatch.cc:3:14: note: candidate: ‘static int foo::member_1(int, const char**, float)’ static int member_1 (int one, const char **two, float three); ^~~~~~~~ param-type-mismatch.cc:3:14: note: no known conversion for argument 2 from ‘const char*’ to ‘const char**’ For GCC 9, I’ve special-cased this, giving a more direct error message, which highlights both the problematic argument and the parameter that it can’t be converted to: $ g++-9 param-type-mismatch.cc param-type-mismatch.cc: In function ‘int test(int, const char*, float)’: param-type-mismatch.cc:8:32: error: cannot convert ‘const char*’ to ‘const char**’ 8 | return foo::member_1 (first, second, third); | ^~~~~~ | | | const char* param-type-mismatch.cc:3:46: note: initializing argument 2 of ‘static int foo::member_1(int, const char**, float)’ 3 | static int member_1 (int one, const char **two, float three); | ~~~~~~~~~~~~~^~~ Similarly, GCC 8 took two messages to offer suggestions for various kinds of misspelled names: $ g++-8 typo.cc typo.cc:5:13: error: ‘BUFSIZE’ was not declared in this scope uint8_t buf[BUFSIZE]; ^~~~~~~ typo.cc:5:13: note: suggested alternative: ‘BUF_SIZE’ uint8_t buf[BUFSIZE]; ^~~~~~~ BUF_SIZE so for GCC 9, I’ve consolidated the messages: $ g++-9 typo.cc typo.cc:5:13: error: ‘BUFSIZE’ was not declared in this scope; did you mean ‘BUF_SIZE’? 5 | uint8_t buf[BUFSIZE]; | ^~~~~~~ | BUF_SIZE In some cases, where GCC 8 knew to offer suggestions within namespaces: $ g++-8 typo-2.cc typo-2.cc: In function ‘void mesh_to_strip()’: typo-2.cc:8:3: error: ‘tri_strip’ was not declared in this scope tri_strip result; ^~~~~~~~~ typo-2.cc:8:3: note: suggested alternative: typo-2.cc:2:9: note: ‘engine::tri_strip’ class tri_strip { ^~~~~~~~~ GCC 9 can now offer fix-it hints: $ g++-9 typo-2.cc typo-2.cc: In function ‘void mesh_to_strip()’: typo-2.cc:8:3: error: ‘tri_strip’ was not declared in this scope; did you mean ‘engine::tri_strip’? 8 | tri_strip result; | ^~~~~~~~~ | engine::tri_strip typo-2.cc:2:9: note: ‘engine::tri_strip’ declared here 2 | class tri_strip { | ^~~~~~~~~ Location, location, location A long-standing issue within GCC’s internal representation is that not every node within the syntax tree has a source location. For GCC 8, I added a way to ensure that every argument at a C++ call site has a source location. For GCC 9, I’ve extended this work so that many more places in the C++ syntax tree now retain location information for longer. This really helps when tracking down bad initializations. GCC 8 and earlier might unhelpfully emit errors on the final closing parenthesis or brace, for example: $ g++-8 bad-inits.cc bad-inits.cc:12:1: error: cannot convert ‘json’ to ‘int’ in initialization }; ^ bad-inits.cc:14:47: error: initializer-string for array of chars is too long [-fpermissive] char buffers[3][5] = { "red", "green", "blue" }; ^ bad-inits.cc: In constructor ‘X::X()’: bad-inits.cc:17:35: error: invalid conversion from ‘int’ to ‘void*’ [-fpermissive] X() : one(42), two(42), three(42) ^ whereas now, GCC 9 can highlight exactly where the various problems are: $ g++-9 bad-inits.cc bad-inits.cc:10:14: error: cannot convert ‘json’ to ‘int’ in initialization 10 | { 3, json::object }, | ~~~~~~^~~~~~ | | | json bad-inits.cc:14:31: error: initializer-string for array of chars is too long [-fpermissive] 14 | char buffers[3][5] = { "red", "green", "blue" }; | ^~~~~~~ bad-inits.cc: In constructor ‘X::X()’: bad-inits.cc:17:13: error: invalid conversion from ‘int’ to ‘void*’ [-fpermissive] 17 | X() : one(42), two(42), three(42) | ^~ | | | int What is the optimizer doing? GCC can automatically “vectorize” loops, reorganizing them to work on multiple iterations at once, to take advantage of the vector units on your CPU. However, it can do this only for some loops; if you stray from the path, GCC will have to use scalar code instead. Unfortunately, historically it hasn’t been easy to get a sense from GCC about the decisions it’s making as it’s optimizing your code. We have an option, -fopt-info, that emits optimization information, but it’s been more of a tool for the developers of GCC itself, rather than something aimed at end users. For example, consider this (contrived) example: #define N 1024 void test (int *p, int *q) { int i; for (i = 0; i < N; i++) { p[i] = q[i]; asm volatile ("" ::: "memory"); } } I tried compiling it with GCC 8 with -O3 -fopt-info-all-vec, but it wasn’t very enlightening: $ gcc-8 -c v.c -O3 -fopt-info-all-vec Analyzing loop at v.c:7 v.c:7:3: note: ===== analyze_loop_nest ===== v.c:7:3: note: === vect_analyze_loop_form === v.c:7:3: note: === get_loop_niters === v.c:7:3: note: not vectorized: loop contains function calls or data references that cannot be analyzed v.c:3:6: note: vectorized 0 loops in function. v.c:3:6: note: ===vect_slp_analyze_bb=== v.c:3:6: note: ===vect_slp_analyze_bb=== v.c:10:7: note: === vect_analyze_data_refs === v.c:10:7: note: got vectype for stmt: _5 = *_3; vector(4) int v.c:10:7: note: got vectype for stmt: *_4 = _5; vector(4) int v.c:10:7: note: === vect_analyze_data_ref_accesses === v.c:10:7: note: not consecutive access _5 = *_3; v.c:10:7: note: not consecutive access *_4 = _5; v.c:10:7: note: not vectorized: no grouped stores in basic block. v.c:7:3: note: === vect_analyze_data_refs === v.c:7:3: note: not vectorized: not enough data-refs in basic block. v.c:7:3: note: ===vect_slp_analyze_bb=== v.c:7:3: note: ===vect_slp_analyze_bb=== v.c:12:1: note: === vect_analyze_data_refs === v.c:12:1: note: not vectorized: not enough data-refs in basic block. For GCC 9, I’ve reorganized problem-tracking within the vectorizer so that the output is of the form: [LOOP-LOCATION]: couldn't vectorize this loop [PROBLEM-LOCATION]: because of [REASON] For the example above, this gives the following, identifying the location of the construct within the loop that the vectorizer couldn’t handle. (I hoped to have it also show the source code, but that didn’t make feature freeze): $ gcc-9 -c v.c -O3 -fopt-info-all-vec v.c:7:3: missed: couldn't vectorize loop v.c:10:7: missed: statement clobbers memory: __asm__ __volatile__("" : : : "memory"); v.c:3:6: note: vectorized 0 loops in function. v.c:10:7: missed: statement clobbers memory: __asm__ __volatile__("" : : : "memory"); This improves things, but still has some limitations, so for GCC 9 I’ve also added a new option to emit machine-readable optimization information: -fsave-optimization-record. This writes out a SRCFILE.opt-record.json.gz file with much richer data: for example, every message is tagged with profile information (if available), so that you can look at the “hottest” part of the code, and it captures inlining information, so that if a function has been inlined into several places, you can see how each instance of the function has been optimized. Other improvements GCC can emit “fix-it hints” that suggest how to fix a problem in your code. These can be automatically applied by an IDE. For GCC 9, I’ve added various new fix-it hints. There are now fix-it hints for forgetting the return *this; needed by various C++ operators: $ g++-9 -c operator.cc operator.cc: In member function ‘boxed_ptr& boxed_ptr::operator=(const boxed_ptr&)’: operator.cc:7:3: warning: no return statement in function returning non-void [-Wreturn-type] 6 | m_ptr = other.m_ptr; +++ |+ return *this; 7 | } | ^ and for when the compiler needs a typename: $ g++-9 -c template.cc template.cc:3:3: error: need ‘typename’ before ‘Traits::type’ because ‘Traits’ is a dependent scope 3 | Traits::type type; | ^~~~~~ | typename and when you try to use an accessor member as if it were a data member: $ g++-9 -c fncall.cc fncall.cc: In function ‘void hangman(const mystring&)’: fncall.cc:12:11: error: invalid use of member function ‘int mystring::get_length() const’ (did you forget the ‘()’ ?) 12 | if (str.get_length > 0) | ~~~~^~~~~~~~~~ | () and for C++11’s scoped enums: $ g++-9 -c enums.cc enums.cc: In function ‘void json::test(const json::value&)’: enums.cc:12:26: error: ‘STRING’ was not declared in this scope; did you mean ‘json::kind::STRING’? 12 | if (v.get_kind () == STRING) | ^~~~~~ | json::kind::STRING enums.cc:3:44: note: ‘json::kind::STRING’ declared here 3 | enum class kind { OBJECT, ARRAY, NUMBER, STRING, TRUE, FALSE, NULL_ }; | ^~~~~~ And I added a tweak to integrate the suggestions about misspelled members with that for accessors: $ g++-9 -c accessor-fixit.cc accessor-fixit.cc: In function ‘int test(t*)’: accessor-fixit.cc:17:15: error: ‘class t’ has no member named ‘ratio’; did you mean ‘int t::m_ratio’? (accessible via ‘int t::get_ratio() const’) 17 | return ptr->ratio; | ^~~~~ | get_ratio() I’ve also tweaked the suggestions code so it considers transposed letters, so it should do a better job of figuring out misspellings. Looking to the future The above covers some of the changes I’ve made for GCC 9. Perhaps a deeper change is that we now have a set of user experience guidelines for GCC, to try to keep a focus on the programmer’s experience as we implement new diagnostics. If you’d like to get involved in GCC development, please join us on the GCC mailing list. Hacking on diagnostics is a great way to get started. Trying it out GCC 9 will be in Fedora 30, which should be out in a few weeks. For simple code examples, you can play around with the new GCC at (select GCC “trunk”). Have fun! See Also If you are using GCC 8 on Red Hat Enterprise Linux 6, 7, or 8 Beta, some articles that might be of interest:
https://developers.redhat.com/blog/2019/03/08/usability-improvements-in-gcc-9/
CC-MAIN-2019-13
refinedweb
2,766
55.74
Increment and Save This is a script that you can add to the Actions menu to duplicate the current script and add a number to it (or if it's numbered already, add one). I wanted a quick way to keep multiple iterations of a script. I just started learning Python last week, so I'm sure I could do things differently (let me know!), but it seems to working for my purposes and I didn't see anything similar already on here.. Thanks briarfox, I'll check out StaSh. I noticed my script wouldn't increment correctly if a file ending in a higher number already existed. For example, if I've got the files a1, a2, a3 and use the script on a2, it would give me "a3 1". I've attempted to fix this and it seems to be working but the code is not at all elegant. Any tips on easier ways to do this? Again, I'm really new to this so sorry for the crazy code! I don't really know what I'm doing. I also noticed it doesn't work in folders, but that's for another day. Here's the code: import os, sys, editor, re filepath = editor.get_path() filename = os.path.basename(filepath) ext1 = os.path.splitext(filepath) noext = filename[:-len(ext1)-1] noextnonum = re.split('([0-9]+)$',noext)[0] namelen = len(noextnonum) #filepath stuff path = os.path.dirname(filepath) #editor.reload_files() files = os.listdir(path) text = editor.get_text() if not text: sys.exit('No text in the Editor.') alist = [] x = 0 while x<=len(files)-1: if noextnonum == files[x][:namelen]: ext = os.path.splitext(files[x])[1] noext = files[x][:-len(ext)] try: num = re.split('([0-9]+)$',noext)[1] alist.append(int(num)) filename = noextnonum + str(max(alist)+1) + ext except: filename = noextnonum + str(1) + ext x = x + 1 editor.make_new_file(filename, text)) Oh thank you - this is perfect! I knew there had to be an easier way than looping every file. It's just my personal preference to have the numbered files. There's an "increment and save" function in Adobe After Effects that I use for my job and I just wanted to replicate that. And on my phone the I can't really read the long timestamps.
https://forum.omz-software.com/topic/1821/increment-and-save
CC-MAIN-2018-30
refinedweb
383
68.87
Yes. Ok so I might be overblowing things slightly, but stop and think for a moment… Mark Miller built a plugin that allowed him to interface a wireless guitar controller, with Visual studio. Using this plugin, CodeRush and his guitar instead of a keyboard, he was able to code faster than most people could with a keyboard and vanilla VS. Come on… That is Awesome! Oh yeah .. And don’t get me started about his next scheme. Anyway… all that out of the way… What *is* a plugin good for? Well that’s an interesting question. Well let’s put it this way…. CodeRush == DXCore + Plugins Ok sure but what does that mean? It means that CodeRush is technically nothing more than a bunch of plugins built on top of the services of the DXCore. This in turn means that the DXCore provides everything you need to start building plugins as powerful as the features in CodeRush. So why is writing a plugin using the DXCore easier than writing it without. Ok, let’s have a look at the benefits of the DXCore: Managed Code The DXCore removes the need for programming against COM Interfaces for the vast majority of plugin code, without removing your access to that facility in case you should need it. Ask anyone (Oh ok … any semi-respectable programmer) … “All other things being equal, would you prefer to write against COM or against a managed library?”. If you find someone who votes for COM, you have found a <Insert polite term here>*. *Note: I did asked my followers on twitter, what a polite term for such a person would be. Answers included ‘a lunatic’, ‘grandpa’, ‘old’, ‘sadist’ and my personal favourite ‘There is no appropriate polite term for such a guy’. Get straight to the point. When you code add-ins with the DXCore, it can be a simple matter of dropping a component on a design surface setting a couple of properties (typically for sensible naming and such), and then handling one or more events. You don’t have to mess around with registering your plugin with anything. There’s no shimming to create tool-windows, and you don’t have to perform multiple casts on everything, just to get access to properties that you should have been able to see all along. The DXCore lets you just get on with creating your plugin. It worries about the glue so you don’t have to. Support all the way back to VS2005 Just like it says on the tin. The DXCore can provide you with all sorts of contextual information and understands many different versions of each of the languages that are supported. This means that you can easily write a single version of a plugin, and have it support the last 3 versions of studio (VS2010, VS2008 and VS2005) without needing to recode or recompile. Your plugin can be installed in a single location on a machine which has all 3 of these IDE’s installed, and it will function quite happily in all of them. This does not mean that it has to function exactly the same in all 3. If you like you can ask the DXCore which version you’re operating under, and you can alter your plugin’s behaviour accordingly. So it’s not something you need to worry about, but if you want this sort of info, it’s available on tap for you to do with what you will. Deep Language Parsing The DXCore parses everything. I’m serious I really mean every part of your source. I remember trying to write CodeGen code before finding out about the DXCore. It was a black art at best, and worse there wasn’t much support for anything more detailed than a method declaration. The DXCore parses everything into an abstract syntax tree (AST) of objects which is completely language independent. Everything from the source files, through namespaces and types (Classes Structs and Interfaces) then on into fields, methods, properties, accessors … statements, branches, loops … expressions, primitives. Like I said… everything. Cross Language Plugins Given my previous point about how well parsed your code is, and that the result is an AST which is decoupled from your code, it should come as no surprise really, that this means a DXCore Plugin is able to perform it’s task needing little-to-no knowledge of the language within which it is operating. That’s right. you can write a single plugin which can work just as well with C#, VB.Net or even JavaScript. All these languages are parsed into the same objects within the AST, and can be analysed to produce information based upon this abstract nature. For example the ‘maintenance complexity’ metric feature of CodeRush works with all 3 languages, because what it’s analysing is loops, conditionals, declarations and the like. The feature itself has no real knowledge of any of these languages, because it doesn’t need to. The DXCore has been parsed out all of the language specifics and their nuances into an AST. All that’s left to do is analyse the AST and produce a result, which is exactly what the ‘Maintenance Complexity’ metric does. Likewise if you construct an AST of your own, adding classes, members, statements etc, it can be then emitted into any of these languages with a single function call. Allowing you to create Refactorings and CodeProviders that work across multiple languages without additional coding or even fully understanding the syntax of those languages. Rapid Plugin Prototyping Coding against the DXCore is quick. I’ve lost track of the number of times that I’ve said to myself "I wish that studio could do X” or “The lack of Y really annoys me” or “Wouldn’t it be great if…” Starting from a raw “Standard Plugin” project you literally drop a component on the design surface (if that’s the way you prefer), fill out a couple of properties and then handle one or more events to provide the specific functionality you’re after. You can have a workable prototype plugin in seconds, and a fully working version in minutes. If you add to this, the ability to change the code of your plugin on the fly whilst it’s still running inside Visual Studio (Edit and Continue**) and you’ve got a very flexible way to build plugins to do all sorts of crazy things. I’ll be showing you in subsequent posts, how individual types of plugins are created, and I’ll provide you example code for achieving all sorts of cool stuff. (**‘Edit and Continue’ really is teh awesome. Except if you’re coding in C# and like to use Lambdas, but hey nobody is perfect.) Summary What it boils down to is this: Visual Studio is not perfect. The guys on the IDE team at MS are great. No really they are… Look at what they have achieved. It really is awesome… but they simply cannot ship features as fast as we come up with requirements. The DXCore gives you the ability to take matters into your own hands. Imagine for a moment, all of your accumulated skill from all those years of programming that you’ve done. Wouldn’t it be nice if you could use some of that, to enhance your own day to day life, rather than always directly in service of your customers. I’m not suggesting the you should ignore your customers, but if your own programming life can be made smoother, then the benefits of this are passed on to your customers anyway through your increased productivity. The DXCore gives you back the power to do just this. So stick with me here, as I guide you through the process of building some plugins of your very own. If you happen to prefer different keys to the CodeRush defaults, or if you’ve downloaded a third party plugin which needs some keys configuring, then at some point you’re going to want to visit the shortcuts page of the options screen. Once you launch the options screen (DevExpress\Options or CTRL+SHIFT+ALT+O), you can locate the shortcuts page in the tree on the left at IDE\Shortcuts. At this point you should see something like the following: (Note:The page tree has been collapsed to allow extra space for the other features of this page.) The tree on the left shows a hierarchical view of all of the shortcut keys recognised by CodeRush at the current time. Above the tree are several icons allowing you to: Here are some steps to guide you through the creation of CodeRush shortcuts. Create a Custom Folder Before creating any new shortcuts, create a new folder called “Custom”. Use this folder (or one beneath it) as the location in which any new shortcuts are created. This has the benefit of collecting all of your custom shortcuts in a single location which makes sharing or moving them to another machine much easier. Note: The on-disk representation of your shortcut settings can be found at: ‘%AppData%\CodeRush for VS.Net\1.1\Settings.xml\IDE\Shortcuts’ Choose your Shortcut Most of the time you’ll want to invoke your functionality via a keyboard shortcut of some kind. However you’ll want to give some thought to which key combination to use. To specify a key combo, simply place your caret in the ‘Key 1’ box, and press the keys in the combination you’re after. If your shortcut is intended to be the first part of a chord (ie 2 key combos one after the other), you should enter the 2nd part of this chord in the ‘Key 2’ box. If either if these combos require any special keys ({Tab}, {Backspace}, {Delete}, {Esc} etc), these can be entered by using the right-click context menu of these boxes. As stated before, you can use the “Hide Shortcut Folders” to help determine if there might be a conflict with an existing piece of CodeRush feature. If this turns out to be the case, you might solve this by allocating differing contexts to each of the conflicting shortcuts. (See contexts – below) Command Next up you’ll have to choose the command that you want your shortcut to execute. Command refers to either a CodeRush Action or a Visual Studio command. CodeRush Actions are listed within the dropdown element of the command box. In the case of an Action, there might be some parameters you wish to pass to the Action. These may be passed via the Parameters box and should be comma separated if present. Note: It’s worth bearing in mind that CodeRush Shortcuts are processed before those of Visual Studio, and only passed on to studio, if not handled by CodeRush (unless otherwise expressly specified). If you find a case where you need to pass these on to Studio afterward, just check the tick box underneath the parameters box. Context Finally you should setup the context in which you wish your Shortcut to operate. Context is one of the key parts of the DXCore. It allows you to indicate that certain operations are only valid under particular circumstances. This means that you can allocate the same shortcut to 2 or more completely different operations by supplying them with different contexts (prerequisites). If these contexts are mutually exclusive, then there can be no confusion about which action you meant to invoke. If you are assigning behaviour to a keystroke that is only appropriate when Studio is focused on the Code Editor, then you should indicate this in it’s context. Otherwise you might find that your functionality is also triggered from within a Find Dialog or similar. Most of the time this is not what you want. So in order to create your shortcut, you need only specify the key combination, command name and context. You may also edit these portions of any existing shortcuts. Once you are happy with your shortcuts, simply click the ‘Apply’ or ‘Ok’ buttons, and you should find that your shortcut is immediately available. CodeRush Shortcuts, like their Template counterparts, are very powerful due to the Context provided by the DXCore on which they are both built. This enables the same key combination to be interpreted differently depending on the current situation. This post has demonstrated how to create or edit a shortcut, the key parts of a each and what they mean. You should now have everything you need to reassign any keys you like, as well as adding additional bindings for any third party plugins that you might download..
https://community.devexpress.com/blogs/rorybecker/archive/2010/10.aspx
CC-MAIN-2017-43
refinedweb
2,111
67.79
The easiest way I found to go about this is to first set some permanent environment variables in your Windows environment. This can be done through a GUI in Windows, or via the cmd console. The console commands to set the necessary variables are: setx Path "%Path%;C:\Program Files\SageMath 8.1\runtime\opt\sagemath-8.1\local\lib;C:\Program Files\SageMath 8.1\runtime\opt\sagemath-8.1\local\bin;C:\Program Files\SageMath 8.1\runtime\bin;C:\Program Files\SageMath 8.1\runtime\lib\lapack" setx SAGE_ROOT /opt/sagemath-8.1 setx SAGE_LOCAL /opt/sagemath-8.1/local setx DOT_SAGE /dot_sage There are likely some others that should be set as well, but that was the bare minimum I found necessary to get Sage's Python interpreter working happily in PyCharm. Then we need to correctly add Sage's Python interpreter to PyCharm's list of available interpreters. From the Welcome screen click on the little "Configure" gear and select "Settings" from the menu: In the settings page select "Project Intepreter"--this is where you can add additional interpreters for use across projects. You might have something different shown here for an already existing interpreter. Click the little gear icon in the top-right corner next to the drop-down list of available interpreters, and select "Add Local" from the menu. Then from the list of interpreter types, select "System Interpreter": Browse to the python2.7.exe executable under C:\Program Files\SageMath 8.1\runtime\opt\sagemath-8.1\local\bin (or you can just copy this path directly into the file browser): If you set up the correct environment variables, PyCharm should be able to successfully execute Sage's Python interpreter, and also populate the list of packages installed for that interpreter, and you'll see something like this: If you didn't set the Path environment variable correctly, then you'll get an error here (it might show "Permission error" or something like that). This is because Windows uses the Path environment variable to search for DLLs, and the correct paths need to be added in order to find the Cygwin DLL, among others. Otherwise the interpreter executable can't even start. If this does happen you can still proceed with adding that interpreter, but it won't work until you set the necessary environment variables. Then when you start a new project, make sure to select the Sage Python as the default interpreter (you might be able to use it with a virtualenv as well but I haven't tried that--if you do make sure it inherits system site-packages, or else you don't get Sage, etc.) In general I don't think it's necessary: Finally, PyCharm also allows you to set environment variables to run the interpreter with on a per-project basis in a couple differentl places. You can configure environment variables in the "Run" configurations, and then again (separately, unfortunately) in the settings for the Console. This is actually what I did initially--I set Path, as well as SAGE_ROOT etc. just in PyCharm and that worked as well. But I found it simpler to just set the environment variables permanently in my environment. Then things "just worked". Be aware that this is still just the normal Python interpreter, not the Sage interpreter, so it doesn't know how to run .sage files, nor is it aware of Sage syntax. But you should be able to from sage.all import * and use Sage objects in plain Python. To get that all working might be a little bit tricky, and I think should be tackled as a separate question.
https://ask.sagemath.org/answers/40220/revisions/
CC-MAIN-2021-10
refinedweb
613
62.38
How to use Google Maps API with Flash AS3 I was playing with Google Maps API for Flash when I noticed the tutorials in the official page are somehow not that smart, so I am going to clarify some things. Follow these simple steps: Sign up for a Google Maps API Key at this link. Once you submit the form, ignore everything you see on the page (it refers to javascript version), just write down the key. Download the Google Maps API for Flash SDK at this link. Inside the archive you will find a lib directory with a file called map_1_8a.swc inside. The official Google docs refer to a map_1_7.swc file, so this file could be updated anytime. Just refer to the map_xxx.swf, no matter the version you are downloading. Install the API SWC component to your Flash creating a map_xxx.swf inside. The path to this folder varies from CS3 to CS4, it should be placed in \en\Configuration\Components if you are running CS3 (watch out the en, it may differ according to your language) and \Common\Configuration\Components if you are running CS4. Create a new Flash file and open the components window. You can find this window on Window -> Components menu. You should find a Google -> GoogleMapsLibrary compoent. Drag in on stage wherever you want (you will set its position later). Don’t worry about the size. Now it’s time to write the class. Here it is: Line 4: importing the Point class in order to use a point later. This is not explained in the official tutorial as it writes the code directly into the timeline. Lines 5-8: importing Google libraries Line 10: declaring the new map type Line 12: inserting the key API Line 13: setting the size of the map to fill the entire stage, using the Point class Line 14: listener for the map to be ready Line 15: adding the map itself Lines 16-18: once the map is ready, show us Venice! Here it is: If you give me good feedback, I’ll show you how to create custom controls and some more tricks. Download the source code. Get it now They can be easily customized to meet the unique requirements of your project. This post has 23 comments One Whoa, that’s awesome, thx for this information (too) songkhoon This is really cool. Last time I have use the component provide by afcomponents.com, can use some of the function in the google map. Daniel Rodriguez Like it, always a nice app for a site. alfonsofonso it works nice! is there any more fla files elsewhere, because i dont have flex… salut! alfonsofonso ah! my example: TJ Downes You forgot a couple of crucial steps: 19. Realize Google has no local search integration 20. Use Yahoo Maps instead :) What I am finding is that while each of the map APIs have pros and cons, Yahoo map seems to offer more in terms of functionality, unless you want to use them both in combination. Ive also found that Google maps tends to be more sluggish than Yahoo, but ymmv. Pamela Fox Thanks for this, alfonso. @TJ – You can integrate local search with Flash API via the Local Search API: How to use Yahoo Maps API with Flash AS3 : Emanuele Feronato [...] is quite the same tutorial as How to use Google Maps API with Flash AS3, but this time we’ll learn how to use Yahoo! [...] How to use Google Maps API with Flash AS3 - part 2 : Emanuele Feronato [...] How to use Google Maps API with Flash AS3 if you are new to Google Maps API for [...] Introduction: Flash Google Maps API and Multi-touch | Cyan[c] Design [...] I came across Emanuele Feronato’s website, italian geek and PROgrammer. She has a tutorial to get you started using the GoogleMaps API, so here is your first task in this [...] Alejandro Guillen do you know if you can use kml with google maps as3 Hendrik Awesome, thnx! weblog » Blog Archive » Googlemaps Flash API [...] [...] iamnotbored.com » Blog Archive » flash google maps [...] [...] Maverik0106 Hey this is great, Thanks a lot for the awesome work here, I was just wondering, this works if you put the script inside the flash file, but you’re showing us the package which means its coming from an actionscript file, so my question is, how do you call it from within flash??? I know you have to go googlemap(); but it asks you for an argument inside the function caller. So my question is, what would the argument be inside the function caller? thanks in advance for your help! Pavan How can i use to get reviews and ratings in flash?? Introduction: Flash Google Maps API and Multi-touch « Kelso’s Corner [...] I came across Emanuele Feronato’s website, Italian geek and PROgrammer. He has a tutorial to get you started using the GoogleMaps API, so here is your first task in this [...] roughbern I am new to the google map api for flash. I found your example helpful to understand more about how they work. I was wondering what the line 9 public class googlemap extends Sprite { did for the map and how you would add a marker for a business for example? Jimmy Hey thanks for the good example, was really helpful. The Google tutorial was rubbish! Ciao! Mark thax alot .. it is amazing .. i was looking for this .. if u can just tell us how to make the custom control buttons.!!! thx again .. Google maps application with actionscript 3 for android ( AIR ) | Moe Zainal [...] google maps api for flash ( Emanuele Feronato tutorial [...] mnu7 I use the same code, and for key I use localhost as I want to run it on my PC. Resultant key I put in my AS3 code but still get error. What else changes to make Flash Game Development Inter-web mash up: Dec 1, 2008 « 8bitrocket.com [...] To Use Google Maps and AS3Emanuele Feronato has a new tutorial on integrating the Google Maps API with AS3. The API allows Flex and CS3/CS4 developers embed maps and control them. Emanuele's tutorial covers [...]
http://www.emanueleferonato.com/2008/12/01/how-to-use-google-maps-api-with-flash-as3/
CC-MAIN-2013-48
refinedweb
1,028
82.14
Re: CSVDE Importing From: Al Dunbar [MS-MVP] (alan-no-drub-spam_at_hotmail.com) Date: 04/21/04 - Next message: Matt Hickman: "Re: XP slowness logging into an AD domain" - Previous message: Marin Marinov: "Re: allow users to defrag pc's on domain?" - In reply to: Karl: "CSVDE Importing" - Messages sorted by: [ date ] [ thread ] Date: Tue, 20 Apr 2004 20:31:41 -0600 "Karl" <karl@karl.com> wrote in message news:2sXgc.32141$h44.4696085@stones.force9.net... > We have around 200 users within AD that I want to update there information > within AD. > > I have exported certain fields from AD using the following command. > > CSVDE -f users.csv -r "(&(objectCategory=person)(objectClass=user))" -l > "countryCode, description, displayName, comment, manager, company, > department, physicalDeliveryOfficeName, streetAddress, c, > facsimileTelephoneNumber, I, homePhone, mobile, otherTelephone, pager, > > I have now updated the information that was exported with excel and saved > the file back to a csv file. > > When I goto import the file I get a error > > Logging in as current user using SSPI > Importing directory from file "users.csv" > objectClass Attribute not defined > 0 entries modified successfully. > An error has occurred in the program > No log files were written. In order to generate a log file, please > specify the log file path via the -j option. > > > I am not adding any new users just editing there details. There is your problem. CSVDE imports can only be used to create new users (or other objects) as they are incapable of modifying the properties of existing objects. Short of writing your own script to do the importing, you could use LDIFDE instead. It can create (and even delete) new objects, but more importantly for you it can modify the properties of existing objects. Unfortunately, the syntax is a bit more involved than a simple csv file, which makes it a little more difficult to manage its content via script. When I am faced with a task for which writing a full script would be overkill, I often do an ldifde extract, interactively change this to the import syntax using PrimalScript editor macros (yes, I know, very kludgy and adhoc), and then upload the result. /Al - Next message: Matt Hickman: "Re: XP slowness logging into an AD domain" - Previous message: Marin Marinov: "Re: allow users to defrag pc's on domain?" - In reply to: Karl: "CSVDE Importing" - Messages sorted by: [ date ] [ thread ]
http://www.tech-archive.net/Archive/Windows/microsoft.public.windows.server.active_directory/2004-04/1127.html
crawl-002
refinedweb
393
53.71
Search: Search took 0.02 seconds. - 5 Nov 2010 5:40 AM I think I am not using the RPCProxy correctly. I load my data through updating the store and commiting the changes. I think I have to do all the data loading through the RPCProxy, is that right? - 5 Nov 2010 5:32 AM Throughout my application I am calling loader.load only once. But I have commented out this line and now the PagingToolBar is enabled en stays enabled after pressing the refresh button on my... - 5 Nov 2010 3:22 AM Hello ~o) I have an issue with a PagingToolBar, positioned under my Grid. As soon as the initial load through the loader is completed, the PagingToolBar is being set to disabled and it's buttons... - 3 Nov 2010 6:08 AM Hi Sven! My apologies for my late reply. I just wanted to say this topic can be closed and my problem is solved :) You were right about the types, I have set all to BeanModel. The only... - 20 Oct 2010 6:30 AM Hi Sven, thanks for your reply. I removed the extention to BeanModel and added the BeanModelReader to my loader, but now I get errors saying: Bound mismatch: The type RequesterBean is... - 19 Oct 2010 11:34 PM Yes ofcourse: import java.io.Serializable; import com.extjs.gxt.ui.client.data.BeanModel; - 19 Oct 2010 7:09 AM Hello, I'm trying to set up a Grid in GXT. The grid itsself is showing properly, but the data inside is being displayed as empty rows..Through debugging I found out that the store is filled,... Results 1 to 7 of 7
http://www.sencha.com/forum/search.php?s=a399ebde59dfaa14d5cf59c7b2ba6475&searchid=7614066
CC-MAIN-2014-41
refinedweb
278
75.3
The other day I read this interesting paper on contructing a correct equals method when subclassing. It is about Java, but it applies equally well to C#. They cite Josh Bloch’s book Effective Java, who writes: There is no way to extend an instantiable class and add a value component while preserving the equals contract, unless you are willing to forgo the benefits of object-oriented abstraction. I read this book a while back—maybe six or seven years ago now. At the time I thought it was invaluable. It seemed like the Java version of Expert C Programming: Deep C Secrets (the fish book). But when I think back on it now, all I can remember is the author’s ongoing struggle to overcome Java’s limitations and contradictions. It seemed he was constantly recommending more and more verbose code to get around problems in the underlying language. I guess that’s not Bloch’s fault, but Java just seems to be like that. It’s the reason my resume has a crowded half-page of Java TLAs. Anyway, contrary to Bloch’s commonly-accepted denial, the authors of the paper present a way to write an equals method that preserves the contract of equals even when extending from another non-abstract class and adding more state. Their solution isn’t even that verbose or twisted. It’s worth a read. Basically they recommend this (some parts changed for brevity): public class Point { public int x; public int y; public boolean equals(Object other) { boolean result = false; if (other instanceof Point) { Point that = (Point)other; result = that.canEqual(this) && this.x == that.x && this.y == that.y; } return result; } public boolean canEqual(Object other) { return (other instanceof Point); } public int hashCode() { return 41 * (41 + x) + y; } } public class ColoredPoint extends Point { public Color color; public boolean equals(Object other) { boolean result = false; if (other instanceof ColoredPoint) { ColoredPoint that = (ColoredPoint)other; result = that.canEqual(this) && color.equals(that.color) && super.equals(that); } return result; } public boolean canEqual(Object other) { return (other instanceof ColoredPoint); } public int hashCode() { return 41 * super.hashCode() + color.hashCode(); } } The trick here is that canEquals method. It is not really a public method; it is only called from within the equals method. But note that an object doesn’t call it’s own canEquals method; it calls it on the other object. This lets the two objects agree that they are really equal, and it solves the problem of non-symmetric implementations of equals (where a.equals(b) != b.equals(a)). This is a common problem, because a Point might think it equals a ColoredPoint, whereas the ColoredPoint knows it doesn’t equal the Point. The naive way of ensuring symmetry would be to replace instanceof with a comparison of the object’s actual class. But this is too crude, because it means you can’t use anonymous classes. For instance, a Point should still equal an anonymous class instance like this one: Point pAnon = new Point() { public void overrideSomeMethod() { // ... } } With canEquals, the anonymous class simple inherits canEquals from Point, and the two objects will still agree on their equality. I think this is a really nice solution to a thorny problem. The forum discussion about the paper (which is almost as good as the paper itself) argues that Java ought to support an Equalator interface as a parallel to Comparator<T>. The idea is that just as you can override the “natural ordering” of a class, you should be able to override its “natural equivalence.” This would let you instantiate a Set, HashMap, etc. with an Equalator to get a different notion of equals than usual. Just as objects may sort differently in different contexts, so they may “be equal” differently in different contexts, depending on what you care about. Who hasn’t run into the need for a Set based on reference identity, for example? Apache Collections provides just such a class. The need for an Equalator seems most pressing in classes like TreeSet that use compareTo rather than equals to test for set duplicates. If you use a TreeSet with a Comparator that is not consistent with equals, that the TreeSet will appear to violate the set contract, because you could have a.equals(b) but s.contains(a) != s.contains(b). I went to bed thinking it’s a shame Sun hasn’t added this Equalator concept. But as I was thinking about it over the night, I started to believe Sun is right to leave it out, at least in so far as it pertains to classes like TreeSet that use compareTo instead of equals. Basically, the TreeSet’s Comparator is already operating as an Equalator here. Why do you need an Equalator, too? What problem would it solve that isn’t already solved by the Comparator? If you passed an Equalator to a TreeSet, it wouldn’t change this code problem: a.equals(b) && (s.contains(a) != s.contains(b)). The whole point of an Equalator is to impose a different notion of equality on a limited context, and with TreeSet a Comparator is sufficient for that. Of course, that’s not to say an Equalator wouldn’t be useful in a regular Set or Map. It turns out that C# does have the Equalator idea, but it’s called IEqualityComparer<T>. It doesn’t seem to be used much, but Dictionary<K,V> and HashSet<T> both support it. I actually came across this paper while thinking about how C#’s CompareTo<T> can work in a class heirarchy. As in Java, this method must be “consistent with Equals.” That is, whenever Equals returns true, CompareTo must return 0, and whenever CompareTo returns 0, Equals must return true. Put into code, (a.CompareTo(b) == 0) == a.Equals(b). The CompareTo method is tricky because it’s parameterized: its signature is bool CompareTo(T o), where T comes from IComparable<T>. So what happens if you have Base : IComparable<Base> and Subclass : Base, IComparable<Subclass>? My instinct is you’re asking for trouble, although when I think it through it seems that the compiler will choose the method based on the current static type, not the instance’s actual type, so maybe you’d be okay. If your code is interested in comparing Bases, you’ll call that method; you’ll only call CompareTo(Subclass o) if you’re explicitly comparing Subclasses. So maybe everything will work out, but I’m still uneasy. I also see that C# 4.0 is supporting new keywords for co- and contra-variance in generic parameters. So we get IEnumerable<out T> and IComparable<in T>. This means that if you implement IEnumerator<Subclass> GetEnumerator, you also fulfill the contract for IEnumerable<Base>, and if you implement CompareTo(Base o), your subclass doesn’t have to implement CompareTo(Subclass o) in order to fulfill the contract for IComparable<Subclass>. I hope I’ve got that right! The first part—covariant return types—seems like the bigger deal here. (I only wish it were full covariant return types as in C++!) But the part about IComparable seems nice, too. It should save a bit of code, because it means that if you have a full-featured base class and you want to write a quick subclass on top of it, you can still use your subclass in things that require an IComparable<Subclass> (like List<Subclass>) without writing another CompareTo implementation.
https://illuminatedcomputing.com/posts/2010/03/equals-and-compareto-in-subclasses/
CC-MAIN-2021-21
refinedweb
1,246
62.17
Next Chapter: Modular Programming and Modules File I/O Working with Files Though everybody has an understanding of the term file, we want to give a formal definition anyway: A file or a computer file is a chunk of logically related data or information which can be used by computer programs. Usually a file is kept on durable storage. A unique name and path can be used by human users or in programs or scripts to access a file for reading and modification purposes. The term "file" in above described meaning appeared in the history of computers very early. It was used as early as 1952, when punch cards where used. A programming language without the ability to store and retrieve previously stored information would be hardly useful. The most basic tasks involved in file manipulation are reading data from files and writing or appending data to files. The syntax for reading and writing files in Python is similar to programming languages like C and C++ or Perl, but "r" we are determining that we want to read.. You can download the text file ad_lesbiam.txt, if you want to test it yourself: fobj = open("ad_lesbiam.txt") for line in fobj: print line.rstrip() fobj.close()If we save this script and call it "file_read.py", we get the following output, provided that the textfile Catull to his beloved Lesbia. Writing into a File Writing to a file is as easy as reading from a file. To open a file for writing we use as the second parameter a "w" instead of a "r". To actually write the data to this file, we use the method write() of the file object. Example: seuer)We have to point out one possible problem: What happens if you open a file for writing, and this file already exists. Be happy, if you had a backup of this file, if you need it, seuer file including the carriage returns and line feeds. "How to get into a Pickle" We don't mean what the heading says. We just want to show you, how you can save your data in an easy way, so that you or better your program can reread them at a later date again. We are "pickling" the data, so that it doesn't get])A serialized version of the object "obj" will be written to a file "file". The protocol determines the way the object should be written: - 0=ascii - 1=compact (not human readable) - 2=optimised classes Objects which have been dumped to a file with pickle.dump can be reread into a program by using the method pickle.load(file). pickle.load recognizes automatically, which format had been used for writing the data. A simple example: import pickle data = (1.4,42) output = open('data.pkl', 'w') pickle.dump(data, output) output.close()After this code had been executed, the content of the file data.pkl will look like this: (F1.3999999999999999 I42 tp0 .This file can easily be read in again: >>> import pickle >>> f = open("data.pkl") >>> data = pickle.load(f) >>> print data (1.3999999999999999, 42) >>>Only the objects and not their names are saved. That's why we use the assignment to data in the previous example, i.e. data = pickle.load(f). Next Chapter: Modular Programming and Modules
http://python-course.eu/file_management.php
CC-MAIN-2017-09
refinedweb
553
65.83
(Updated 2013-06-15. See comments at the end of the post) (Updated 2014-04-12. A follow up post that applies the same analysis to Roslyn) (Updated 2015-01-23. A much clearer version of this analysis has been done by Evelina Gabasova. She knows what she is talking about, so I highly recommend you read her post first!) This is a follow up post to two earlier posts on module organization and cyclic dependencies. I thought it would be interesting to look at some real projects written in C# and F#, and see how they compare in modularity and number of cyclic dependencies. My plan was to take ten or so projects written in C# and ten or so projects written in F#, and somehow compare them. I didn’t want to spend too much time on this, and so rather than trying to analyze the source files, I thought I would cheat a little and analyze the compiled assemblies, using the Mono.Cecil library. This also meant that I could get the binaries directly, using NuGet. The projects I picked were: C# projects F# projects Unfortunately, there is not yet a wide variety of F# projects to choose from. I picked the following: I did choose SpecFlow and TickSpec as being directly comparable, and also Moq and and Foq. But as you can see, most of the F# projects are not directly comparable to the C# ones. For example, there is no direct F# equivalent to Nancy, or Entity Framework. Nevertheless, I was hoping that I might observe some sort of pattern by comparing the projects. And I was right. Read on for the results! I wanted to examine two things: “modularity” and “cyclic dependencies”. First, what should be the unit of “modularity”? From a coding point of view, we generally work with files (Smalltalk being a notable exception), and so it makes sense to think of the file as the unit of modularity. A file is used to group related items together, and if two chunks of code are in different files, they are somehow not as “related” as if they were in the same file. In C#, the best practice is to have one class per file. So 20 files means 20 classes. Sometimes classes have nested classes, but with rare exceptions, the nested class is in the same file as the parent class. This means that we can ignore them and just use top-level classes as our unit of modularity, as a proxy for files. In F#, the best practice is to have one module per file (or sometimes more). So 20 files means 20 modules. Behind the scenes, modules are turned into static classes, and any classes defined within the module are turned into nested classes. So again, this means that we can ignore nested classes and just use top-level classes as our unit of modularity. The C# and F# compilers generate many “hidden” types, for things such as LINQ, lambdas, etc. In some cases, I wanted to exclude these, and only include “authored” types, which have been coded for explicitly. I also excluded the case classes generated by F# discriminated unions from being “authored” classes as well. That means that a union type with three cases will be counted as one authored type rather than four. So my definition of a top-level type is: a type that is not nested and which is not compiler generated. The metrics I chose for modularity were: Once we have our units of modularity, we can look at dependencies between modules. For this analysis, I only want to include dependencies between types in the same assembly. In other words, dependencies on system types such as String or List do not count as a dependency. Let’s say we have a top-level type A and another top-level type B. Then I say that a dependency exists from A to B if: Aor any of its nested types inherits from (or implements) type Bor any of its nested types. Aor any of its nested types has a field, property or method that references type Bor any of its nested types as a parameter or return value. This includes private members as well – after all, it is still a dependency. Aor any of its nested types has a method implementation that references type Bor any of its nested types. This might not be a perfect definition. But it is good enough for my purposes. In addition to all dependencies, I thought it might be useful to look at “public” or “published” dependencies. A public dependency from A to B exists if: Aor any of its nested types inherits from (or implements) type Bor any of its nested types. Aor any of its nested types has a public field, property or method that references type Bor any of its nested types as a parameter or return value. The metrics I chose for dependencies were: Given this definition of dependency, then, a cyclic dependency occurs when two different top-level types depend on each other. Note what not included in this definition. If a nested type in a module depends on another nested type in the same module, then that is not a cyclic dependency. If there is a cyclic dependency, then there is a set of modules that are all linked together. For example, if A depends on B, B depends on C, and then say, C depends on A, then A, B and C are linked together. In graph theory, this is called a strongly connected component. The metrics I chose for cyclic dependencies were: I analyzed cyclic dependencies for all dependencies and also for public dependencies only. First, I downloaded each of the project binaries using NuGet. Then I wrote a little F# script that did the following steps for each assembly: This dependency list was then used to extract various statistics, shown below. I also rendered the dependency graphs to SVG format (using graphViz). For cycle detection, I used the QuickGraph library to extract the strongly connected components, and then did some more processing and rendering. If you want the gory details, here is a link to the script that I used, and here is the raw data. It is important to recognize that this is not a proper statistical study, just a quick analysis. However the results are quite interesting, as we shall see. Let’s look at the modularity first. Here are the modularity-related results for the C# projects: And here are the results for the F# projects: The columns are: I have extended these core metrics with some extra calculated columns: The first thing I noticed is that, with a few exceptions, the code size is bigger for the C# projects than for the F# projects. Partly that is because I picked bigger projects, of course. But even for a somewhat comparable project like SpecFlow vs. TickSpec, the SpecFlow code size is bigger. It may well be that SpecFlow does a lot more than TickSpec, of course, but it also may be a result of using more generic code in F#. There is not enough information to know either way right now – it would be interesting to do a true side by side comparison. Next, the number of top-level types. I said earlier that this should correspond to the number of files in a project. Does it? I didn’t get all the sources for all the projects to do a thorough check, but I did a couple of spot checks. For example, for Nancy, there are 339 top level classes, which implies that there should be about 339 files. In fact, there are actually 322 .cs files, so not a bad estimate. On the other hand, for SpecFlow there are 242 top level types, but only 171 .cs files, so a bit of an overestimate there. And for Cecil, the same thing: 240 top level classes but only 128 .cs files. For the FSharpX project, there are 173 top level classes, which implies there should be about 173 files. In fact, there are actually only 78 .fs files, so it is a serious over-estimate by a factor of more than 2. And if we look at Storm, there are 67 top level classes. In fact, there are actually only 35 .fs files, so again it is an over-estimate by a factor of 2. So it looks like the number of top level classes is always an over-estimate of the number of files, but much more so for F# than for C#. It would be worth doing some more detailed analysis in this area. The “Code/Top” ratio is consistently bigger for F# code than for C# code. Overall, the average top-level type in C# is converted into 580 instructions. But for F# that number is 1606 instructions, about three times as many. I expect that this is because F# code is more concise than C# code. I would guess that 500 lines of F# code in a single module would create many more CIL instructions than 500 lines of C# code in a class. If we visually plot “Code size” vs. “Top-level types”, we get this chart: What’s surprising to me is how distinct the F# and C# projects are in this chart. The C# projects seem to have a consistent ratio of about 1-2 top-level types per 1000 instructions, even across different project sizes. And the F# projects are consistent too, having a ratio of about 0.6 top-level types per 1000 instructions. In fact, the number of top level types in F# projects seems to taper off as projects get larger, rather than increasing linearly like the C# projects. The message I get from this chart is that, for a given size of project, an F# implementation will have fewer modules, and presumably less complexity as a result. You probably noticed that there are two anomalies. Two C# projects are out of place – the one at the 50K mark is FParsecCS and the one at the 425K mark is my business application. I am fairly certain that this because both these implementations have some rather large C# classes in them, which helps the code ratio. Probably a necessarily evil for a parser, but in the case of my business application, I know that it is due to cruft accumulating over the years, and there are some massive classes that ought to be refactored into smaller ones. So a metric like this is probably a bad sign for a C# code base. On the other hand, if we compare the ratio of code to all types, including compiler generated ones, we get a very different result. Here’s the corresponding chart of “Code size” vs. “All types”: This is surprisingly linear for F#. The total number of types (including compiler generated ones) seems to depend closely on the size of the project. On the other hand, the number of types for C# seems to vary a lot. The average “size” of a type is somewhat smaller for F# code than for C# code. The average type in C# is converted into about 400 instructions. But for F# that number is about 180 instructions. I’m not sure why this is. Is it because the F# types are more fine-grained, or could it be because the F# compiler generates many more little types than the C# compiler? Without doing a more subtle analysis, I can’t tell. Having compared the type counts to the code size, let’s now compare them to each other: Again, there is a significant difference. For each unit of modularity in C# there are an average of 1.1 authored types. But in F# the average is 1.9, and for some projects a lot more than that. Of course, creating nested types is trivial in F#, and quite uncommon in C#, so you could argue that this is not a fair comparison. But surely the ability to create a dozen types in as many lines of F# has some effect on the quality of the design? This is harder to do in C#, but there is nothing to stop you. So might this not mean that there is a temptation in C# to not be as fine-grained as you could potentially be? The project with the highest ratio (4.9) is my F# business application. I believe that this is due to this being only F# project in this list which is designed around a specific business domain, I created many “little” types to model the domain accurately, using the concepts described here. For other projects created using DDD principles, I would expect to see this same high number. Now let’s look at the dependency relationships between the top level classes. Here are the results for the C# projects: And here are the results for the F# projects: The columns are: The diagram column contains a link to a SVG file, generated from the dependencies, and also the DOT file that was used to generate the SVG. See below for a discussion of these diagrams. (Note that I can’t expose the internals of my applications, so I will just give the metrics) These results are very interesting. For C#, the number of total dependencies increases with project size. Each top-level type depends on 3-4 others, on average. On the other hand, the number of total dependencies in an F# project does not seem to vary too much with project size at all. Each F# module depends on no more than 1-2 others, on average. And the largest project (FSharpX) has a lower ratio than many of the smaller projects. My business app and the Storm project are the only exceptions. Here’s a chart of the relationship between code size and the number of dependencies: The disparity between C# and F# projects is very clear. The C# dependencies seem to grow linearly with project size, while the F# dependencies seem to be flat.: So, what can we deduce from these numbers? First, in the F# projects, more than half of the modules have no outside dependencies at all. This is a bit surprising, but I think it is due to the heavy use of generics compared with C# projects. Second, the modules in the F# projects consistently have fewer dependencies than the classes in the C# projects. Finally, in the F# projects, modules with a high number of dependencies are quite rare – less than 2% overall. But in the C# projects, 9% of classes have more than 10 dependencies on other classes. The worst offender in the F# group is my very own F# application, which is even worse than my C# application with respect to these metrics. Again, it might be due to heavy use of non-generics in the form of domain-specific types, or it might just be that the code needs more refactoring! It might be useful to look at the dependency diagrams now. These are SVG files, so you should be able to view them in your browser. Note that most of these diagrams are very big – so after you open them you will need to zoom out quite a bit in order to see anything! Let’s start by comparing the diagrams for SpecFlow and TickSpec. Here’s the one for SpecFlow: Here’s the one for TickSpec: SpecFlow diagram has 12 ranks, and the TickSpec diagram has five. As you can see, there are generally a lot of tangled lines in a typical dependency diagram! How tangled the diagram looks is a sort of visual measure of the code complexity. For instance, if I was tasked to maintain the SpecFlow project, I wouldn’t really feel comfortable until I had understood all the relationships between the classes. And the more complex the project, the longer it takes to come up to speed. The TickSpec diagram is a lot simpler than the SpecFlow one. Is that because TickSpec perhaps doesn’t do as much as SpecFlow? The answer is no, I don’t think that it has anything to do with the size of the feature set at all, but rather because the code is organized differently. Looking at the SpecFlow classes (dotfile), we can see it follows good OOD and TDD practices by creating interfaces. There’s a TestRunnerManager and an ITestRunnerManager, for example. And there are many other patterns that commonly crop up in OOD: “listener” classes and interfaces, “provider” classes and interfaces, “comparer” classes and interfaces, and so on. But if we look at the TickSpec modules (dotfile) there are no interfaces at all. And no “listeners”, “providers” or “comparers” either. There might well be a need for such things in the code, but either they are not exposed outside their module, or more likely, the role they play is fulfilled by functions rather than types. I’m not picking on the SpecFlow code, by the way. It seems well designed, and is a very useful library, but I think it does highlight some of the differences between OO design and functional design. Let’s also compare the diagrams for Moq and Foq. These two projects do roughly the same thing, so the code should be comparable. As before, the project written in F# has a much smaller dependency diagram. Looking at the Moq classes (dotfile), we can see it includes the “Castle” library, which I didn’t eliminate from the analysis. Out of the 249 classes with dependencies, only 66 are Moq specific. If we had considered only the classes in the Moq namespace, we might have had a cleaner diagram. On the other hand, looking at the Foq modules (dotfile) there are only 23 modules with dependencies, fewer even than just the Moq classes alone. So something is very different with code organization in F#. The FParsec project is an interesting natural experiment. The project has two assemblies, roughly the same size, but one is written in C# and the other in F#. It is a bit unfair to compare them directly, because the C# code is designed for parsing fast, while the F# code is more high level. But… I’m going to be unfair and compare them anyway! Here are the diagrams for the F# assembly “FParsec” and C# assembly “FParsecCS”. They are both nice and clear. Lovely code! What’s not clear from the diagram is that my methodology is being unfair to the C# assembly. For example, the C# diagram shows that there are dependencies between Operator, OperatorType, InfixOperator and so on. But in fact, looking at the source code, these classes are all in the same physical file. In F#, they would all be in the same module, and their relationships would not count as public dependencies. So the C# code is being penalized in a way. Even so, looking at the source code, the C# code has 20 source files compared to F#’s 8, so there is still some difference in complexity. In defence of my method though, the only thing that is keeping these FParsec C# classes together in the same file is good coding practice; it is not enforced by the C# compiler. Another maintainer could come along and unwittingly separate them into different files, which really would increase the complexity. In F# you could not do that so easily, and certainly not accidentally. So it depends on what you mean by “module”, and “dependency”. In my view, a module contains things that really are “joined at the hip” and shouldn’t easily be decoupled. Hence dependencies within a module don’t count, while dependencies between modules do. Another way to think about it is that F# encourages high coupling in some areas (modules) in exchange for low coupling in others. In C#, the only kind of strict coupling available is class-based. Anything looser, such as using namespaces, has to be enforced using good practices or a tool such as NDepend. Whether the F# approach is better or worse depends on your preference. It does make certain kinds of refactoring harder as a result. Finally, we can turn our attention to the oh-so-evil cyclic dependencies. (If you want to know why they are bad, read this post ). Here are the cyclic dependency results for the C# projects. And here are the results for the F# projects: The columns are: If we are looking for cycles in the F# code, we will be sorely disappointed. Only two of the F# projects have cycles at all, and those are tiny. For example in FSharp.Core there is a mutual dependency between two types right next to each other in the same file, here. On the other hand, almost all the C# projects have one or more cycles. Entity Framework has the most cycles, involving 24% of the classes, and Cecil has the worst participation rate, with over half of the classes being involved in a cycle. Even NDepend has cycles, although to be fair, there may be good reasons for this. First NDepend focuses on removing cycles between namespaces, not classes so much, and second, it’s possible that the cycles are between types declared in the same source file. As a result, my method may penalize well-organized C# code somewhat (as noted in the FParsec vs. FParsecCS discussion above). Why the difference between C# and F#? One more comparison. As part of my day job, I have written a number of business applications in C#, and more recently, in F#. Unlike the other projects listed here, they are very focused on addressing a particular business need, with lots of domain specific code, custom business rules, special cases, and so on. Both projects were produced under deadline, with changing requirements and all the usual real world constraints that stop you writing ideal code. Like most developers in my position, I would love a chance to tidy them up and refactor them, but they do work, the business is happy, and I have to move on to new things. Anyway, let’s see how they stack up to each other. I can’t reveal any details of the code other than the metrics, but I think that should be enough to be useful. Taking the C# project first: Now let’s look at my F# project: I started this analysis from curiosity – was there any meaningful difference in the organization of C# and F# projects? I was quite surprised that the distinction was so clear. Given these metrics, you could certainly predict which language the assembly was written in. Perhaps this has do with the competency of the programmer, rather than a difference between languages? Well, first of all, I think that the quality of the C# projects is quite good on the whole – I certainly wouldn’t claim that I could write better code! And, in two cases in particular, the C# and F# projects were written by the same person, and differences were still apparent, so I don’t think this argument holds up. This approach of using just the binaries might have gone as far as it can go. For a more accurate analysis, we would need to use metrics from the source code as well (or maybe the pdb file). For example, a high “instructions per type” metric is good if it corresponds to small source files (concise code), but not if it corresponds to large ones (bloated classes). Similarly, my definition of modularity used top-level types rather than source files, which penalized C# somewhat over F#. So, I don’t claim that this analysis is perfect (and I hope haven’t made a terrible mistake in the analysis code!) but I think that it could be a useful starting point for further investigation. This post caused quite a bit of interest. Based on feedback, I made the following changes: Assemblies profiled As you can see, adding seven new data points (five C# and two F# projects) didn’t change the overall analysis. Algorithm changes Text changes The original post is still available here
https://fsharpforfunandprofit.com/posts/cycles-and-modularity-in-the-wild/
CC-MAIN-2020-34
refinedweb
4,046
71.04
In the past days I had a chance to give an eye to these future feature of the .NET framework and I have to say I really love it. It allows you to write code that have to run asynchronously or in sequence (continuations) in a very simple and intuitive way. If you know the basic principles of asynchronous programming the learning curve is quite smooth and fast (it took half a day to me to read up some documentation and start coding my first experiments) I will not go into the in-depth of the feature, because the official documentation is good and easy to read; at this link you can find all the references and the tutorials to start with: Visual Studio Asynchronous Programming. The CTP can be used with any .NET platform: desktop framework, Silverlight or WP7; this is good so you can experiment with your favorite environment. Asynchronous operations are methods and other function members that may have most of their execution take place after they return. In .NET the recommended pattern for asynchronous operations is for them to return a task which represents the ongoing operation and allows waiting for its eventual outcome. Basically after you install the CTP you’ll have access to two new language keywords and some support classes: - async: marks a function as an asynchronous function, it must return void, Task, Task<T> types; inside an async function you can use await expression to wait on ongoing tasks, in other words you flow of execution for the current function stops until the Task you requested to wait for ends (the programming language is responsible for setting up and handling the continuations). - await: causes the flow of execution to stop for the current function until the Task (or Task<T>) for which it’s called end, then the execution proceed to the previous calling point. - Task: it represents an asynchronous operation and exposes all the needed information to check its current execution state or to await until the execution ends. - TaskEx: exposes some utility and helpers function that allows us to execute asynchronous code in different threads or await for multiple tasks termination. As you’ll see in a while using these classes is easy, and the framework itself will take care of the dirty work of generating the state machine to handle your sequence of operation; however always keep in mind this: asynchronous programming doesn’t mean ‘background threads’ all the time. Enough talking let’s see some code in action in my WP7 app ‘All About PrimordialCode’, I’ll start by showing you some traditional async code I had there, this was the starting RssClient class that was used to retrieve the rss feeds: public class RssClient { private readonly string _rssUrl; private readonly object _control; public delegate void ItemsReceivedDelegate(RssClient client, IList<FeedItem> items, Object control); public event ItemsReceivedDelegate ItemsReceived; public RssClient(string rssUrl, object control) { _rssUrl = rssUrl; _control = control; } public void LoadItems() { var request = (HttpWebRequest)WebRequest.Create(_rssUrl); request.BeginGetResponse(ResponseCallback, request); } void ResponseCallback(IAsyncResult result) { var request = (HttpWebRequest)result.AsyncState; WebResponse response; try { response = request.EndGetResponse(result); } catch (Exception) { if (ItemsReceived != null) ItemsReceived(this, null, _control); return; } var stream = response.GetResponseStream(); var reader = XmlReader.Create(stream); var items = new List<FeedItem>(50); FeedItem item = null; var pointerMoved = false; while (!reader.EOF) { // ... // boring code to read items and add them to the 'items' list // ... if (ItemsReceived != null) ItemsReceived(this, items, _control); } } In this code you will see a callback that is scheduled to be executed when we start getting the data stream (line 18) and an event (lines 51-52) that will be raised to give the control back to the calling application to let the rest of the processing go on (continuation). You will also notice that this class will also accept on his constructor the control that will be filled with the returned data. This is how this class was used: //... var rssClient = new RssClient("...", listctrl); rssClient.ItemsReceived += ItemsReceived; rssClient.LoadItems(); ShowProgressBar(true); //... void ItemsReceived(RssClient client, IList<FeedItem> items, object control) { Dispatcher.BeginInvoke(delegate { if (items != null) { ((ItemsControl)control).ItemsSource = items; } else { if (((ItemsControl)control).Items.Count == 1) { FeedItem fi = new FeedItem(); fi.Title = "No connection"; fi.Description = ""; List<FeedItem> lfi = new List<FeedItem>(); lfi.Add(fi); ((ItemsControl)control).ItemsSource = lfi; } } ShowProgressBar(false); }); } We’ve added an event handler and we used a Dispatcher.BeginInvoke() to be sure to execute this function on the correct UI thread (to avoid the cross thread exception when updating a control from a background thread). This is more or less how we do these things now, let’s see now how it will change starting from the RssClass: public class RssClientAsync { private readonly string _rssUrl; public RssClientAsync(string rssUrl) { _rssUrl = rssUrl; } public async Task<IList<FeedItem>> LoadItemsAsync() { var client = new WebClient(); // async call to retrieve the data (in the same thread) string data = await client.DownloadStringTaskAsync(_rssUrl); if (string.IsNullOrEmpty(data)) return null; // i wanna run the rest of the processing in a background thread return await TaskEx.Run(delegate { var items = XDocument.Parse(data).Descendants("item") .Select(e => new FeedItem() { Title = (string)e.Element("title"), Description = Regex.Replace((string)e.Element("description"), @"<(.|\n)*?>", " "), Link = ParseLink(e), PublishDate = ParseDate((string)e.Element("pubDate")) }); return items.ToList(); }); } // some parsing functions... } This is going to be interesting, first off I removed the reference to the control and the ItemsReceived event, I will not need them anymore. Line 10: I marked the function as async and I changed the return type of the function to Task<IList<FeedItems>>, which means that WHEN this function will end it will returns me the whole list of items parsed from the rss stream. Line 15: here we take advantage of some extension that the CTP adds to the WebClient class, the DownloadStringTaskAsync will return a Task<string> object we can wait on with the await keyword. The language will build a state machine to wait for this function to end, then the execution will proceed with... Line 21: we have the whole rss stream read inside our ‘data’ string, it’s time to process it and I choose to force it t execute in a background thread (TaskEx.Run() will force the execution of the delegate in a background thread and it will return a Task object we can wait on), once again we used the await keyword to let the language know that we want to wait for the task to end before going on with the original function. Awesome! we’ve wrote asynchronous code like it was synchronous without altering the ‘flow’ or jumping back and forth following events and callbacks...but wait we’ve not done, let’s see how we use this piece of beauty: private async void TwitterRefreshClick(object sender, RoutedEventArgs e) { var twiClient = new RssClientAsync("..."); ShowProgressBar(true); var items = await twiClient.LoadItemsAsync(); if (items.Count != 0) { Twitter.ItemsSource = items; } else { FeedItem fi = new FeedItem(); fi.Title = "No connection"; fi.Description = ""; List<FeedItem> lfi = new List<FeedItem>(); lfi.Add(fi); Twitter.ItemsSource = lfi; } ShowProgressBar(false); } Line 01: we need to mark the function as async, because we’ll need to use asynchronous operation inside it. Line 03-04: creates and instance of the client class and start a progress bar animation. Line 05: we call and ‘await’ for the LoadItemsAsync() function to complete , once it’s done the control returns to the rest of the function that.. Line 07-23: binds the result to the list control (same code we had inside the event handler before) and stops the progress bar animation. Once again the flow of execution is perfectly clear and the code is extremely easy to read. In the end I have to admit that this CTP really impresses me, it makes writing asynchronous code a breeze in a wide range of scenarios, here I used a WP7 project as example, but it’s really the same in any other platform, so just go there and download this CTP to try it. I really can’t wait to use it in ‘real’ production code. Oh well...actually I do...in the next days I’ll push to the WP7 marketplace another version of ‘All About PrimordialCode’ that uses the Async CTP for these kind of processing. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/wpf-silverlight-wp7-and-async
CC-MAIN-2017-22
refinedweb
1,389
51.68
Technical Articles SAP Readiness Check 2.0 – Setup & Execution Hello All , As Mentioned in the Continuation of the previous blog series on SRC2.0 we have now come up with the complete installation and setup of SRC2.0 followed up by execution. About this Blog In this Blog, We shall try yo Enlighten you about the setup and execution of SRC2.0 As we Know that SAP Readiness Check 2.0 is an Assertive and Robust assessment application to evaluate your Current ECC (ERP system) which you are aspiring to transform into S/4HANA. Disclaimer. The steps/ screen shots in this document are according to note 2758146. Please refer to the note for latest documents. Also in this Document We have considered the Execution as the Detailed planning phase execution as it brings entire set of insights for the Customer. SRC2.0 – Setup System Identification The System which is suppose to be identified for SRC2.0 should have all the recent and used Business process that is being used in an Customers ERP environment. Thus for that it should be either a direct Production system or a system which is the recent Production Copy with workload Statistic data loaded for at least 6 months. So the system which matches the mentioned quality should be identified as Source system for SAP readiness Check 2.0. Also the Analysis that has rendered as a output is based on insights that are client independent and shall cover the insights of all the productive clients under the landscape in which SRC is executed. The Source system identified will be used for Readiness Check 2.0. The report needs to be executed in identified system only . Please refer note 2758146 for more information. System Pre-requisites - While implementing the new Note Version Ensure you De-implement the previous note installed for the smooth Operation of SRC2,0. - Also Always download and install the latest version of the mentioned notes in the system for Smooth Operation of SAP readiness check 2.0 - In case Of any ABAP irregularity make sure you gets the class header has been cleaned using the Class Transaction SE24 . Also you can select the concerned Object open it in change mode and do as shown below in the screen shot. - The Executor /User Created should l have the following – Roles and Auth as - - Download usage data from production system and upload into the copy system following the SAP Note 2568736. This will bring ST03N data only. OSS Note Implementation - The following SAP Notes are required to perform the SAP Readiness Check analysis for the Detailed Planning Phase. - Also Always download and install the latest version of the mentioned notes in the system for Smooth Operation of SAP readiness check 2.0 and De-implement the previous version if there are any installed . - The note implementation is needed in the following manner. These notes are required to have deep analysis on custom code or data consistency. These notes bring in SAP Standard objects used in HANA Sizing analysis, Data Volume Management etc. - Refer SAP Note 2758146. - For more Details on Notes You may Site here. SRC 2.0 Architecture – Remote and Source System Remote system Remote system standalone NW 7.52 or above necessary to complete the technical analysis on custom code to measure the impact of simplification items brought in for S/4HANA. The SCI variant S4HANA_READINESS _XXXX (XXXX can be 1809/1909) is only available on NW version 7.52 and above. The only option available for the same is to install a standalone NW system in the current landscape and enable an RFC connectivity with the Source system for custom Code Analysis. Remote System Pre-requisite - ATC Configuration for System Role – Configure the Remote system to behave as a central check system by changing the system Role to ATC checks by Object Providers only. - Please refer the steps – Open Transaction ATC and select System Role under the Setup option. – Click on edit and choose radio button option ATC check by Object Providers Only - ATC Configure Object Providers – Object provider configuration is needed to collect program information in remote system. To configure Object Provider please refer Steps -Open Transaction ATC and select Object Providers under the Setup option – Create a new System Group – Save the same. Next create RFC Object Providers – Add new id and description, select system group created in the step above. Select the RFC destination created for the source system for custom code analysis. Once done select save. The object provider entries are for reference purpose only and in actual config you need to include valid entries e.g. Sample is for reference purpose only, please include actual RFC destination associated with the source system for custom code analysis system and for other fields as well. - SCI import check variants – Check Variants Contains the series of Checks that are supposed to be crossly apply on the Custom Code to Assess there Compatibility W.r.t to the DB or Data model changes.To perform custom code analysis, SCI Check variants needs to be imported into the remote system. Please perform the steps . – Open Transaction SCI and navigate to Utilities -> Import Check Variants. This should bring in all the check variants into the system. –Check if the variant (in Remote system S4HANA_Readiness_REMOTE or S4HANA_READINESS_XXXX where XXXX can be 1511, 1610, 1709 or 1809/1909) are being imported in the screen as shown below Simplification Database to be loaded in Remote system - The Simplification Database contains the list of all the Simplifications Items that refers various Line of Business within SAP . These Items that are simplified in an SAP product (for example, SAP S/4HANA). The Simplification database needed to perform the Custom Code impact based on the Simplification items applied on the Lobs according to the change in Data model.. Refer steps here- - The detailed steps for downloading the simplification database is mentioned in OSS note 2241080. The DB Download should be in sync of the Target S/4HANA version Customer is aspiring for. E.g. if you plan to upgrade to S/4HANA 1809 /1909 then download the database for 1809 /1909 system. - To upload the simplification database in the remote system, open transaction code SYCM and navigate to menu path Simplification Database -> Import from Zip File. Simplification Catalog in Source system - Simplification Catalog is the segregation of all the simplified items that are very much needed to evaluate the changes that can create impacts on existing ECC system on comparison to the simplified data model of S/4HANA. It is the delicately marked place for the collection of S/4HANA simplification items.Thus to analyze the simplification items impacts for Functional /Business Impact Analysis simplification catalog needs to be downloaded. The process is described below - .Download Simplification Catalog for Readiness Check To download the simplification catalog for Readiness check report, we can download the same directly using the report or from the support portal. Also, the same can be downloaded by using the report /SDF/RC_START_CHECK. Please refer steps – - To download the Simplification Catalog using the report /SDF/RC_START_CHECK. Get to the selection screen of the program and check if the simplification item catalog source is marked at Latest version through auto update. Also, the Catalog Download must be in sync of the Target S/4HANA version, you execute the report and a new version is available. If the radio button is not checked for auto update, you can change the same by clicking on switch source. - If the above fails due to RFC SAPOSS connectivity issue, then you can download the same from here (Select the latest product version based on S/4HANA Target version and download the file using the download simplification item button on top of the report). You can use the Upload Simplification Item Catalog button to load the downloaded file. - If it is set up for local version the file needs to be uploaded manually using the Upload Simplification Item Catalog. Thus Post Doing the Catalog Load . Setup for SRC2.0 Seems to attain a finish line just assure the requested notes and setup steps has been performed as explained. SRC2.0 – Execution The below details provides you with the execution steps to perform SAP Readiness Check for SAP S/4HANA . Data Extraction in Source System This has already been explained a bit in my previous Blog of the same series . Execute program RC_COLLECT_ANALYSIS_DATA in transaction SE38 in the system to download all checks including the consistency check in the zip file. - Make sure “Simplification Item Consistency” checkbox is selected and click the button “Schedule Analysis” to schedule a job to collect data - Go To SE38 - Execute the report RC_COLLECT_ANALYSIS_DATA - Schedule the job. - Schedule the analysis at your convenience. - The following job is scheduled. Download the collected data - Click on Download analysis data. - Save the zip file at appropriate folder. ATC Execution in Remote system - Go to ATC Transaction in SAP GUI - Click on Schedule Runs in Runs Node. - Click on create - Provide a series name - Execute (Tick box) - Provide the following details : - Check Variant according to target version - The Object provider - The objects to be checked - Here Objects can be provided by packages/ type etc. for custom, namespace objects as well as SAP modified objects. - Save the Run series by clicking on Save. - A new run series is created with the name provided. Select the Run and click schedule. - Various options to schedule the runs are provided. - Please schedule the run according to convenience. Consult Basis for job process availability, memory availability. Usually, it is scheduled in following way - Schedule using server Group. - Execute in background. - Click in the tick mark. - Click on Immediate and save. - On results Uploading the collected Source System data to Analyzer. - Click on the Start new Analysis Button as shown below - Enter the name of the Analysis and upload the Zip file obtained from the Execution. - Post Submitting the files After three to four days. A notification Comes that analysis is Ready as shown below. - On clicking on the Analysis the output is shown as below. Upload Remote system ATC results - Open the analysis used for SRC2.0. - Click on the upload button. - Once loaded finding from ATC Custom Code analysis will also become available. as shown above. - Few more Blog Sites that contribute the Setup are here. - Few More Blog Sites that Contribute to Simplification DB/Catalog are here. - Few more FAQs and whats new in SRC2.0 you may site here. *The Snapshots/Images Portrayed taken is belonging to self source . Summary – This blog is in Continuation to the previous Blog on Insights and Flavors .The Complete Setup and execution for SRC2.0 has been mentioned in the Blog. Also I would like to mention that SRC2.0 is an perfect Assessment tool for Assessing the system visibility in terms of conversion to S/4HANA. Super Document ...
https://blogs.sap.com/2020/06/02/sap-readiness-check-2.0-setup-execution/
CC-MAIN-2022-40
refinedweb
1,813
55.95
19 December 2008 20:24 [Source: ICIS news] TORONTO (ICIS news)--Accelerating demand destruction in building and automotive end markets in the US and Europe has prompted Longbow Research to downgrade the shares of US chemicals and coatings firm PPG Industries to "sell" from "neutral", it said on Friday. “We are lowering our investment rating of PPG’s … based on accelerating demand destruction across the company's North American and European businesses,” Longbow said in a research note. A media official a PPG's headquarters was not immediately available for comment. Longbow said the downgrade reflected PPG’s large exposure to domestic and international construction markets, as well as the domestic automotive market and possible pricing challenges in the high-flying caustic soda business in 2009. PPG’s significant exposure to the ?xml:namespace> Margin pressure would last into the first half of 2009, providing downside risk to earnings and PPG's share price, they added. The analysts also lowered their fourth-quarter earnings per share (EPS) estimate for PPG to 49 cents (€0.34) from $1.07 and their 2009 estimate to $3.50 from $4.96, it said. Longbow set a target price of $35 for PPG’s shares. The stock was down 2.51% to $41.63 in Friday afternoon trading in ($1 = €0.70) For more
http://www.icis.com/Articles/2008/12/19/9180888/demand-destruction-slams-us-ppg-hard-analysts.html
CC-MAIN-2014-41
refinedweb
220
58.69
XML::Parser::Expat - Lowlevel access to James Clark's expat XML parser use XML::Parser::Expat; $parser = XML::Parser::Expat->new; $parser->setHandlers('Start' => \&sh, 'End' => \&eh, 'Char' => \&ch); open(FOO, '<', 'info.xml') or die "Couldn't open"; $parser->parse(*FOO); close(FOO); # $parser->parse('<foo id="me"> here <em>we</em> go </foo>'); sub sh { my ($p, $el, %atts) = @_; $p->setHandlers('Char' => \&spec) if ($el eq 'special'); ... } sub eh { my ($p, $el) = @_; $p->setHandlers('Char' => \&ch) # Special elements won't contain if ($el eq 'special'); # other special elements ... } This module provides an interface to James Clark's XML parser, expat. As in expat, a single instance of the parser can only parse one document. Calls to parsestring after the first for a given instance will die. Expat (and XML::Parser::Expat) are event based. As the parser recognizes parts of the document (say the start or end of an XML element), then any handlers registered for that type of an event are called with suitable parameters. This is a class method, the constructor for XML::Parser::Expat. Options are passed as keyword value pairs. The recognized options are: The protocol encoding name. The default is none. The expat built-in encodings are: UTF-8, ISO-8859-1, UTF-16, and US-ASCII. Other encodings may be used if they have encoding maps in one of the directories in the @Encoding_Path list. Setting the protocol encoding overrides any encoding in the XML declaration. When this option is given with a true value, then the parser does namespace processing. By default, namespace processing is turned off. When it is turned on, the parser consumes xmlns attributes and strips off prefixes from element and attributes names where those prefixes have a defined namespace. A name's namespace can be found using the "namespace" method and two names can be checked for absolute equality with the "eq_name" method. option. When this option is defined, errors are reported in context. The value of ErrorContext should be the number of lines to show on either side of the line in which the error occurred. Unless standalone is set to "yes" in the XML declaration, setting this to a true value allows the external DTD to be read, and parameter entities to be parsed and expanded. The base to use for relative pathnames or URLs. This can also be done by using the base method. This method registers handlers for the various events. If no handlers are registered, then a call to parsestring or parsefile will only determine if the corresponding XML document is well formed (by returning without error.) This may be called from within a handler, after the parse has started. Setting a handler to something that evaluates to false unsets that handler. This method returns a list of type, handler pairs corresponding to the input. The handlers returned are the ones that were in effect before the call to setHandlers. The recognized events and the parameters passed to the corresponding handlers are: This event is generated when an XML start tag is recognized. Parser is an XML::Parser::Expat instance. Element is the name of the XML element that is opened with the start tag. The Attr & Val pairs are generated for each attribute in the start tag. This event is generated when an XML end tag is recognized. Note that an XML empty tag (<foo/>) generates both a start and an end event. There is always a lower level start and end handler installed that wrap the corresponding callbacks. This is to handle the context mechanism. A consequence of this is that the default handler (see below) will not see a start tag or end tag unless the default_current method is called.). This is called after an external entity has been parsed. It allows applications to perform cleanup on actions performed in the above ExternEnt handler. an XML::Parser::ContentModel object. See "XML::Parser::ContentModel Methods" for methods available for this class. will be true or false, indicating whether or not the doctype declaration contains an internal subset. This handler is called after parsing of the DOCTYPE declaration has finished, including any internal or external DTD declarations.. Return the URI of the namespace that the name belongs to. If the name doesn't belong to any namespace, an undef is returned. This is only valid on names received through the Start or End handlers from a single document, or through a call to the generate_ns_name method. In other words, don't use names generated from one instance of XML::Parser::Expat with other instances. Return true if name1 and name2 are identical (i.e. same name and from the same namespace.) This is only meaningful if both names were obtained through the Start or End handlers from a single document, or through a call to the generate_ns_name method. Return a name, associated with a given namespace, good for using with the above 2 methods. The namespace argument should be the namespace URI, not a prefix. When called from a start tag handler, returns namespace prefixes declared with this start tag. If called elsewere (or if there were no namespace prefixes declared), it returns an empty list. Setting of the default namespace is indicated with '#default' as a prefix. Return the uri to which the given prefix is currently bound. Returns undef if the prefix isn't currently bound. Use '#default' to find the current binding of the default namespace (if any). Return a list of currently bound namespace prefixes. The order of the the prefixes in the list has no meaning. If the default namespace is currently bound, '#default' appears in the list. Returns the string from the document that was recognized in order to call the current handler. For instance, when called from a start handler, it will give us the the start-tag string. The string is encoded in UTF-8. This method doesn't return a meaningful string inside declaration handlers. Returns the verbatim string from the document that was recognized in order to call the current handler. The string is in the original document encoding. This method doesn't return a meaningful string inside declaration handlers. When called from a handler, causes the sequence of characters that generated the corresponding event to be sent to the default handler (if one is registered). Use of this method is deprecated in favor the recognized_string method, which you can use without installing a default handler. This method doesn't deliver a meaningful string to the default handler when called from inside declaration handlers. Concatenate onto the given message the current line number within the XML document plus the message implied by ErrorContext. Then croak with the formed message. Concatenate onto the given message the current line number within the XML document plus the message implied by ErrorContext. Then carp with the formed message. Returns the line number of the current position of the parse. Returns the column number of the current position of the parse. Returns the current position of the parse. Returns the current value of the base for resolving relative URIs. If NEWBASE is supplied, changes the base to that value. Returns a list of element names that represent open elements, with the last one being the innermost. Inside start and end tag handlers, this will be the tag of the parent element. Returns the name of the innermost currently opened element. Inside start or end handlers, returns the parent of the element associated with those tags. Returns true if NAME is equal to the name of the innermost currently opened element. If namespace processing is being used and you want to check against a name that may be in a namespace, then use the generate_ns_name method to create the NAME argument. Returns the number of times the given name appears in the context list. If namespace processing is being used and you want to check against a name that may be in a namespace, then use the generate_ns_name method to create the NAME argument. Returns the size of the context list. Returns an integer that is the depth-first visit order of the current element. This will be zero outside of the root element. For example, this will return 1 when called from the start handler for the root element start tag. INDEX is an integer that represents an element index. When this method is called, all handlers are suspended until the start tag for an element that has an index number equal to INDEX is seen. If a start handler has been set, then this is the first tag that the start handler will see after skip_until has been called. Returns a string that shows the current parse position. LINES should be an integer >= 0 that represents the number of lines on either side of the current parse line to place into the returned string. Returns TEXT with markup characters turned into character entities. Any additional characters provided as arguments are also turned into character references where found in TEXT. The SOURCE parameter should either be a string containing the whole XML document, or it should be an open IO::Handle. Only a single document may be parsed for a given instance of XML::Parser::Expat, so this will croak if it's been called previously for this instance. Parses the given string as an XML document. Only a single document may be parsed for a given instance of XML::Parser::Expat, so this will die if either parsestring or parsefile has been called for this instance previously. This method is deprecated in favor of the parse method. Parses the XML document in the given file. Will die if parsestring or parsefile has been called previously for this instance. NO LONGER WORKS. To find out if an attribute is defaulted please use the specified_attr method. When the start handler receives lists of attributes and values, the non-defaulted (i.e. explicitly specified) attributes occur in the list first. This method returns the number of specified items in the list. So if this number is equal to the length of the list, there were no defaulted values. Otherwise the number points to the index of the first defaulted attribute name. Unsets all handlers (including internal ones that set context), but expat continues parsing to the end of the document or until it finds an error. It should finish up a lot faster than with the handlers set. There are data structures used by XML::Parser::Expat that have circular references. This means that these structures will never be garbage collected unless these references are explicitly broken. Calling this method breaks those references (and makes the instance unusable.) Normally, higher level calls handle this for you, but if you are using XML::Parser::Expat directly, then it's your responsibility to call it. The element declaration handlers are passed objects of this class as the content model of the element declaration. They also represent content particles, components of a content model. When referred to as a string, these objects are automagicly converted to a string representation of the model (or content particle). This method returns true if the object is "EMPTY", false otherwise. This method returns true if the object is "ANY", false otherwise. This method returns true if the object is "(#PCDATA)" or "(#PCDATA|...)*", false otherwise. This method returns if the object is an element name. This method returns true if the object is a choice of content particles. This method returns true if the object is a sequence of content particles. This method returns undef or a string representing the quantifier ('?', '*', '+') associated with the model or particle. This method returns undef or (for mixed, choice, and sequence types) an array of component content particles. There will always be at least one component for choices and sequences, but for a mixed content model of pure PCDATA, "(#PCDATA)", then an undef is returned. The class XML::Parser::ExpatNB is a subclass of XML::Parser::Expat used for non-blocking access to the expat library. It does not support the parse, parsestring, or parsefile methods, but it does have these additional methods: Feed expat more text to munch on. Tell expat that it's gotten the whole document. Load an external encoding. ENCODING is either the name of an encoding or the name of a file. The basename is converted to lowercase and a '.enc' extension is appended unless there's one already there. Then, unless it's an absolute pathname (i.e. begins with '/'), the first file by that name discovered in the @Encoding_Path path list is used. The encoding in the file is loaded and kept in the %Encoding_Table table. Earlier encodings of the same name are replaced. This function is automaticly called by expat when it encounters an encoding it doesn't know about. Expat shouldn't call this twice for the same encoding name. The only reason users should use this function is to explicitly load an encoding not contained in the @Encoding_Path list. Larry Wall <larry@wall.org> wrote version 1.0. Clark Cooper <coopercc@netheaven.com> picked up support, changed the API for this version (2.x), provided documentation, and added some standard package features.
http://search.cpan.org/~chorny/XML-Parser-2.40/Expat/Expat.pm
CC-MAIN-2017-13
refinedweb
2,203
65.93
AccountObject Accountstill means to offer three services: okToWithdraw(), withdraw(), and deposit() 1 package com.artima.examples.account.ex * Money is stored in this account in integral units. Clients 16 * can use this account to store any kind of value, such as money 17 * or points, etc. The meaning of the integral units stored in 18 * this account is a decision of the client that instantiates the 19 * account. The maximum amount of units that can be stored as 20 * the current balance of an <code>Account</code> is Long.MAX_VALUE. 21 */ 22 public class OverdraftAccount { 23 24 /** 25 * Helper back-end object 26 */ 27 private Account account = new Account(); 28 29 /** 30 * The maximum amount the bank will loan to the client. 31 */ 32 private final long overdraftMax; 33 34 /** 35 * The current amount the bank has loaned to the client 36 * which has not yet been repaid. This must be zero to 37 * overdraftMax. 38 */ 39 private long overdraft; 40 41 /** 42 * Constructs a new <code>OverdraftAccount</code> with the 43 * passed <code>overdraftMax</code>. 44 * 45 * @param overdraftMax the maximum amount the bank will loan 46 * to the client 47 */ 48 public OverdraftAccount(long overdraftMax) { 49 this.overdraftMax = overdraftMax; 50 } 51 52 /** 53 * Returns the current overdraft, the amount the bank has 54 * loaned to the client that has not yet been repaid. 55 * 56 * @returns the current overdraft 57 */ 58 public long getOverdraft() { 59 return overdraft; 60 } 61 62 /** 63 * Returns the overdraft maximum, the maximum amount the 64 * bank will allow the client to owe it. For each instance 65 * of <code>OverdraftAccount</code>, the overdraft maximum 66 * is constant. 67 * 68 * @returns the overdraft maximum 69 */ 70 public long getOverdraftMax() { 71 return overdraftMax; 72 } 73 74 /** 75 * Gets the current balance of this <code>OverdraftAccount</code> 76 * 77 * @returns the current balance 78 */ 79 public long getBalance() { 80 return account.getBalance(); 81 } 82 83 /** 84 * Withdraws exactly the passed amount from the 85 * <code>Account</code>. If the passed amount is 86 * less than or equal to the current balance, all withdrawn 87 * funds will be taken from the balance, and the balance 88 * will be decremented by the passed amount. If the passed amount 89 * exceeds the current balance, the bank may loan the client the 90 * difference. The bank will make the loan only if the difference 91 * between the passed amount and the balance is less than or equal to 92 * the available overdraft. The available overdraft is equal to 93 * the current overdraft (the amount already loaned to the client and 94 * not yet repaid), subtracted from the overdraft maximum, which 95 * is passed to the constructor of any <code>OverdraftAccount</code>. 96 * 97 * <p> 98 * If the passed amount less the current balance is less than or equal 99 * to the available overdraft, the <code>withdraw</code> method returns 100 * the requested amount, sets the current balance to zero, and records 101 * the loan. Otherwise, if the passed amount less the current balance 102 * exceeds the available overdraft, the <code>withdraw</code> method throws 103 * <code>InsufficientFundsException</code>. 104 * 105 * @param amount amount to withdraw 106 * @returns amount withdrawn from the <code>Account</code> 107 * @throws InsufficientFundsException if the <code>Account</code> 108 * contains insufficient funds for the requested withdrawal 109 */ 110 public long withdraw(long amount) 111 throws InsufficientFundsException { 112 113 long balance = account.getBalance(); 114 if (balance >= amount) { 115 116 // Balance has sufficient funds, just take the 117 // money from the balance. 118 balance -= amount; 119 return amount; 120 } 121 122 long shortfall = amount - balance; 123 long extraAvailable = overdraftMax - overdraft; 124 125 if (shortfall > extraAvailable) { 126 throw new InsufficientFundsException(shortfall - extraAvailable); 127 } 128 overdraft += shortfall; 129 account.withdraw(amount - shortfall); 130 131 return amount; 132 } 133 134 /** 135 * Deposits exactly the passed amount into the <code>Account</code>. 136 * If the current overdraft is zero, the balance will be increased 137 * by the passed amount. Otherwise, the bank will attempt to pay 138 * off the overdraft first, before increasing the current balance 139 * by the amount remaining after the overdraft is repaid, if any. 140 * 141 * <p> 142 * For example, if the balance is 200, the overdraft is 100, and the 143 * <code>deposit</code> method is invoked with a passed <code>amount</code> 144 * of 50, the bank would use all 50 of those monetary units to pay down 145 * the overdraft. The overdraft would be reduced to 50 and the balance would 146 * remain at 200. If subsequently, the client deposits another 100 units, 147 * the bank would use 50 of those units to pay off the overdraft loan and 148 * direct the remaining 50 into the balance. The new overdraft would 149 * be 0 and the new balance would be 250. 150 * 151 * @param amount amount to deposit 152 * @throws ArithmeticException if requested deposit would cause the 153 * balance of this <code>Account</code> to exceed Long.MAX_VALUE. 154 */ 155 public void deposit(long amount) { 156 if (overdraft > 0) { 157 if (amount < overdraft) { 158 overdraft -= amount; 159 } 160 else { 161 long diff = amount - overdraft; 162 overdraft = 0; 163 account.deposit(diff); 164 } 165 } 166 else { 167 account.deposit(amount); 168 } 169 } 170 } Accountobject on the heap: Another relationship similar to composition is aggregation. Like composition, the aggregation relationship entails a front-end object holding references in instance variables to back-end objects. The difference is intent. In a composition relationship, the front-end objects enlist the help of the back-end objects to fulfill the front-end's semantic contract. In an aggregation relationship, front-end objects merely serve as containers for back-end objects. Front-end objects in an aggregation relationship don't invoke methods on back-ends, they just hold them. In a non-garbage collected language, such as C++, it is more important to differentiate between composition and aggregation. Roughly speaking, if a back-end object is in a composition relationship in C++, the back-end should in general be deleted by the destructor of the front-end. By contrast, if a back-end object is held in an aggregation relationship in C++, the back-end object should in general survive the destruction of the front-end. Given that Java objects are never explicitly destroyed, just released to the whims of the garbage collector, the composition/aggregation distinction is not as important in Java. On the other hand, it is important in Java to differentiate between composition and aggregation when implementing the clone method. Mutable back-end objects held in a composition relationship should be cloned along with the front-end object. In an aggregation relationship, by contrast, back-end objects should not be cloned. Put another way, composition implies deep copy; aggregation implies shallow copy. This distinction is discussed in guideline ??? and the Clonable Object Recipe in Appendix A. composition sometimes models the HAS-A relationship, but not always. Here mention why I avoided HAS-A, that design patterns give a much richer discussion of composition relationships -- see chapter 4. Discuss aggregation in that you are holding onto objects for the client, but not delegating to those objects yourself. Mention the collections stuff, messengers for multi-valued returns, arrays, tuples.
https://www.artima.com/interfacedesign/EnlistHelp.html
CC-MAIN-2019-13
refinedweb
1,199
50.36