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
Ok. I'm doing this site's tutorial on C++, and I'm on the lesson about functions. I'm trying to do the multiplication example. But it won't work. here's what i haveWhen i copy and paste it in, it works just fine. What am i doing wrong?When i copy and paste it in, it works just fine. What am i doing wrong?Code://a program to test out this whole idea of functions #include <iostream> using namespace std int mult (int x, int y); int main() { int x; int y; cout << "please input two numbers to be multiplied: "; cin >> x >> y; cin.ignore(); cout<<"the product of your two numbers "<< mult (x,y) << "\n"; cin.get(); } int mult (int x, int y) { return x*y; } Never mind. I figured out what i was doing wrong. I need to put a ; after namespace std
http://cboard.cprogramming.com/cplusplus-programming/70269-help-functions.html
CC-MAIN-2015-35
refinedweb
148
85.49
SETEUID(2) Linux Programmer's Manual SETEUID(2) seteuid, setegid - set effective user or group ID #include <sys/types.h> #include <unistd.h> int seteuid(uid_t euid); int setegid(gid_t egid); Feature Test Macro Requirements for glibc (see feature_test_macros(7)): seteuid(), setegid(): _POSIX_C_SOURCE >= 200112L || /* Glibc versions <= 2.19: */ _BSD_SOURCE seteuid() sets the effective user ID of the calling process. Unprivileged. Note: there are cases where seteuid() can fail even when the caller is UID 0; it is a grave security error to omit checking for a failure return from seteuid(). EINVAL The target user or group ID is not valid in this user namespace. EPERM In the case of seteuid(): the calling process is not privileged (does not have the CAP_SETUID capability in its user namespace) and euid does not match the current real user ID, current effective user ID, or current saved set-user-ID. In the case of setegid(): the calling process is not privileged (does not have the CAP_SETGID capability in its user namespace) and egid does not match the current real group ID, current effective group ID, or current saved set-group-ID. POSIX.1-2001, POSIX.1-2008, 4.3BSD. Setting the effective user (group) ID to the saved set-user-ID (saved set-group-ID) is possible since Linux 1.1.37 (1.1.38). On an arbitrary system one should check _POSIX_SAVED_IDS.. C library/kernel differences On Linux, seteuid() and setegid() are implemented as library functions that call, respectively, setreuid(2) and setregid(2). geteuid(2), setresuidEUID(2) Pages that refer to this page: pmdaproc(1), setgid(2), setgid32(2), credentials(7), nptl(7)
https://man7.org/linux/man-pages/man2/setegid.2.html
CC-MAIN-2020-40
refinedweb
271
51.68
1. What is the implication of having different number of work processes defined differently in different places in the system A. No implication, the system resolves it by taking the definition of the kernel B. Inconsistencies can occur C. The switching must be done manually D. The switching takes place dynamically 2. Packages are created and managed with A. Package Builder (SPAK) B. Package Developer (SPAK) C. Package Editor (SPAK) D. ABAP Editor (SE38) 3. It is possible for an individual to request for his own namespace in SAP. True/False 4. Workbench and customizing requests are both created with A. SE10 B. SE09 C. SE12 D. SE21 5. What elements are parts of the data structure of an SAP system? A. Registry Repository B. Object Repository C. Client D. Database Server E. Cross-client customizing F. SAP Kernel 6. Decide which of the following statements are correct A. Entering customer data requires a customizing request B. A change request contains one or more tasks C. A task can always be assigned to only one developer D. Any customizing requires a customizing request 7. Which statements are correct? A. The transport of objects is divided into export, storage and import phases B. The import into target system is performed automatically at midnight Greenwich Mean Time C. The transport directory is specified by parameter DIR_TRANS D. When transporting, the following rules applies: The target client is the same as the source client, unless otherwise specified 8. Work processes use a shared user to access the database. True/false 9. Users are assigned authorizations using A. Privileges B. Profile C. Roles D. Authentication 10. Which of the following are user types in an SAP system A. Dialog B. System C. Communication D. Service E. RFC F. Reference 11. Which of these user types is used to assign additional authorization A. Dialog B. System C. Communication D. Reference 12. Which of the following user type is used for anonymous system accesses using an ITS or ICF service A. Dialog B. System C. Service D. Communication E. Reference 13. Which of the following user types can be used for dialog free communication within the system A. Dialog B. System C. Service D. Communication E. Reference 14. Which of the following user types requires only the system administrator to change the password A. Dialog B. System C. Service D. Communication E. Reference 15. Which of the following user type is exempted from the usual settings for the validity period of a password A. Dialog B. System C. Communication D. Reference E. Service ANSWERS 1. B. If it is not possible to switch between operation modes, this is usually due to inconsistencies in the SAP system. These inconsistencies can occur if the number of work processes is defined differently in different places in the system. There are the instance profiles at operating system level, the instance profile in the database, and the definition of operation modes themselves. If for example, the number of work process in the profile is changed, the system can no longer switch operation modes until after a restart of the instance. It is therefore necessary to adjust the configuration of the operation modes after a change to the profile. 2. A. 3. True. You can request your own namespace that begins and end with “/” free of charge from SAP. E.g /Firm/. All of the objects that you write then have a name beginning with “/Firm” such as “/Firm/GreatProgram/”. 4. A, B 5. B, C, E. The object repository, cross client customizing, and the clients are part of the data structures of an SAP system. The database structure is not part of the data structure, rather, it contains it. 6. B, C. Entering customer data is not part of customizing and therefore does not require a customizing request. Only client dependent customizing requires a customizing request; cross client customizing, on the other hand, requires a workbench request. A change request contains one or more tasks, each of which are assigned to only one developer. 7. C, D. The transport is divided into only two phases: Export and Import. The import into database of the target system is never performed automatically. 8. True 9. C 10. A, B, C, D, F. RFC is not a type of user in SAP. 11. D. A reference user is used only to assign additional authorization. You can specify a reference user for a dialog user for additional authorization on the roles tab page. A reference user is a general non-person-related user. 12. C. A service user is a dialog user that is available to a larger anonymous group of users. You should only assign highly restricted authorizations to users of this type 13. B, D 14. B, C 15. B
https://it.toolbox.com/blogs/eseyinok/sap-on-oracle-certification-preparation-c-tadm51-70-test-your-basis-skill-082709
CC-MAIN-2019-04
refinedweb
797
58.58
Prettyfaces + Hibernate + Spring lazy initialization Splash › Forums › PrettyFaces Users › Prettyfaces + Hibernate + Spring lazy initialization This topic contains 6 replies, has 3 voices, and was last updated by Christian Kaltepoth 6 years, 3 months ago. - AuthorPosts Hi, I have an application with primefaces, spring and hibernate set up and working. But in one particular case it fails. Whenever I go to create an editing screen and do the following process: I run the edit method by carrying my object id, after that, I point to the page editing as follows. return “pretty: edit”; Thus the loading screen it returns a lazy initialization exception. I have the Spring filter set, but I think that when I call this the filter is no longer running, or has been executed. This may be related to the redirect? My filter is configured so after prettyfaces. <filter> <filter-name> hibernate </ filter-name> <filter-class> org.springframework.orm.hibernate3.support.OpenSessionInViewFilter </ filter-class> </ filter> <filter-mapping> <filter-name> hibernate </ filter-name> <url-pattern> / * </ url-pattern> <dispatcher> FORWARD </ dispatcher> <dispatcher> REQUEST </ dispatcher> <dispatcher> ERROR </ dispatcher> </ filter-mapping> Best Regards This sound like you are calling an action method to “prepare” the edit page by loading the corresponding object from the database, then doing return "pretty: edit";which redirects the user to the actual edit page. Correct? In this case the exception is easy to explain. You are first loading the object and then you do a redirect. After the redirect the object will be detached resulting in a lazy initialization exception because the redirect results in a new request to the server. This is a pattern that is not recommended. You should instead encode the ID of the object you want to edit in the URL. Then load the object in an URL action. This way you get a clean bookmarkable URL like /user/edit/5. The example 3.1 in this chapter of the documentation: I hope this helps Christian Lincoln Baxter IIIKeymaster Yes, I agree with Christian’s assessment. You’ll either need to use a long-running conversation with Hibernate, store your object in the session (not recommended unless you have performance problems,) or you’ll need to pass the ID of your object via the URL of the edit page. ~Lincoln Hi, Perfect. Is there a design example of how an application should work PrettyFaces, urls, configuration, eg for a crud? What would be good practice. When the User clicks the edit button: pretty: edit Directs to the url: / user/edit/5 In the bean is loaded object 5 is shown to the User. It changes some information and clicks the save button: pretty: update Upon arriving at this object bean must be reloaded to avoid the lazy? And after copying the properties of the filled object on the screen? What would best solution? Best Regards, I can only for myself, but I’m typically using the following pattern. The entry point is a list view containing all the entities. The Java class typically looks like this: @Named @RequestScoped @URLMapping(id = "userList", pattern = "/admin/users", viewId = "/admin/user-list.jsf") public class UserListBean { private List<User> list; @URLAction public void init() { list = userDao.list(); } /* getter + setter */ } The dataTable contains a column with an edit link. This link refers to the edit page like this: <h:dataTable <!-- .... --> <h:column> <pretty:link <f:param Edit </pretty:link> </h:column> </h:dataTable> This renders a simple HTML link. The bean responsible for the edit page looks like this: @Named @RequestScoped @URLMapping(id = "editUser", pattern = "/admin/user/#{userEditBean.id}", viewId = "/admin/user-edit.jsf") public class UserEditBean { private Long id; private User user; private String firstname; private String lastname; @URLAction public void init() { // load user to edit from the DB user = userDao.getById( id ); // load values to edit firstname = user.getFirstname(); lastname = user.getLastname(); } public String save() { // update database object user.setFirstname(firstname); user.setLastname(lastname); // back to list view return "pretty:userList"; } /* getter + setter */ } Simple, isn’t it? I typically prefer to have separate fields in the JSF bean which hold the properties of the database object that are editable. I prefer that because you can post process these values (like to a String.trim()) and do complex validations that aren’t possible with JSF validators. But you could also bind the input components directly to the database entity. Christian Hi Cristian, In the edit page as you call the save method? action=”#{userEditBean.save}” This is my big question, what the correct way to perform the method change. Calling the bean directly, or by calling an action of Pretty: pretty:save Best Regards Just call the bean directly. This makes most sense here because it allows you to process all the form data. - AuthorPosts You must be logged in to reply to this topic.
http://www.ocpsoft.org/support/topic/prettyfaces-hibernate-spring-lazy-initialization/
CC-MAIN-2018-39
refinedweb
798
56.55
Before going ahead and describing how we can use Python to create a universally unique identifier (UUID), one might ask, what is the UUID anyway? So, let's start by defining what we mean by a UUID and why we use it. What Is a UUID? The UUID is basically a 16-byte (128-bit) number used to uniquely identify an object (data). This number consists of 32 hexadecimal digits which are displayed in five groups, and separated by hyphens. To see what a UUID might look like, here is an example: 022db29c-d0e2-11e5-bb4c-60f81dca7676 The goal of using such an identifier is to guarantee that we don't have similar identifiers, or at least guarantee having an identifier to be different from any UUIDs generated until 3400 A.D.! Such uniqueness is achieved by combining different components together that would guarantee that UUIDs are different. The identifier in this case will be composed of the network address of the machine, a timestamp, and a randomly generated component. Thus, we can say that a UUID is considered an algorithm which is used to create a unique string of particular format which is composed of different components that ensure the uniqueness of the identifier. UUIDs in Python Let's now come to the fun part, how to create a UUID in python. In order to do so, we will need to use Python's uuid module. You don't need to install anything at this point, as this module comes with your Python distribution. All you need to do to use the module is to import it directly from your script. Before that, let me show you how Python's documentation describes this module: This module provides immutable UUIDobjects (the UUIDclass) and the functions uuid1(), uuid3(), uuid4(), uuid5()for generating version 1, 3, 4, and 5 UUIDs as specified in RFC 4122. Well, guess what? As we learned in the smooth refreshers series, Python strives to make things easy, and creating a UUID is no different. Here you go! import uuid print uuid.uuid4() Yes, that's it! This is all you need to generate a UUID in Python. On my machine, I got the following output: b77eafed-69ab-422d-8448-1ec1f0a2eb8c How many hexadecimal digits can you see? Don't you think Python is trying to make our lives easier?! Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
https://code.tutsplus.com/tutorials/quick-tip-how-to-create-a-universally-unique-identifier-in-python--cms-25927
CC-MAIN-2018-26
refinedweb
412
63.49
Overview Atlassian Sourcetree is a free Git and Mercurial client for Windows. Atlassian Sourcetree is a free Git and Mercurial client for Mac. Multimethod provides a decorator for adding multiple argument dispatching to functions. The decorator finds the multimethod of the same name, creating it if necessary, and registers the function with its annotations. There are several multiple dispatch libraries on PyPI. This one aims to be correct, simple, and fast. It doesn't support arbitrary predicates, for example, but should be the fastest pure Python implementation possible. Usage from multimethod import multimethod @multimethod def func(x: int, y: float): ... func is now a multimethod which will delegate to the above function, when called with arguments of the specified types. Subsequent usage will register new types and functions to the existing multimethod of the same name. If an exact match can't be found, the next closest method is called (and cached). Candidate methods are ranked based on their subclass relationships. If no matches are found, a custom TypeError is raised. A strict flag can also be set on the multimethod object, in which case finding multiple matches also raises a TypeError. Keyword arguments can be used when calling, but won't affect the dispatching. Types can instead be specified by calling multimethod, thereby supporting Python 2 as well. This syntax also supports stacking decorators for registering multiple signatures. @multimethod(int, float) @multimethod(float, int) def func(x, y): ... The functools.singledispatch style syntax introduced in Python 3.4 is also supported. This requires creating a multimethod explicitly, and consequently doesn't rely on the name matching. from multimethod import multidispatch @multidispatch def func(*args): ... @func.register(*types) def _(*args): ... See tests for more example usage. Installation $ pip install multimethod Dependencies - Python 2.7, 3.4+ Tests 100% branch coverage. $ pytest [--cov] Changes 0.6 - Multimethods can be defined inside a class 0.5 - Optimized dispatching - Support for functools.singledispatch syntax 0.4 - Dispatch on Python 3 annotations
https://bitbucket.org/coady/multimethod/overview
CC-MAIN-2017-39
refinedweb
329
52.87
Mbirn: Meeting Minutes From NAMIC Date: Feb 7, 2005 2:00pm EST Attendance: Dan Marcus, Yong Gao, Heidi Schmidt, Tony Lissot, Tim Clark, Georgios Asteris, Hans Breiter, Dave Kennedy (Did I miss anyone?) 1. We will be using the mBIRN/NAMIC wiki site () for ongoing discussion and documentation. Use of this facility is essential to assist in the development of the necessary documentation for XNAT. 2. Hans provided brief background of PGP project to Dan Marcus. Additional information (executive summary, etc.) will be provided to Dan to help them understand the overall structure and goals of the PGP project. 3. A mid-level XNAT system description will be developed, to assist potential users of the XNAT system in understanding the nature, design and implementation practices employed in the system. Dan and Yong will continue this discussion off-line. 4. Hardware/software requirements were reviewed. The initial 'installation memo' was reasonably complete in the requirements. Additional dependencies will be packaged into the XNAT distribution itself, and will not require preinstallation. 5. Approach to Installation. Multi-phased approach. Phase I: MGH test of WashU sample app (Notes: schema stays same, only installation site changes; this to initially be database generation tool, with it's xml schema and test data; web app testing is still approx 2 weeks away; MGH will concurrently test Postgres and Oracle versions) Phase II: MGH will prepare sample xml data models for PGP specific data (subject, structural imaging, functional imaging, diffusion imaging, ASL imaging, behavioral testing, etc.). These models will also be tested at WashU to provide feedback on the generation code. (Note: for WashU testing, installation stays the same, only data model changes). Phase III: MGH will continue local implementation of PGP data requirements at MGH. 6. Action Items: a) Dan to provide sample schema and data and database generator to MGH (Yong/Heidi) b) Yong and Heidi (and Georgios?) to test the generation functions. c) Tony to provide existing schema (xml?) of the database structure he's already using d) Dave, Tony, (with help from many others) to create initial data models for structural and functional data requirements Transcribed by: --Dave 09:17, 8 Feb 2005 (EST) Date: Feb 7, 2005 2:00pm EST Attendance: Dan Marcus, Heidi Schmidt, Yong Gao, Dave Kennedy, Tim Olsen, Tim Clark Agenda: 1. PGP-extensions to oasis sample sample data conforming to this schema Reviewed the specific extensions that have been proposed from PGP standpoint, and that the new XSD has been tested through the generator and with 'fake' sample data. Work is ongoing to prepare a data document with real PGP data, first for one subject, to test; then with mulitple (~10) subjects for further testing. This involves work on formating the output of local programs to export data in the necessary XML format. Issues regardinging what namespaces should be used arose. Dan will review the proposed changes and suggest what changes should be part of the base XNAT namespace, versus which elements belong in a PGP extension namespace. Ways for checking XML validity were discussed (rxp, Xerces, smlspy, etc.). Where should be ways for data files to be checked prior to upload; there will also be some checking as part of XNAT. Over the next week, this sample data will be finalized and loaded. 2. WebApp... Dan discussed the general form of this a bit; including XML display documents related to each element in the schema. Disucssion of the difference between listing pages and report pages was introduced. Since this is not well described in the current MGH example, Dan will prepare some documentation on the process, and review some examples of how to control the Webapp, so that the MGH group can begin to see how this will work. Over the next week, this information will be sent to MGH. 3. Documentation Yes. It is needed. What ever can be generated should be. As questions arise, they should be sent to Dan, so that he can both answer them, and prepare a FAQ. 4. Dan Visit to MGH Tentitive: April 27-29 5. Other things... 'Standing' weekly teleconference on Mondays at 1:00 (EST) for ongoing dialog. Transcribed by: --Dave 09:17, 8 Feb 2005 (EST)
http://www.na-mic.org/Wiki/index.php/Meeting_Minutes
crawl-003
refinedweb
699
53.21
If you already have created a custom server control, you would have probably noticed that the intelisense in the HTML view is absent. This article will show you how to get it back. Softomatix published an article about how to create server control: ASP.NET Server Control - Updown Control 1. That's the basics. I'll go on to other topics. My code example is ClickOnce a control that becomes disabled, until postback returns. Add your code Identity to the control TagPrefix. [assembly: System.Web.UI.TagPrefix("Gootvilig.Controls","Gootvilig")] Now when you drop your control, we will have a friendly name in the TagPrefix attribute and not something like TagPrefix="cc1". <%@ Register TagPrefix="gootvilig" Namespace="Gootvilig.Controls" Assembly="Gootvilig.Controls" %> The Intelisense for web controls is in a file named "asp.xsd", that can be found in the path "Program Files\Microsoft Visual Studio .NET 2003\Common7\Packages\schemas\xml". This is the schema for any controls prefixed with "asp:", and their attributes. Furthermore, the ability to display data in the Properties Window is also dependent on this schema. BODYtag: <body MS_POSITIONING="GridLayout" xmlns: Now we will get intlisense support (And also Properties Window support). The next code snippet is the base of the schema for my control. <?xml version="1.0" encoding="utf-8" ?> <xsd:schema <xsd:annotation> <xsd:documentation>Gootvilig Control schema.</xsd:documentation> </xsd:annotation> <xsd:element</xsd:element> <xsd:complexType <xsd:attributeGroup ref=" ButtonDef" /> </xsd:complexType> </xsd:schema> Now we have a problem. The reference to " ButtonDef" is located in "asp.xsd" file with a different namespace from the one I chose for my control. So we have to copy some lines from "asp.xsd" file. The whole schema is in the code download. Now there is complete intelisense for the control. Adding your component to the toolbar is simple. Just right click on the desired toolbox tab, choose "Add/Remove Items�", and browse to your component's assembly DLL. The component name will appear there with the following default icon: . To add your Icon to the toolbox, add this attribute to your class: ToolboxBitmap(typeof(ClickOnce),"Gootvilig.Controls.ClickOnce.bmp") // or ToolboxBitmap(typeof(Bottun)) As you can see, there are two choices. The first choice uses an embedded BMP file and associates it to the class. The file must be 16 X 16 pixels. " Build Action" of the file must be " Embedded Resource". The second choice associates your class with a built in class icon. Now when you drag and drop ClickOnce to our page, lines will be added to our page: (First we have to add a reference to the assembly) <%@ Register</Gootvilig:ClickOnce> The control is designed to support long term round trip actions. In that case we want to avoid any possibility of re-clicking on a button. To achieve this action we need to add some JavaScript code, for the client to execute it before the long time server callback code will take place. Be sure not to replace the " onclick" event, but add your code to the event code chain. Here is the code for implementing this: protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); string currentOnClick = Attributes["onclick"]; // Add javascript onclick handler Attributes["onclick"] += string.Format("document.getElementById( '{0}').disabled = true;",ClientID); } Now we have an additional problem: Because the control was set to " disabled = true", the server callback method doesn�t fire. So I added a call to JavaScript method that is generally added to most ASP.NET pages - __doPostBack() Attributes["onclick"] += string.Format("document.getElementById('{0}').disabled = true;__doPostBack('{0}','');",ClientID); Here is the code that the Page added to support postback operations: <input type="hidden" name="__EVENTTARGET" value="" /> <input type="hidden" name="__EVENTARGUMENT" value="" /> <script language="javascript" type="text/javascript"> <!-- function __doPostBack(eventTarget, eventArgument) { var theform; if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1) { theform = document.Form1; } else { theform = document.forms["Form1"]; } theform.__EVENTTARGET.value = eventTarget.split("$").join(":"); theform.__EVENTARGUMENT.value = eventArgument; theform.submit(); }// --> </script> But the page doesn't always add these snippet code. Only if one of the following controls is embedded in the page, it will call the page internal RegisterPostBackScript() method to accomplish that. The controls that do that are: HtmlAnchor, HtmlButton, HtmlInputButton, HtmlImage, Calendar, CheckBox, LinkButton, ListButton, ListControl and TextBox. Those controls call RegisterPostBackScript() depend on some conditions. Here is the code of Page.RegisterPostBackScript(). The flag _fRequirePostBackScript is for inserting the script later on. internal void RegisterPostBackScript() { if (this._fPostBackScriptRendered); { return; } if (!this._fRequirePostBackScript) { this.RegisterHiddenField("__EVENTTARGET", ""); this.RegisterHiddenField("__EVENTARGUMENT", ""); } this._fRequirePostBackScript = true; } Here is the code to enforce the page to call RegisterPostBackScript(), using reflection: //Call the internal method Page.RegisterPostBackScript() MethodInfo methodInfo = typeof(Page).GetMethod("RegisterPostBackScript", BindingFlags.Instance|BindingFlags.NonPublic); if(methodInfo != null) { methodInfo.Invoke(Page,new object[]{}); } The ClientID, as the name indicates, is good only for client script code. When calling the __doPostBack(), in case our button is located on User Control, we need UniqueIDWithDollars name, which is also an internal method. Our good old friend, reflection, will help here as well: //Code from Control internal string UniqueIDWithDollars{ get { string text1 = this.UniqueID; if (text1 == null) { return null; } if (text1.IndexOf(':') >= 0) { return text1.Replace(':', '$'); } return text1; } } Here is the code to call UniqueIDWithDollars by reflection: //Get the Control UniqueIDWithDollars for the call to __doPostBack() PropertyInfo propertyInfo = typeof(Control).GetProperty( "UniqueIDWithDollars",BindingFlags.Instance|BindingFlags.NonPublic); string uniqueIDWithDollars = ClientID; if(propertyInfo != null) { uniqueIDWithDollars = (string)propertyInfo.GetValue(this,new object[]{}); } Wait! How will the ClickOnce control behave now? It should be enabled after the long server run: So we set Enabled to true in the OnInit method. protected override void OnInit(EventArgs e) { base.OnInit(e); //Enable upon PostBack Enabled = true; } After OnInit, ViewState will take place, so users of our ClickOnce Button, can change it's state to disabled. The demo code illustrates that. See also Eric Plowe's ClickOnce Button Server Control. What did we have here : We saw that, we need to copy the XSD that support our control schema to the "Asp.xsd" folder, then add our namespace to the page BODY tag. But what if we are working with a User Control, where we have no BODY tag? We can do that by enclosing all the HTML code in a tag and add the namespace to that tag.For example: <DIV xmlns: <!-- Here is all the User Control code --> </DIV> Or better in a way that will not rendered to the actual HTML of the client side: <% if(false) { %> <DIV xmlns: <%}%> <!-- Here is all the User Control code --> <% if(false) { %> </DIV> <%}%> If we have the XSD in the solution which we are working on, we don't have to copy that file to the "Asp.xsd" folder! General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/webforms/DesignTimeSupport.aspx
crawl-002
refinedweb
1,123
50.43
expo-sharingallows you to share files directly with other compatible applications. 🚨 Web browser support: expo-sharing for web is built on top of the Web Share API, which still has very limited browser support. Be sure to check that the API can be used before calling it by using Sharing.isAvailableAsync(). 💡 HTTPS required on web: The Web Share API is only available on web when the page is served over https. Run your app with expo start --httpsto enable it. ⚠️ No local file sharing on web: Sharing local files by URI works on iOS and Android, but not on web. You cannot share local files on web by URI — you will need to upload them somewhere and share that URI. expo install expo-sharing To use this in a bare React Native app, follow the installation instructions. import * as Sharing from 'expo-sharing'; trueif the sharing API can be used, and falseotherwise. mimeTypefor Intent(Android only)
https://docs.expo.io/versions/latest/sdk/sharing/
CC-MAIN-2020-16
refinedweb
156
73.17
Source learnvimscriptthehardway / chapters / 51.markdown Potion Section Movement Now that we know how section movement works, let's remap the commands to work in a way that makes sense for Potion files. First we need to decide what "section" should mean for a Potion file. There are two pairs of section movement commands, so we can come up with two "schemes" and our users can use the one they prefer. Let's use the following two schemes to define where Potion sections start: - Any line following a blank line that contains non-whitespace as the first character, or the first line in the file. - Any line that contains non-whitespace as the first character, an equal sign somewhere inside the line, and ends with a colon. Using a slightly-expanded version of our sample factorial.pn file, here's what these rules will consider to be section headers: # factorial.pn 1 # Print some factorials, just for fun. factorial = (n): 1 2 total = 1 n to 1 (i): total *= i. total. print_line = (): 1 2 "-=-=-=-=-=-=-=-\n" print. print_factorial = (i): 1 2 i string print '! is: ' print factorial (i) string print "\n" print. "Here are some factorials:\n\n" print 1 print_line () 1 10 times (i): print_factorial (i). print_line () Our first definition tends to be more liberal. It defines a section to be roughly a "top-level chunk of text". The second definition is more restrictive. It defines a section to be (effectively) a function definition. Custom Mappings Create a ftplugin/potion/sections.vim file in your plugin's repo. This is where we'll put the code for section movement. Remember that this code will be run whenever a buffer's filetype is set to potion. We're going to remap all four section movement commands, so go ahead and create a "skeleton" file: noremap <script> <buffer> <silent> [[ <nop> noremap <script> <buffer> <silent> ]] <nop> noremap <script> <buffer> <silent> [] <nop> noremap <script> <buffer> <silent> ][ <nop> Notice that we use noremap commands instead of nnoremap, because we want these to work in operator-pending mode too. That way you'll be able to do things like d]] to "delete from here to the next section". We make the mappings buffer-local so they'll only apply to Potion files and won't take over globally. We also make them silent, because the user won't care about the details of how we move between sections. Using a Function The code for performing the section movements is going to be very similar for all of the various commands, so let's abstract it into a function that our mappings will call. You'll see this strategy in a lot of Vim plugins that create a number of similar mappings. It's easier to read and maintain than stuffing all the functionality in to a bunch of mapping lines. Change the sections.vim file to contain this: function! s:NextSection(type, backwards) endfunction noremap <script> <buffer> <silent> ]] \ :call <SID>NextSection(1, 0)<cr> noremap <script> <buffer> <silent> [[ \ :call <SID>NextSection(1, 1)<cr> noremap <script> <buffer> <silent> ][ \ :call <SID>NextSection(2, 0)<cr> noremap <script> <buffer> <silent> [] \ :call <SID>NextSection(2, 1)<cr> I used Vimscript's long line continuation feature here because the lines were getting a bit long for my taste. Notice how the backslash to escape long lines comes at the beginning of the second line. Read :help line-continuation for more information. Notice that we're using <SID> and a script-local function to avoid polluting the global namespace with our helper function. Each mapping simply calls NextSection with the appropriate arguments to perform the movement. Now we can start implementing NextSection. Base Movement Let's think about what our function needs to do. We want to move the cursor to the next "section", and an easy way to move the cursor somewhere is with the / and ? commands. Edit NextSection to look like this: function! s:NextSection(type, backwards) if a:backwards let dir = '?' else let dir = '/' endif execute 'silent normal! ' . dir . 'foo' . "\r" endfunction Now the function uses the execute normal! pattern we've seen before to perform either /foo or ?foo, depending on the value given for backwards. This is a good start. Moving on, we're obviously going to need to search for something other than foo, and that pattern is going to depend on whether we want to use the first or second definition of section headings. Change NextSection to look like this: function! s:NextSection(type, backwards) if a:type == 1 let pattern = 'one' elseif a:type == 2 let pattern = 'two' endif if a:backwards let dir = '?' else let dir = '/' endif execute 'silent normal! ' . dir . pattern . "\r" endfunction Now we just need to fill in the patterns, so let's go ahead and do that. Top Level Text Sections Replace the first let pattern = '...' line with the following: let pattern = '\v(\n\n^\S|%^)' To understand how the regular expression works, remember the definition of "section" that we're implementing: Any line following a blank line that contains a non-whitespace as the first character, or the first line in the file. The \v at the beginning simply forces "very magic" mode like we've seen several times before. The remainder of the regex is a group with two options. The first, \n\n^\S, searches for "a newline, followed by a newline, followed by a non-whitespace character". This finds the first set of lines in our definition. The other option is %^, which is a special Vim regex atom that means "beginning of file". Now we're at a point where we can try out the first two mappings. Save ftplugin/potion/sections.vim and run :set filetype=potion in your sample Potion buffer. The [[ and ]] commands should work, but somewhat oddly. Search Flags You'll notice that when you move between sections your cursor gets placed on the blank line above the one we actually want to move to. Think about why this happens before reading on. The answer is that we searched using / (or ?) and by default Vim places your cursor at the beginning of matches. For example, when you run /foo your cursor will be placed on the f in foo. To tell Vim to put the cursor at the end of the match instead of the beginning, we can use a search flag. Try searching in your Potion file like so: /factorial/e Vim will find the word factorial and move you to it. Press n a few times to move through the matches. The e flag tells Vim to put the cursor at the end of matches instead of the beginning. Try it in the other direction too: ?factorial?e Let's modify our function to use a search flag to put our cursor on the other end of the matches for this section: function! s:NextSection(type, backwards) if a:type == 1 let pattern = '\v(\n\n^\S|%^)' let flags = 'e' elseif a:type == 2 let pattern = 'two' let flags = '' endif if a:backwards let dir = '?' else let dir = '/' endif execute 'silent normal! ' . dir . pattern . dir . flags . "\r" endfunction We've changed two things here. First, we set a flags variable depending on the type of section movement. For now we only worry about the first type, which is going to need a flag of e. Second, we've concatenated dir and flags to the search string. This will add ?e or /e depending on which direction we're searching. Save the file, switch back to your sample Potion file and run :set ft=potion to make the changes take effect. Now try [[ and ]] to see them working properly! Function Definitions It's time to tackle our second definition of "section", and luckily this one is much more straightforward than the first. Recall the definition we need to implement: Any line that contains a non-whitespace as the first character, an equal sign somewhere inside the line, and ends with a colon. We can use a fairly simple regex to find these lines. Change the second let pattern = '...' line in the function to this: let pattern = '\v^\S.*\=.*:$' This regex should look much less frightening than the last one. I'll leave it as an exercise for you to figure out how it works -- it's a pretty straightforward translation of our definition. Save the file, run :set filetype=potion in factorial.pn, and try out the new ][ and [] mappings. They should work as expected. We don't need a search flag here because putting the cursor at the beginning of the match (the default) works just fine. Visual Mode Our section movement commands work great in normal mode, but we need to add a bit more to make them work in visual mode as well. First, change the function to look like this: function! s:NextSection(type, backwards, visual) if a:visual normal! gv endif if a:type == 1 let pattern = '\v(\n\n^\S|%^)' let flags = 'e' elseif a:type == 2 let pattern = '\v^\S.*\=.*:$' let flags = '' endif if a:backwards let dir = '?' else let dir = '/' endif execute 'silent normal! ' . dir . pattern . dir . flags . "\r" endfunction Two things have changed. First, the function takes an extra argument so it knows whether it's being called from visual mode or not. Second, if it's called from visual mode we run gv to restore the visual selection. Why do we need to do this? Let's try something that will make it clear. Visually select some text in any buffer and then run the following command: :echom "hello" Vim will display hello but the visual selection will also be cleared! When running an ex mode command with : the visual selection is always cleared. The gv command reselects the previous visual selection, so this will "undo" the clearing. It's a useful command, and can be handy in your day-to-day work too. Now we need to update the existing mappings to pass 0 in for the new visual argument: noremap <script> <buffer> <silent> ]] \ :call <SID>NextSection(1, 0, 0)<cr> noremap <script> <buffer> <silent> [[ \ :call <SID>NextSection(1, 1, 0)<cr> noremap <script> <buffer> <silent> ][ \ :call <SID>NextSection(2, 0, 0)<cr> noremap <script> <buffer> <silent> [] \ :call <SID>NextSection(2, 1, 0)<cr> Nothing too complex there. Now let's add the visual mode mappings as the final piece of the puzzle: vnoremap <script> <buffer> <silent> ]] \ :<c-u>call <SID>NextSection(1, 0, 1)<cr> vnoremap <script> <buffer> <silent> [[ \ :<c-u>call <SID>NextSection(1, 1, 1)<cr> vnoremap <script> <buffer> <silent> ][ \ :<c-u>call <SID>NextSection(2, 0, 1)<cr> vnoremap <script> <buffer> <silent> [] \ :<c-u>call <SID>NextSection(2, 1, 1)<cr> These mappings all pass 1 for the visual argument to tell Vim to reselect the last selection before performing the movement. They also use the <c-u> trick we learned about in the Grep Operator chapters. Save the file, :set ft=potion in the Potion file and you're done! Give your new mappings a try. Things like v]] and d[] should all work properly now. Why Bother? This has been a long chapter for some seemingly small functionality, but you've learned and practiced a lot of useful things along the way: - Using noremapinstead of nnoremapto create mappings that work as movements and motions. - Using a single function with several arguments to simplify creating related mappings. - Building up functionality in a Vimscript function incrementally. - Building up an execute 'normal! ...'string programmatically. - Using simple searches to move around with regexes. - Using special regex atoms like %^(beginning of file). - Using search flags to modify how searches work. - Handling visual mode mappings that need to retain the visual selection. Go ahead and do the exercises (it's just a bit of :help reading) and then grab some ice cream. You've earned it after this chapter! Exercises Read :help search(). This is a useful function to know, but you can also use the flags listed with the / and ? commands. Read :help ordinary-atom to learn about more interesting things you can use in search patterns.
https://bitbucket.org/sjl/learnvimscriptthehardway/src/f28776bb4531/chapters/51.markdown
CC-MAIN-2015-27
refinedweb
2,019
73.47
Must be a bad month for programmers. I'm starting to feel nostalgic now. I woke up early morning to find that Dennis Ritchie, the inventor of C and Unix passed away yesterday. I remember when I first started programming in C as a kid. I came from a BASIC background. Atari BASIC was cool, easy, straight forward and I kept discovering all its other variations - GWBASIC, QBASIC, Quick BASIC. Each progression let me do newer things. I thought I was living the life. And then I hit upon C and I instantly fell in love with it - the control over memory and other parts of your computer. Crashing your computer made you feel cool back then. You fell in love with the amazing syntax. No more line numbers. The ability to create your own datatypes. This whole new world was simply amazing. There were very very few people who inspired me in my teens to make meI decide that instead of being a cool fighter pilot, I wanted to be a programmer - Bill Gates was one of them. The other one was Dennis Ritchie. Dennis because I wanted to know what Bill Gates used to get BASIC, MS DOS and Windows. And the buck stopped there because I couldn't find out what Dennis Ritchie used. He was the man though he was less acknowledged but was equally if not more influential and revolutionary. Ritchie, along with Ken Thompson created and designed C and UNIX. Successors like C++, Java, C#, Objective C used the semantics, syntax and ideas from C while variants of UNIX such as Linux and Apple's iOS run desktops to mobile phones to datacenters today.. You would expect that going back to those days would give programmers brought up in this generation (web oriented) or the last one (desktop oriented) a completely unique perspective but when I read an interview with Dennis Ritchie which I blogged about a few months ago, some of the principles that drove him back then still drive programmers today. Looks like we are living in a time when we will witness the pioneers of the modern computing era make way for the new ones .i.e the googles, the facebooks and the twitters. But all these were built on the foundations they laid. We owe it to these guys big time. I owe my career and the fact that I actually enjoy my job to Dennis Ritchie and his datatypes. RESPECT. C 'ya later. // good bye world program #include <studio.h> int main (void) { printf("Goodbye World"); return 0; } not only that Profs(not all) are not that great even though they are Phd's. i tell my kids you will see the real meaning of competition when you go back to India! Career wise I was also inspired by many people, but the real heroes are my parents. " int main(int argc, char* argv[]) main program signature is correct (I hope I don't get into trouble over use of the word ""signature"" now). Thinking in terms of Kernighan & Ritchie C, this form would not only be conspicuously missing, but you'd not likely find parameters enclosed within the parentheses. I think standards are very important, but it seems criminal to teach that only one form is ""correct."" As apparent, the only consideration that occurred to me at the time was that I couldn't think of an instance in which you'd have to accept command-line parameters to a program that simply said ""Goodbye."" " cheap business phone calls
https://it.toolbox.com/blogs/georgealexander/dennis-ritchie-another-hero-and-pioneer-leaves-us-101411
CC-MAIN-2018-17
refinedweb
591
72.56
A class is a template for an object. It describes the attributes and general behavior of an object. For example, the Sun (not to be confused with the company), an object, is an instance of a class called Star. There are certain characteristics that are shared by all stars, such as temperature, size, and color. A star represents a generic set of suns. Each instance of the Star class, such as our own sun or Alpha Centauri, will have different temperature, size, and color values. Thus, we can think of a class as a blueprint for an object which contains placeholders for values (e.g., size, color, temperature). An object is a concrete example of that object with specifiable values for its attributes (e.g., size = 13, color = yellow, temperature = 8000K.). Java has several keywords for class specification, encapsulation, and manipulation, as shown in Table 3: Table 3: Class Related Keywords These will be discussed further in the column. Building Classes in Java The Star class can be specified in Java with the following simple line of code: class Star { } To give the class more character, add the following lines of code between the braces ({ }) as demonstrated below: class Star { int size; int temperature; Color color; } Now we have a class with three attributes: an integer value that indicates the size and temperature of a particular Star object. The color of a specific Star instance is also an instance of a class, the Color class, which is part of the standard Java Abstract Window Toolkit (AWT) package. Declaring a class instance is easy. It is the same as with primitive types. To declare an object of class Star called myStar, do the following: Star myStar; Declaring a Star, however, does not create an instance of a Star . In other words, no memory space has been requested for the Star variable. A Star is instantiated by using the new keyword: Star myStar = new Star(); or Star myStar; myStar = new Star(); Java puts new objects in a memory area called the heap. Each time you create an instance of a class, heap space is allocated for that object. Java uses packages to group related classes, interfaces, and exceptions together in a common repository. For example, the String class is part of the java.lang package, and the Color class is part of the java.awt package. A list of all packages and their specifications is available at If a class exists inside of another package, then you must import the class before you can manipulate it. The exception to this is the java.lang package, which is a default package for all Java class files. The import statement has the following format: import packagename.<packagename/classname/wildcard>; Where packagename is the name of a java package. The name following the first package name may be another package name, a class name, or a wildcard that signifies all classes in the specified package should be imported. All imports must appear before a class declaration. The following is an example of class importation using various import techniques: import personal.MyClass; // imports MyClass from the personal package import java.util.Hashtable; // imports the Hashtable class from // the java.util package import java.awt.*; // imports all classes in the java.awt // package (wildcard) The first and second import examples are the preferred method of class importation. While using wildcards is acceptable, it does prevent developers from readily viewing class dependencies. You can also reference packages explicitly instead of importing the package. This technique is most appropriate when you only need to use a class one or two times or two seperate packages both have a class with the same name. The following illustrates the use of explicit package referencing : class MyClass extends java.util.Hashtable { ... } Importing classes is more suitable than explicit package referencing for most situations and provides for better code readability. If you try to compile the Star class with the Color attribute without importing java.awt.Color or java.awt.* you will get an error message indicating that the Color class cannot be found. Add the following line of code before the class declaration in the Star.java file: import java.awt.Color; Imports must appear somewhere before class declaration. If you create an instance of the Star class as it is currently written, you will be able to modify the attribute values. Total access to the class attributes is granted to your application. This is in opposition to the idea of information hiding with objects. The primary purpose of object-oriented design is to prevent promiscuous alteration of encapsulated data. Java provides four methods of controlling access to class members, as shown in table 4: Table 4: Class Access Control Private members of a class cannot be accessed outside of the class. Only members inside the class can manipulate the values of private data or call private methods. Protected members will be discussed in more detail when we look at inheritance. Briefly, protected members of a class are accessible from other classes inside the same package and also from classes that inherit from the protected members' associated class. Public members are available to all classes. Normally, the public accessor method is applied to constant data or methods. The default access control mechanism restricts class data visibility to only classes in the same package or derived classes. Since the Star class data members do not have any explicit access specifiers, the default specifier is used. An access specifier precedes the declaration of a variable, constant, class, or method. Make the data members of the Star class private by preceding each variable declaration with the private keyword as follows: private int size; private int temperature; private Color color; A class can have static data members. A static data member is a class attribute that is shared among all instances of a class. A commonly used static data member is a count variable that keeps a count of the number of instances of a class. Such a data member would be declared just like any other variable, and can be private, protected, or public . Just for fun, add the following line of code to the end of the Star class: private static int count; Class member access specifiers prevent programmers from changing encapsulated data values directly. So, how does a programmer change the value of an inaccessible member? She does so through the use of methods. Methods are the communication mechanisms for objects. They allow a developer to issue commands to an object that change the object's state or behavior. Here is the Star class with accessor methods added: class Star { public Color getColor() { return color; } public int getSize() {return size; } public int getTemperature { return temperature; } public void setColor(Color newColor) { color = newColor; } public void setSize(int newSize) {size = newSize; } public void setTemperature(int newTemp) { temperature = newTemp; } private int size; private int temperature; private Color color; } Accessor methods provide a means of indirectly altering the values of an object's private members. The format of a class method is as follows: [AccessSpecifier] [Modifier] ([Parameters]) { [Code] } AccessSpecifier can be private, protected, or public. If ommited, the default access control is used. Modifiers are optional, but may include any of the following keywords: final, native, static, and synchronized . The final and static keywords will be explained later. All methods must have a return type. This is the primitive datatype or class returned by the method after a method completes a call. The return type void indicates that the method does not return any value. The name of a method can be any legal Java name as previously discussed. Use appropriate Java style for naming as described in Naming Conventions , which was in Part 1 of this column. Parameters are enclosed within parentheses. The are declared just like any other variable (e.g., int newValue, Star star, etc.). Multiple parameters are seperated by a comma (","). A left brace ("{") follows the parameter list. This starts the method code block. A right brace ("}") ends the code block and appears on a seperate line immediately following the last line of code in the method. Listed below are a few examples of class methods: private void initialize() { // a private method with no return type. } public final Star getStar(String name) { // a public method with a modifier (final) and class // Star as a return type. The method parameter is a String // that represents the desired star's name. } public void send(Object[] message, int count) { // Another public method with no return type passed // an array of objects and an integer variable) } You may be wondering why we use methods to change the values of an object. Why not just change the values directly? As previously mentioned, information hiding is an important aspect of object-oriented programming. The programmer should not be concerned about the data inside an object. She should be primarily interested only in the behavior of the object, i.e., what can she do with the object? Removing the unessential details also allows the object's creator more flexibility in the internal attributes of the object. For example, the designer of a Car class might later decide that a float variable rather than an integer variable would be a better format for the Car's speed attribute. Altering the representation of the Car's speed does not change the appearance of the Car class to a developer. Instances of Car still have getSpeed() and setSpeed() methods. Thus, the outward behavior of the class remains the same. Consequently, get and set methods are very commonly used. Static methods are used to access static data members. To declare a static method, just add the static keyword after the access specifier in a method declaration. To access the count variable in the Star class, add the following method: public static int getCount() { return count; } Method parameters are used to pass information to an object from the outside world. The setSize() method, for example, passes an integer value from outside the class into the class method. The class method can now manipulate the newSize variable. In Java, primitive types are passed by value while objects are passed by reference. Variables passed by value can have their contents changed without any noticeable difference outside the class. However, variables passed by reference can not only have their contents changed, but the change is effective outside the class method. Methods can return values, either primitive types or classes. You return a value from a method by specifying the return type in the class declaration and using the return keyword in the method code block. The get methods in class Star demonstrate how to return values from methods. Constructors are methods that allow you to customize an object at the moment of its instantiation. Without constructors, you'd have to explicitly set each attribute of an object using multiple accessor methods. For example: Star sun = new Star(); sun.setSize(1390000); sun.setColor(Color.yellow); sun.setTemperature(5800); If you have to create many objects, this repetitiveness can become very tiresome. A better approach is possible through the use of constructor methods. Constructor methods permit the passing of parameters to an object during its creation. Using a constructor, the previous code can be reduced to a single line: Star sun = new Star(1390000, Color.yellow, 5800); The format for declaring a constructor is as follows: [AccessSpecifier] ([Parameters]) { [Code] } Constructors are optional. If you do not include constructors in your code, Java generates a default constructor that initializes all primitive data members to zero and all object members to null. A null reference means that a particular object does not reference anything (i.e., has not been instantiated or assigned to another object). Add the following lines of code to the Star class just before the getter and setter methods: Star() { this(0, 0, Color.yellow); } Star(int newSize) { this(newSize, 0, Color.yellow); } Star(int newSize, int newTemp) { this(newSize, newTemp, Color.yellow); } Star(int newSize, newTemp, newColor) { size=newSize; temperature = newTemp; color = newColor; } The Star class now has four constructors: the first constructor is a default constructor and the rest are constructors that accept a certain number of parameters. When a class has multiple constructors, the default constructor must be explicitly defined; otherwise, you cannot allocate objects using the default constructor (e.g., new Star()). Notice the use of the keyword this. This is another way to refer to the current class from within a method. In the Star class definition, this is used to call the class constructor that expects three parameters. So: this(newSize, newTemp, Color.yellow); calls the fourth constructor in the Star class. The this keyword can also be used to refer to data members within its enclosing class. For example, inside of a Star method you can write: this.size = 10; This is commonly used to resolve name conflicts in methods. For example: public void setSize(int size) { this.size = size; } It is preferable, however, to make the names of parameters distinct from class data member names, as is done in the Star class. Inheritance is a technique whereby a class can inherit the attributes and methods of another class. The technical term for this is specialization . As the name implies, specialization defines more specific behavior for a class. It represents the "is a" relationship between classes. For example, a Person class has general attributes that apply to all people. A more specialized version of a Person, such as Employee , would have the same attributes as a Person, plus other data members and methods that are applicable to all employees (salary, etc.). Simply put, an employee is a person. Inheritance in Java is specified using the extends keyword. You would create an Employee class which is an extension of the Person class as follows: class Employee extends Person { // methods and attributes here } Protected members of a superclass are available to the subclass. They can be accessed without the use of getter and setter methods. This is illustrated below: In Person.java: public class Person { public String getName() { return name; } public void setName(String newName) { name = newName; } protected String name; } In Employee.java: public class Employee extends Person { public void changeSuperName(String newName) { name = newName; } } Some classes are so general that they should not be allowed to have specific instances. These classes are called abstract classes. For example, consider a Shape class. In the real-world, you would not draw a shape. Instead, you'd draw a square, rectangle, or circle. However, these are all specializations of a shape. A Shape class would never be used to create an object, but would instead provide a framework for more specific shapes. An abstract Shape can be constructed as follows: abstract class Shape { // shape methods here. } An abstract class may have methods just like an ordinary class, but additionally might have abstract methods. An abstract method is used for methods that are too general for a specific implementation but may be used to perform a more specific function in a derived, concrete class. As an illustration, consider the following Shape class declaration: abstract class Shape { public abstract void draw(Graphics g); } Since many different representations can be used for a shape (squares, rectangles, octagons, etc.), it is impossible to implement a generic draw() method that can work for all types of shapes. However, a class derived from Shape, such as Square, can implement the generic draw() method to display itself. Certain restrictions apply to abstract method declaration: Interfaces are similar to abstract classes, except that, unlike abstract classes which can have some methods which are fully implemented, none of the methods in an interface can have an implementation. Furthermore, interfaces can only have final, static data members. At first, these restrictions may appear to demote the usefulness of an interface. However, interfaces are powerful abstractions. Consider the Shape class discussed earlier. In the most recent JDK, the Shape class (in the java.awt package) is declared as an interface with a single method, getBounds, which returns a Rectangle object. This rectangle object provides access to its x, y, width, and height attributes (while this may seem to violate the rule of encapsulation, it is actually justifiable in this case). A class which implements this interface can specify how these fields are set and what they mean. For example, the Polygon (also in the java.awt package) class implements the Shape interface. An interface is declared as follows: interface [extends [InterfaceName]] { // final, static attributes and // methods that must be implemented by a class or will // be inherited by another interface that extends this interface } Notice that an interface can inherit from another interface. A class cannot inherit from an interface or vice versa. A class implements an interface by using the implements keyword, as illustrated below: public class Polygon extends Object implements Shape { // See java.awt.Polygon for class attributes and methods. } The extends clause can be omitted from the above, since all classes inherit from the class Object by default. It was explicitly written to illustrate that a class can inherit from another class and simultaneously implement an interface. A class can also implement multiple interfaces. The Polygon class actually implements two interfaces: public class Polygon extends Object implements Shape, Serializable; The serializable interface allows an object to write itself to a stream. We will discuss this mechanism in a later column. You can find out if an object belongs to a particular class by using the instanceof keyword. if(myObject instanceof MyClass) { // Perform some action if true. } As illustrated above, this keyword tests if the object on the left is an instance of the class specified on the right. The expression will return true or false depending on the outcome of the test. A good example of when you'd want to use instanceof is inside the methods of an employee list that is a linked list which can contain only instances of class Employee, such as: public class EmployeeList implements List { // some list methods public void add(Object data) { if(data instanceof Employee) super.add(data); } } This ends part 2 of a two part introduction to Java. In the next issue, we'll further explore the Java language, applets, and the Java class libraries. George Crawford III is a software engineer at MPI Software Technology, Inc. and completing:
http://www.acm.org/crossroads/xrds4-3/ovp.html
crawl-001
refinedweb
3,054
55.64
Docs | Forums | Lists | Bugs | Planet | Store | GMN | Get Gentoo! Not eligible to see or edit group visibility for this bug. View Bug Activity | Format For Printing | XML | Clone This Bug On both sparc and on amd64, with tk-8.4.19 an attempt on python to use the Tkinter module from import Tkinter results in a failure; I'll attach a traceback demonstrating the problem from the pysol package: 1) This is dev-lang/python-2.5.2-r7; 2) Rebuilding python for tk-8.4.19 makes no difference; 3) But after downgrading to {tcl, tk}-8.4.18, everything is fine again. I'm reporting against tk because the problem appears with the {tcl, tk} version change. Created an attachment (id=171746) [edit] Trace file (on sparc) of the Tkinter failure with the tk-8.4.19 upgrade This little traceback from python shows the problem it has using Tkinter with tk-8.4.19. This trace is from a sparc system, but results are the same on amd64. Test program is the pysol solitaire games package, and it has been completely stable for many years (although perhaps not as a Gentoo package). pysol is pure python, using tk as its took kit. Adding python people in case this is really theirs. which version of tk exactly doesn't spots this problem? is really 8.4.18, or perhaps it is 8.4.18-r1? because since 8.4.18-r1 ebuild includes a patch that *should* have solved this problem. please also tell me your version of x11-proto/xproto. On both failing systems, xproto-7.0.13. But here we go: On the failing systems, genlop tells us: Sun Oct 26 14:09:15 2008 >>> dev-lang/tk-8.4.19 Changelog tells us: 27 Oct 2008; Federico Ferri <mescalinum@gentoo.org> +files/tk-8.4-lastevent.patch, +tk-8.4.18-r1.ebuild, tk-8.4.19.ebuild: adding patch 8.4-lastevent, fixes bug #225999 And if we rebuild tk-8.4.19 to include that patch, everything is fine. So for me, it was fixed a day after I installed the version of tk which fails. For me, this is fixed; I'll leave it to you to close in case there is something else lurking in the background. I guess this argues that when a very small change fixes something, a version bump is a good idea. Oh, there is a misprint in the ebuild for tk-8.4.19 --- you have >=x11-proto/xproto-7.0.3 but you need: >=x11-proto/xproto-7.0.13 ok, so you installed tk-8.4.19 in the meanwhile of two commits. nice timing! ;) I rev bumped the ebuild, in order to eliminate this problem, and I corrected the typo. I'll mark this bug as a duplicate of bug #225999 just for tracking purposes. thank you *** This bug has been marked as a duplicate of bug 225999 ***
http://bugs.gentoo.org/246774
crawl-002
refinedweb
495
77.13
3/20/2015 Victory for Import Substitution: Russia begins to export meat to the EU Translated from Russian by J.Hawk ZAO Krasnobor, a Russian agribusiness specializing in turkeys and located in the Tula Region entered the list of exporters to the European Union, according to the Rosselknoznadzor state agency. Krasnobor is the first Russian business to receive the permit to export turkey meat to the EU, notes RIA Novosti. Rosselkhoznadzor already announced about two agribusinesses in Belgorod Region that received a permit to export poultry meat (chicken, duck) to the EU. However, the turkey meat will arrive in the EU first. Last year, in response to US and EU sanctions, Russia undertook measures aimed at import substitution. Last summer the Russian Federation launched a campaign of food import substitution. - Advertisement - In the Spring 2015, Hungary, Bulgaria, and several other countries once again demanded that the anti-Russian sanctions be lifted in order to end Russia’s food embargo. J.Hawk’s Note: Beef and pork will take a little while longer, but if this trend continues, Russia’s domestic meat production will continue to grow. It’s just that poultry production can be increased almost overnight due to the birds’ rapid growth and comparably short lifespan. The ruble devaluation of late last year must be viewed with the above in mind. It’s the fact that the ruble is very weak relative to the Euro that makes Russian exports, and not just of food, highly competitive. The criticism that the Director of the Russian Central Bank Elvira Nabiullina received after the fall of the ruble was entirely off the mark, as it failed to note that no import substitution could take place at the ruble exchange rates of a year ago. Yes, the devaluation did hurt people who got used to imported goods. That’s the reason the Russian “liberal opposition” hates Putin and his team—it’s simply fashionable to be seen consuming imported Western goods of all kinds. The process has moved so far that even if the sanctions were lifted tomorrow, EU imports would not return to Russia’s markets, simply because it’s not the sanctions but the value of the ruble that’s keeping them out. Notice that the EU’s own response to its economic crisis was “quantitative easing”, which is a devaluation by another name. Too little, too late…
https://fort-russ.com/2015/03/victory-for-import-substitution-russia/
CC-MAIN-2021-04
refinedweb
397
58.52
Asked by: Assistance with 837I/P Multi-Single ST-SE Outbound Messsages Question So I have a requirement to send outbound 837I/P messages to various customers. Some of them require Single ST/SE messages, while other require Mult ST/SE segments. The only hit of processes that I have seen around this is this article by Eric Stotts Since I can't deploy both the Single and the Multi ST/SE messages to the same environment (without changing the namespaces at least), my understanding is that I can deploy the Single ST/SE schema, and leverage the Microsoft.BizTalk.Edi.BatchingOrchestration.BatchingService process to actually take 2 or more Single schemas and actually create a Multi ST/SE. If anyone has additional information for me please let me know, or tell me the error in my logic... All replies Hi Kevin, You are right.You can use inbuilt BizTalk Batching orchestrations to batch multiple single transactions or change the namespace and use both of them with in the same environment. Thanks.. Surya Thanks... SPN How do I close the batch. Or otherwise, indicate that the batch is complete? So that it will send the batch out. Hi Kevin, You have 3 different options in the party for the same. 1.)Scheduling----You can have a time interval to release the batch 2.)No of Transactions:-You can release batch based on no of transactions either in interchange or group. 3.)No of Characters:-The release can be based on the no of characters in the batch. The final option is to release an external trigger called PAM Control Message.You have to create this message and drop in the message box to release the batch. Thanks... SPN - Proposed as answer by SPN Biztalk Tuesday, June 7, 2011 10:58 AM
https://social.msdn.microsoft.com/Forums/en-US/73d1f228-cbf6-4926-b63a-24870138e780/assistance-with-837ip-multisingle-stse-outbound-messsages?forum=biztalkediandas2
CC-MAIN-2020-45
refinedweb
301
63.29
Despite whether you like spaces or tabs, semicolons or none, single or double quotes, we can all agree on the importance of consistency and clarity in a code base. In this article, we’re going to go over the reasons why we should utilize a linter like ESLint and how to customize it with Create React App. Projects created using Create React App have linting with ESLint already working and configured out of the box with sensible defaults. For most scenarios that means that you don’t have anything else to do and everything will just work. The following article should come-in handy in cases where you’d want to customize the linting rules. Also, This article discusses customizing linting rules by ejecting from Create React App, but there’s also an alternative solution using react-app-rewired and react-app-rewire-eslint. 🐊 Alligator.io recommends ⤵Fullstack Advanced React & GraphQL by Wes Bos Why Lint? Coding always leaves room for errors, especially with loosely typed languages like JavaScript. By implementing a linter in our code editor and our project, we can save time by finding an error before we even execute our code. In this article, we’re going to go over why linting is a life saver and also how to customize the linter in a Create React App project. Local linting vs project linting Most popular code editors either automatically include a linter for the language you’re using or offer multiple extensions so that you can configure how you prefer to lint locally. While linting locally can and will save us time, there is always the bigger picture - like different code editors and dev environments. In this article, we’re going to focus our attention specifically on the project level with ESLint. Customizing Create React App and ESLint Let’s use Create React App to quickly setup a React project. If you aren’t up to speed and need a little help getting started, check out our spiffy article Getting Comfortable with Create React App. In the terminal run: $ create-react-app linter-demo $ cd linter-demo $ npm start Voila, we've now got a project to test. Like most things in development, Create React App is practically magic right up until you’re ready to get into some nitty gritty customizations. One drawback with the defaults in a project created using Create React App is that you can only configure ESLint by ejecting or forking the project which leaves a lot to be desired for most advanced developers. Sadly you can’t integrate Prettier, change rules to fit your team’s style and you’re locked into the version Create React App deems as the most stable version despite what releases might solve your unique problems. It leaves a lot to be desired in terms of flexibility. There are even complaints/issues that Create React App disables the rules that it suggests following. How Do We Get Around That? First of all we need to eject. If you’re deep in a project, we’d suggest doing some research on the consequences for your specific project. Essentially when we eject, we no longer get updates on our project from the Create React App core. It’s certainly not the end of the world, though, and it allows for more linting customization. A good analogy of Create React App versus an ejected app is “It’s kind of like pulling in Bootstrap CSS via CDN as opposed to downloading the source code and injecting it directly into your project.” That is, we now have to make manual changes to our packages. Once we’re confident and comfortable let’s get on with it! In the terminal run: $ npm run eject Next just hit y and we’re ready to get rolling. Linter Installation From your root folder, install the following linter packages: $ npm install --save-dev eslint eslint-loader babel-loader babel-eslint eslint-plugin-react These package extensions work together in our React project to provide linter feedback for JavaScript, JSX and React. - eslint is the core JavaScript linter. - eslint-loader tells webpack that you want to use eslintin our build - babel-loader transpiles our code with webpack - babel-eslint provides linting for valid ES6 code - eslint-plugin-react extends ESLint rules to cover React Next create an ESLint file to configure our settings. This file is where you can add, remove and edit configurations. In the terminal run: $ touch .eslintrc If we don’t quite know where to start, style guides like eslint-config-airbnb allow us to configure our project similar to industry leaders like Airbnb. All that we need to do to implement their style guide is install the corresponding packages. Since their rules are a little strict to start with, we’re going to start with something a little simpler. Place the following in .eslintrc file you just created: .eslintrc { "parser": "babel-eslint", "plugins": [ "react" ], "rules": { "no-undef": [ 1 ], } } Show Me the Money! Let’s start with the obvious! Spotting errors. 🙈 If we don’t have a linter setup in our project, it’s difficult to spot errors until the code is compiled. Can you find the errors we added below? App.js import React, { Component } from 'react'; import ReactLogo from './logo.svg'; import './App.css'; class Demo; You're absolutely right! We changed our logo's name in the import but forgot to change it in the src prop. We also changed our class name but forgot to change it in the export. Without a linter, the problem might be hard to identify. The correct version should look like this:; Fairly easy to miss, right? 🤔 With a linter, an error would appear immediately and tip us off that there’s a big problem. Much like how spellcheck gives a squiggly red line when you misspell a word, the linter will give you a squiggly red line when an error is present. If we hover over the related squiggle the linter will give us more information on the specific error and even provide a link for more info on that specific rule. Setting some standards for clear, beautiful code! 😍 Linters like ESLint allow us to create rules for how we want our code to look. These rules include anything from enforcing consistent indentation to requiring spaces in our curly braces. We've all seen, or even wrote, code that resembles something like the example below. 🤫; Imagine if the codebase was large. Digging through the code would seem daunting, frustrating and might make you want to call-in sick 😷🤢. If we are using linting rules to prevent this, the linter will quickly let us know that this isn’t acceptable. Configuring Specific Rules Linting rules are far from black and white. They're actually quite flexible. One of the driving principles of ESLint is that it empowers the developer to decide their own rules and does do not enforce or encourage any specific standards. All rules can be required, used as a warning, modified or even disabled. In ESLint not only can you completely customize a single rule, but you can disable an entire file, a line, or even just a rule related to a specific line in our code. Earlier we created an .eslintrc file with a couple simple rules. Let’s add some more complex rules to see what happens to our file. Be sure to close and reopen your `App.js` file or reload your editor window to see the linter changes reflected. .eslintrc { "parser": "babel-eslint", "plugins": [ "react" ], "rules": { "space-in-parens": [ 0, "always" ], "template-curly-spacing": [ 2, "always" ], "array-bracket-spacing": [ 2, "always" ], "object-curly-spacing": [ 2, "always" ], "computed-property-spacing": [ 2, "always" ], "no-multiple-empty-lines": [ 2, { "max": 1, "maxEOF": 0, "maxBOF": 0 } ], "quotes": [ 1, "single", "avoid-escape" ], "no-use-before-define": [ 2, { "functions": false } ], "semi": [0, "never"], "prefer-const": 1, "react/prefer-es6-class": 0, "react/jsx-filename-extension": 0, "react/jsx-curly-spacing": [ 2, "always" ], "react/jsx-indent": [ 2, 4 ], "react/prop-types": [ 1 ], "react/no-array-index-key": [ 1 ], "class-methods-use-this": [ 1 ], "no-undef": [ 1 ], "no-case-declarations": [ 1 ], "no-return-assign": [ 1 ], "no-param-reassign": [ 1 ], "no-shadow": [ 1 ], "camelcase": [ 1 ], "no-underscore-dangle" : [0, "always"], } } After you reopen the file, it should look something like this: Tell me more about some of those rules… Since we could spend hours explaining linter rules, we selected our top five to highlight and explain. - quotes: allows you to define strings in one of three ways: single quotes, double quotes, or backticks. - semi: enforce or disallow semicolons - react/jsx-curly-spacing: enforce or disallow spaces inside curly braces in JSX props and expressions - react/jsx-indent: validates indentions (spaces, tabs) - no-undef: disallows undefined variables For more info on rules and how to modify them, check out eslint and eslint-plugin-react’s rules. Oof But So Many Things to Fix! So you have a giant project and didn’t know about ESLint, eh? Now you’re linting and are somewhat terrified with the hundreds or even thousands of errors you’re seeing? Not to fear! ESLint has a feature where you enter the file path + eslint --fix and it automatically fixes every simple error that won’t cause a dumpster fire in our project. To try this in our current project, run the following from your terminal: $ eslint --fix src/App.js The result tells us that there is one remaining error. Though we’d love for eslint --fix to be able to fix everything in our file, it has the capability to do some damage. All projects are not created equally so ESLint treads lightly with some fixes. What about that last error? The last error, class-methods-use-this make a good point, class methods should use this to refer to the current class. We will probably want to change that later but since our project is brand new, we’re just going to ignore it for now. We could go about ignoring this in three different ways: - Disabling the rule across the project - Disabling the rule in that file - Disabling the rule in the line above the code block Since this is something that we probably want in other files, we don’t want to disable it across the project and since we want it to be found pretty easily we’re just going to disable it for this specific file. To disable the rule, add the the comment below on line one of your file. /* eslint-disable class-methods-use-this */ Life-Saving Specific Benefits We brainstormed with a few developers on how ESLint has saved them time and here’s a short list of what we came up with. - Do not pass go, do not collect…: The linter can stop the build if the project has any errors. - Stop those old habits!: Did you really just say var?! ESLintwill quickly remind you if you need to use letor const - Smaller Packages: You have a const, or a var… but it’s not used? Guess what? It’ll let you know that you haven’t used it! - Hate repeating yourself?: Good news, ESLintwill remind you to use object destructing! - Undefined…: Need I say much more? We’ve all had our fair share of frustration with anything undefined related. ESLintnotifies you when you have an undefined variable in the file. - Missing Something?: Maybe you’re looking at a colleague’s file and wondering why something isn’t working… When you hit that file, ESLintwill let you know that you’re missing something, an npm package. It’ll even give you the line to install from the terminal. 👉 Good news. Now that we have customized ESLint rules for our project, we never need to have the tabs vs spaces debate again!
https://alligator.io/react/linting-react/
CC-MAIN-2019-09
refinedweb
1,971
61.67
Fundamental Types C++ contains the same familiar keywords (e.g., int) that you recognize from C#. This is unsurprising given that both are C-like languages. There is, however, one potential landmine that can throw you into trouble. While C# explicitly defines the sizes of fundamental types (a short is a 16-bit integer, an int is a 32-bit integer, a long is a 64-bit integer, a double is a 64-bit double-precision IEEE 754 floating point number, etc.), C++ makes no such guarantees. The smallest fundamental unit in C++ is char, which only needs to be at least large enough to hold the 96 basic characters that the C++ standard specifies, plus any other characters in the implementation’s basic character set. In theory, some implementation of C++ could define a char as 7 bits or 16 bits … almost anything is possible. But in practice you don’t need to worry too much about a char being anything other than 8 bits (the equivalent of the byte or sbyte type in C#), which is its size in Visual C++. In C++, char, signed char, and unsigned char are three distinct types. All three are required to take up the same amount of storage in memory. So a char in practice is either signed or unsigned. Whether it is signed or unsigned is implementation defined (see the sidebar). In Visual C++ the char type is, by default, signed. But you can use a compiler switch to have it treated as unsigned instead. In GCC, whether it is signed or unsigned depends on which CPU architecture you are targeting. The signed integer types, in size order from smallest to largest, are: - signed char - short int - int - long int - long long int The only guarantee of the size of each of these integer types is that each one is at least as large as the next smallest integer type. In Visual C++, an int and a long int are both 32-bit integers. It is only the long long int that is a 64-bit integer. Note: You can simply write long or long long; you do not need to write long int or long long int, respectively. The same is also true for short int (i.e. you can just write short). The short type is a 16-bit signed integer in Visual C++. Each of the integer types has a corresponding unsigned integer type. You just put the keyword unsigned in front to get the unsigned version (except for signed char, which you change to unsigned char). If you need to ensure that you are using specific sizes, you can include the C++ Standard Library header file cstdint (e.g., #include <cstdint>), which defines, among other things, the types: - int8_t - int16_t - int32_t - int64_t - uint8_t - uint16_t - uint32_t - uint64_t These types have their use, but you will find that most APIs do not use them; instead, they use the fundamental types directly. This can make your programming confusing, as you constantly need to check the underlying fundamental type to ensure you do not end up with unintended truncation or expansion. These types might come into use more, so I recommend checking for their usage in major libraries and APIs from time to time and adjusting your code accordingly if they become widely adopted. Of course, if you absolutely need a variable to be, for example, an unsigned 32-bit integer, you should certainly make use of uint32_t and make any adjustments for API calls and portability as needed. Floating-point numbers are the same as far as size order rules. They go from float to double to long double. In Visual C++, float is a 32-bit floating-point number and double and long double are both 64-bit floating point numbers (long double is not larger than double, in other words). C++ does not have any native type that is comparable to C#’s decimal type. However, one of the nice things about C++ is there are typically a large number of free or inexpensive libraries that you can license. For example, there’s the decNumber library, the Intel Decimal Floating Point Math Library, and the GNU Multiple Precision Arithmetic Library. None are exactly compatible with C#’s decimal type, but if you are writing for Windows systems only, then you can use the DECIMAL data type to get that compatibility if needed, along with the Decimal Arithmetic Functions and the Data Type Conversion Functions. There is also a Boolean type, bool, which can be true or false. In Visual C++, a bool takes up a byte. Unlike in C#, a bool can be transformed into an integer type. When false, it has an integer-equivalent value of 0, and when true, it has a value of 1. So the statement bool result = true == 1; will compile and result will evaluate to true when the statement has been executed. Then there is the wchar_t type, which holds a wide character. A wide character’s size varies based on the platform. On Windows platforms, it is a 16-bit character. It is the equivalent of C#’s char type. It is frequently used to construct strings. We will discuss strings in another chapter since many variants can be used for strings. Lastly, there is the void type, which is used the same way it is in C#. And there is a std::nullptr_t type, which is messy to explain properly, but basically is there to be the type of the nullptr literal, which is what you should use instead of NULL or a literal 0 (zero) to check for null values. Enumerations Enumerations are fairly similar to each other in C++ and C#. C++ has two types of enums: scoped and un-scoped. A scoped enumeration is defined as either an enum class or an enum struct. There is no difference between the two. An un-scoped enumeration is defined as a plain enum. Let’s look at a sample: Sample: EnumSample\EnumSample.cpp #include <iostream> #include <ostream> #include <string> #include "../pchar.h" enum class Color { Red, Orange, Yellow, Blue, Indigo, Violet }; // You can specify any underlying integral type you want, provided it fits. enum Flavor : unsigned short int { Vanilla, Chocolate, Strawberry, Mint, }; int _pmain(int /*argc*/, _pchar* /*argv*/[]) { Flavor f = Vanilla; f = Mint; // This is legal since the Flavor enum is an un-scoped enum. Color c = Color::Orange; //c = Orange; // This is illegal since the Color enum is a scoped enum. std::wstring flavor; std::wstring color; switch (c) { case Color::Red: color = L"Red"; break; case Color::Orange: color = L"Orange"; break; case Color::Yellow: color = L"Yellow"; break; case Color::Blue: color = L"Blue"; break; case Color::Indigo: color = L"Indigo"; break; case Color::Violet: color = L"Violet"; break; default: color = L"Unknown"; break; } switch (f) { case Vanilla: flavor = L"Vanilla"; break; case Chocolate: flavor = L"Chocolate"; break; case Strawberry: flavor = L"Strawberry"; break; case Mint: flavor = L"Mint"; break; default: break; } std::wcout << L"Flavor is " << flavor.c_str() << L" (" << f << L"). Color is " << color.c_str() << L" (" << static_cast<int>(c) << L")." << std::endl << L"The size of Flavor is " << sizeof(Flavor) << L"." << std::endl << L"The size of Color is " << sizeof(Color) << L"." << std::endl; return 0; } This code will give the following output: Flavor is Mint (3). Color is Orange (1). The size of Flavor is 2. The size of Color is 4. As you can see in the sample, the scoped Color enumeration requires you to access its members in the same way as C# by prefacing the enumeration member with the enumeration’s name and the scope resolution operator. By contrast, the un-scoped Flavor enumeration allows you simply to specify the members without any prefix. For this reason, I think it’s better practice to prefer scoped enumerations: You minimize the risks of naming collisions and lessen namespace pollution. Notice that there is another difference with scoped enumerations: When we wanted to output the numerical value of the scoped Color enum, we had to use the static_cast operator to convert it to an int, while we did not need to do any casting for the un-scoped Flavor enumeration. For the Flavor enumeration, we specified the underlying type as being an unsigned short int. You can also specify the underlying type for scoped enumerations. Specifying the underlying type is optional, but is mandatory if you wish to use forward declaration with an un-scoped enumeration. Forward declaration is a way to speed up program compile times by only telling the compiler what it needs to know about a type rather than forcing it to compile the whole header file the type is defined in. We will look at this later on. For now, just remember that an un-scoped enumeration must have its underlying type explicitly specified in order to use a forward declaration of it; a scope enumeration does not require specification of its underlying type to use a forward declaration of it (the underlying type will be int if none is specified). You can do the same thing with enumerations in C++ as you can in C# in terms of explicitly assigning values to members, and in terms of creating flag enumerations. You do it all the same way, except you don’t need to apply anything like the FlagAttribute in C++ to create flag enumerations; you just assign the correct values and proceed from there. std::wcout, std::wcerr, std::wcin The std::wcout << L”Flavor... code outputs wide character data to the standard output stream. In the case of a console program such as this, the standard output is the console window. There is also a std::wcerr output stream, which will output wide character data to the standard error output stream. This is also the console window, but you can redirect std::wcout output to one file and std::wcerr output to another file. There is also a std::wcin for inputting data from the console. We won’t explore this, nor will we explore their byte counterparts: std::cout, std::cerr, and std::cin. Just to let you see how the input looks, here’s an example. Sample: ConsoleSample\ConsoleSample.cpp #include <iostream> #include <ostream> #include <string> #include "../pchar.h" struct Color { float ARGB[4]; void A(float value) { ARGB[0] = value; } float A(void) const { return ARGB[0]; } void R(float value) { ARGB[1] = value; } float R(void) const { return ARGB[1]; } void G(float value) { ARGB[2] = value; } float G(void) const { return ARGB[2]; } void B(float value) { ARGB[3] = value; } float B(void) const { return ARGB[3]; } }; // This is a stand-alone function, which happens to be a binary // operator for the << operator when used with a wostream on // the left and a Color instance on the right. std::wostream& operator<<(std::wostream& stream, const Color& c) { stream << L"ARGB:{ " << c.A() << L"f, " << c.R() << L"f, " << c.G() << L"f, " << c.B() << L"f }"; return stream; } int _pmain(int /*argc*/, _pchar* /*argv*/[]) { std::wcout << L"Please input an integer and then press Enter: "; int a; std::wcin >> a; std::wcout << L"You entered '" << a << L"'." << std::endl; std::wcout << std::endl << L"Please enter a noun (one word, no spaces) " << L"and then press Enter: "; std::wstring noun; // wcin breaks up input using white space, so if you include a space or // a tab, then it would just put the first word into noun and there // would still be a second word waiting in the input buffer. std::wcin >> noun; std::wcerr << L"The " << noun << L" is on fire! Oh no!" << std::endl; Color c = { { 100.0f/255.0f, 149.0f/255.0f, 237.0f/255.0f, 1.0f } }; // This uses our custom operator from above. Come back to this sample // later when we've covered operator overloading and this should make // much more sense. std::wcout << std::endl << L"Cornflower Blue is " << c << L"." << std::endl; return 0; } The previous code is a fairly simple demo. It has no error checking, for instance. So, if you enter an incorrect value for the integer, it will just run through to the end with std::wcin returning instantly without any data (that’s what it does unless and until you resolve the error). If you are interested in iostream programming, including using things like std::wofstream to output data to a file and std::wifstream to read data in from a file (they work the same as std::wcout and std::wcin, just with added functionality for dealing with the fact that they work with files), see the MSDN iostream programming pages. Learning all the ins and outs of streams could easily fill a book just on its own. One last thing though. You’ve undoubtedly noticed that the stream functionality looks a bit odd with the bit shifting operators << and >>. That’s because these operators have been overloaded. While you would expect the bit shift operators to act a certain way on integers, there isn’t any specific expectation you’re likely to have about how they should work when applied to an output stream or an input stream, respectively. So the C++ Standard Library streams have co-opted these operators to use them for inputting and outputting data to streams. When we want the ability to read in or write out a custom type that we’ve created (such as the previous Color structure), we simply need to create an appropriate operator overload. We’ll learn more about operator overloading later in the book, so don’t worry if it’s a bit confusing right now Classes and Structures The difference between a class and a structure in C++ is simply that a structure’s members default to public whereas a class' members default to private. That's it. They are otherwise the same. There is no value-type versus reference-type distinction as there is in C#. That said, typically you will see programmers use classes for elaborate types (combinations of data and functions) and structures for simple data-only types. Normally, this is a stylistic choice that represents the non-object-oriented origins of structure in C, making it easy to differentiate quickly between a simple data container versus a full-blown object by looking to see if it's a structure or a class. I recommend following this style. Note: An exception to this style is where a programmer is writing code that is meant to be used in both C and C++. Since C does not have a class type, the structure type might instead be used in ways similar to how you would use a class in C++. I’m not going to cover writing C-compatible C++ in this book. To do so, you would need to be familiar with the C language and the differences between it and C++. Instead, we are focusing on writing clean, modern C++ code. In Windows Runtime (“WinRT”) programming, a public structure can only have data members (no properties or functions). Those data members can only be made up of fundamental data types and other public structures—which, of course, have the same data-only, fundamental, and public-structures-only restrictions. Keep this in mind if you are working on any Metro-style apps for Windows 8 using C++. You will sometimes see the friend keyword used within a class definition. It is followed by either a class name or a function declaration. What this code construct does is give that class or function access to the non-public member data and functions of the class. Typically, you’ll want to avoid this since your class should normally expose everything you want to expose through its public interface. But in those rare instances where you do not wish to publicly expose certain data members or member functions, but do want one or more classes or functions to have access to it, you can use the friend keyword to accomplish this. As classes are a very important part of C++ programming, we will explore them in much more detail later in the book. Unions The union type is a bit odd, but it has its uses. You will encounter it from time to time. A union is a data structure appearing to hold many data members, but only allowing you to use one of its data members at any one time. The end-result is a data structure that gives you many possible uses without wasting memory. The size of the union is required to be large enough only to contain the largest member of the union. In practice, this means the data members overlap each other in memory (hence, you can only use one at a time). This also means you have no way of knowing what the active member of a union is unless you keep track of it somehow. There are many ways you could do that, but putting a union and an enum in a structure is a good, simple, tidy way of doing it. Here’s an example. Sample: UnionSample\UnionSample.cpp #include <iostream> #include <ostream> #include "../pchar.h" enum class SomeValueDataType { Int = 0, Float = 1, Double = 2 }; struct SomeData { SomeValueDataType Type; union { int iData; float fData; double dData; } Value; SomeData(void) { SomeData(0); } SomeData(int i) { Type = SomeValueDataType::Int; Value.iData = i; } SomeData(float f) { Type = SomeValueDataType::Float; Value.fData = f; } SomeData(double d) { Type = SomeValueDataType::Double; Value.dData = d; } }; int _pmain(int /*argc*/, _pchar* /*argv*/[]) { SomeData data = SomeData(2.3F); std::wcout << L"Size of SomeData::Value is " << sizeof(data.Value) << L" bytes." << std::endl; switch (data.Type) { case SomeValueDataType::Int: std::wcout << L"Int data is " << data.Value.iData << L"." << std::endl; break; case SomeValueDataType::Float: std::wcout << L"Float data is " << data.Value.fData << L"F." << std::endl; break; case SomeValueDataType::Double: std::wcout << L"Double data is " << data.Value.dData << L"." << std::endl; break; default: std::wcout << L"Data type is unknown." << std::endl; break; } return 0; } As you can see, we define an enum that has members representing each of the types of members of the union. We then define a structure that includes both a variable of the type of that enum and then an anonymous union. This gives us all the information we need to determine which type the union is currently holding within one encapsulated package. If you wanted the union to be usable in multiple structures, you could declare it outside of the structure and give it a name (e.g., union SomeValue { ... };). You could then use it within the structure as, for example, SomeValue Value;. It’s usually better to keep it as an anonymous union though, since you do not need to worry about the side effects of making a change except within the structures in which it is defined. Unions can have constructors, destructors, and member functions. But since they can have only one active data member ever, it rarely makes any sense to write member functions for a union. You will rarely see them, perhaps never. typedef The first thing to understand about typedef is that despite the implications of its name, typedef does not create new types. It is an aliasing mechanism that can be used for many things. It is used a lot in implementing the C++ Standard Library and other template-based code. This is, arguably, its most important use. We will explore it more in the chapter on templates. It can save you from a lot of typing (though this argument lost some of its force with the repurposing of the auto keyword for type deduction in C++11). If you have a particularly complicated data type, creating a typedef for it means you only need to type it out once. If your complicated data type’s purpose is unclear, giving it a more semantically meaningful name with a typedef can help make your program easier to understand. It is sometimes used as an abstraction by developers to easily change a backing type (e.g., from a std::vector to a std::list) or the type of a parameter (e.g., from an int to a long). For your own internal-use-only code, this should be frowned upon. If you are developing code that others will be using, such as a library, you should never try to use a typedef in this way. All you are doing is decreasing the discoverability of breaking changes to your API if you change a typedef. Use them to add semantic context, sure, but do not use them to change an underlying type in code that others rely on. If you need to change the type of something, remember that any change to a function’s parameters is a breaking change as is a change in return type or the addition of a default argument. The proper way to handle the possibility of a future type change is with abstract classes or with templates (whichever is more suitable or whichever you prefer, if both will serve). This way the public interface to your code will not change, only the implementation will. The Pimpl idiom is another good way to keep a stable API while retaining the freedom to change implementation details. We will explore the Pimpl idiom, short for “pointer to implementation,” in a later chapter. Here is a small code block illustrating the syntax for typedef. class ExistingType; typedef ExistingType AliasForExistingType; And the following is a brief sample showing how typedef might be used. The purpose of this sample is to illustrate a simplified but realistic use of a typedef. In practice, a typedef like this would go into a namespace and would then be included in a header file. Since we haven’t covered any of that, this example has been kept simple intentionally. Sample: TypedefSample\TypedefSample.cpp #include <iostream> #include <ostream> #include <vector> #include <algorithm> #include "../pchar.h" // This makes WidgetIdVector an alias for std::vector<int>, which has // more meaning than std::vector<int> would have, since now we know that // anything using this alias expects a vector of widget IDs // rather than a vector of integers. typedef std::vector<int> WidgetIdVector; bool ContainsWidgetId(WidgetIdVector idVector, int id) { return (std::end(idVector) != std::find(std::begin(idVector), std::end(idVector), id) ); } int _pmain(int /*argc*/, _pchar* /*argv*/[]) { WidgetIdVector idVector; // Add some id numbers to the vector. idVector.push_back(5); idVector.push_back(8); // Output a result letting us know if the id is in the // WidgetIdVector. std::wcout << L"Contains 8: " << (ContainsWidgetId(idVector, 8) ? L"true." : L"false.") << std::endl; return 0; } Conclusion You should now have a clear understanding of the types available in C++. In the next article, we'll take a closer look at namespaces<<
https://code.tutsplus.com/articles/c-succinctly-types--mobile-22042
CC-MAIN-2021-04
refinedweb
3,804
61.77
{% set rfcid = “RFC-0082” %} {% include “docs/contribute/governance/rfcs/_common/_rfc_header.md” %} This document proposes a mechanism for running unmodified Linux programs on Fuchsia. The programs are run in a userspace process whose system interface is compatible with the Linux ABI. Rather than using the Linux kernel to implement this interface, we will implement the interface in a Fuchsia userspace program, called starnix. Largely, starnix will serve as a compatibility layer, translating requests from the Linux client program to the appropriate Fuchsia subsystem. Many of these subsystems will need to be elaborated in order to support all the functionality implied by the Linux system interface. In order to run on Fuchsia today, software needs to be recompiled from source to target Fuchsia. In order to reduce the amount of source modification needed to run on Fuchsia, Fuchsia offers a POSIX compatibility layer, POSIX Lite, that this software can target. POSIX Lite is layered on top of the underlying Fuchsia System ABI as a client library. However, POSIX Lite is not a complete implementation of POSIX. For example, POSIX Lite does not contain parts of POSIX that imply mutable global state (e.g., the kill function) because Fuchsia is designed around an object-capability discipline that eschews mutable global state to provide strong security guarantees. Instead, software that uses POSIX Lite needs to be modified to use the Fuchsia system interface directly for those use cases (e.g., the zx_task_kill function). This approach has worked well so far because we have had access to the source code for the software we needed to run on Fuchsia, which has let us recompile the software for the Fuchsia System ABI as well as modify parts of the software that need to be adapted to an object-capability system. As we expand the universe of software we wish to run on Fuchsia, we are encountering software that we wish to run on Fuchsia that we do not have the ability to recompile. For example, Android applications contain native code modules that have been compiled for Linux. In order to run this software on Fuchsia, we need to be able to run binaries without modifying them. The most direct way of running Linux binaries on Fuchsia would be to run those binaries in a virtual machine with the Linux kernel as the guest kernel in the virtual machine. However, this approach makes it difficult to integrate the guest programs with the rest of the Fuchsia system because they are running in a different operating system from the rest of the system. Fuchsia is designed so that you can bring your own runtime, which means the Fuchsia system does not impose an opinion about the internal structure of components. In order to interoperate as a first-class citizen with the Fuchsia system, a component need only send and receive correctly formatted messages over the appropriate zx::channel objects. Rather than running Linux binaries in a virtual machine, starnix creates a Linux runtime natively in Fuchsia. Specifically, a Linux program can be wrapped with a component manifest that identifies starnix as the runner for that component. Rather than using the ELF Runner directly, the binary for the Linux program is given to starnix to run. In order to execute a given Linux binary, starnix manually creates a zx::process with an initial memory layout that matches the Linux ABI. For example, starnix populates argv and environ for the program as data on the stack of the initial thread (along with the aux vector) rather than as a message on the bootstrap channel, as this data is populated in the Fuchsia System ABI. After loading the binary into the client process, starnix registers to handle all the syscalls from the client process (see Syscall Mechanism below). Whenever the client issues a syscall, the Zircon kernel transfers control to starnix, which decodes the syscall according to Linux syscall conventions and does the work of the syscall. For example, if the client program issues a brk syscall, starnix will manipulate the address space of the client process using the appropriate zx::vmar and zx::vmo operations to change the address of the program break of the client process. In some cases, we might need to elaborate the ability for one process (i.e., starnix) to manipulate the address space of another process (i.e., the client), but early experimentation indicates that Zircon already contains the bulk of the machinery needed for remote address-space manipulation. As another example, suppose the client program issues a write syscall. To implement file-related functionality, starnix will maintain a file descriptor table for each client process. Upon receiving a write syscall, starnix will look up the identified file descriptor in the file descriptor table for the client process. Typically, that file descriptor will be backed by a zx::channel that implements the fuchsia.io.File FIDL protocol. To execute the write, starnix will format a fuchsia.io.File#Write message containing the data from the client address space (see Memory access) and send that message through the channel, similar to how POSIX Lite implements write in a client library. To handle syscalls that imply mutable global state, starnix will maintain some mutable state shared between client processes. For example, starnix will assign a pid_t to each client process it runs and maintain a table mapping pid_t to the underlying zx::process handle for that process. To implement the kill syscall, starnix will look up the given pid_t in this table and issue a zx_task_kill syscall on the associated zx::process handle. In this way, each starnix instance serves as a container for related Linux processes. If we wish to have strong isolation guarantees between two Linux processes, we can run those processes in separate starnix instances without the overhead (e.g., scheduling complexities) of running multiple virtual machines. Each starnix instance will also expose its global state for use by other Fuchsia processes. For example, starnix will maintain a namespace of AF_UNIX sockets. This namespace will be accessible both from Linux binaries run by starnix and from Fuchsia binaries that communicate with starnix over FIDL. The Linux system interface also implies a global file system. As Fuchsia does not have a global file system, starnix will synthesize a “global” file system for its client processes from its own namespace. For example, starnix will mount /data/root from its own namespace as / in the global file system presented to client processes. Other mount points, such as /proc can be implemented internally by starnix, for example by consulting its table of running processes. As much as possible, starnix will build upon the security mechanisms of the underlying Fuchsia system. For example, when interfacing with system services, such as file systems, networking, and graphics, starnix will serve largely as a translation layer, reformatting requests from the Linux ABI to the Fuchsia System ABI. The system services will be responsible for enforcing their own security invariant, just as they do for every other client. However, starnix will need to implement some security mechanisms to protect access to its own services. For example, starnix will need to determine whether one client process is allowed to kill another client process. To make these security decisions, starnix will track a security context for each client process, including a uid_t, gid_t, effective uid_t, and effective gid_t. Operations that require security checks will use this security context to make appropriate access control decisions. Initially, we expect this mechanism to be used infrequently, but as our use cases grow more sophisticated, our needs for access control are also likely to grow more complex. When faced with a choice for how starnix ought to behave in a certain situation, the design favors behaving as close to how Linux behaves as feasible. The intention is to create an implementation of the Linux interface that can run existing, unmodified Linux binaries. Whenever starnix diverges from Linux semantics, we run a risk that some Linux binary will notice the divergence and behave improperly. To be able to discuss this design principle more easily, we say that starnix implements Linux as she is spoke, which is to say with all the beauty, ugliness, coincidences, and quirks of a real Linux system. In some cases, implementing the Linux interfaces as she is spoke will require adding functionality to a Fuchsia service to provide the require semantics. For example, implementing inotify requires support from the underlying file system implementation in order to work efficiently. We should aim to add this functionality to Fuchsia services in a way that integrates well with the rest of the functionality exposed by the service. We plan to implement starnix as a Fuchsia component, specifically a normal userspace component that implements the runner protocol. We plan to implement starnix in Rust to help avoid privilege escalation from the client process to the starnix process. One of the core pieces of starnix is the executive, which implements the semantic concepts in the Linux system interface. For example, the executive will have objects that represent threads, processes, and file descriptions. The executive will be structured such that it can be unit tested independently from the rest of the starnix system. For example, we will be able to unit test that duplicating a file descriptor shares an underlying file description without needing to run a process with the Linux ABI. In order to implement Linux syscalls, starnix needs a description of each Linux syscall as well as the userspace memory layout of any associated input or output parameters. These are defined in the Linux uapi, which is a freestanding collection of C headers. To make use of these definitions in Rust, we will use Rust bindgen to generate Rust declarations. The Linux uapi evolves over time. Initially, we will target the Linux uapi from Linux 5.10 LTS, but we will likely need to adjust the exact version of the Linux uapi we support over time. The initial implementation of starnix will use Zircon exceptions to trap syscalls from the client process. Specifically, whenever the client process attempts to issue a syscall, Zircon will reject the syscall because Zircon requires syscalls to be issued from within the Zircon vDSO, which the client process is unaware exists. Zircon rejects these syscalls by generating a ZX_EXCP_POLICY_CODE_BAD_SYSCALL exception. The starnix process will catch these exceptions by installing an exception handler on each client process. To receive the parameters for the syscall, starnix will use zx_thread_read_state to read the registers from the thread that generated the exception. After processing the syscall, starnix sets the return value for the syscall using zx_thread_write_state and then resumes the thread in the client process. This mechanism works but is unlikely to have high enough performance to be useful. After we build out a sufficient amount of starnix to run Linux benchmarks, we will likely want to replace this syscall mechanism with a more efficient mechanism. For example, perhaps starnix will associate a zx::port for handling syscalls from the client process and Zircon will queue a packet to the zx::port with register state of the client process. When we have benchmarks in place, we can prototype a variety of approaches and select the best design at that time. The initial implementation of starnix will use the zx_process_read_memory and zx_process_write_memory to read and write data from the address space of the client process. This mechanism works, but is undesirable for two reasons: After we build out a sufficient amount of starnix to run Linux benchmarks, we will want to replace this mechanism with something more efficient. For example, perhaps starnix will restrict the size of the client address space and map each client‘s address space into its own address space at some client-specific offset. Alternatively, perhaps when the starnix services a syscall from a client, Zircon will arrange for that client’s address space to be visible from that thread (e.g., similar to how kernel threads have visibility into the address space of userspace process when servicing syscalls from those processes). As with the syscall mechanism, we can prototype a variety of approaches and select the best design once we have more running code to use to evaluate the approaches. We will develop starnix using a test-driven approach. Initially, we will use a naively simple implementation that is sufficient to run basic Linux binaries. We have already prototyped an implementation that can run a -static-pie build of a hello_world.c program. The next step will be to clean up that prototype and teach starnix how to run a dynamically linked hello_world.c binary. After running these basic binaries, we will bring up unit test binaries from various codebases. These binaries will help ensure that our implementation of the Linux ABI is correct (i.e., as Linux is spoke). For example, we will run some low-level test binaries from the Android source tree as well as binaries from the Linux Test Project. Performance is a critical aspect of this project. Initially, starnix will perform quite poorly because we will be using inefficient mechanisms for trapping syscalls and for access client memory. However, those are areas that we should be able to optimize substantially once we have sufficient functionality to run benchmarks in the Linux execution environment. In addition to optimizing these mechanisms, we also have the opportunity to offload high-frequency operations to the client. For example, we can implement gettimeofday directly in the client address space by loading code into the client process before transferring control to the Linux binary. For example, if the Linux binary invokes gettimeofday through the Linux vDSO, starnix can provide a shared library in place of the Linux vDSO that implements gettimeofday directly by calling through to the Zircon vDSO. This proposal has many subtle security considerations. There is a trust boundary between the starnix process and the client process. Specifically, the starnix process can hold object-capabilities that are not fully exposed to the client. For example, the starnix process maintains a file descriptor table for each client process. One client process should be able to access handles stored in its file descriptor table but not handles stored in the file descriptor table for another process. Similarly, starnix maintains shared mutable state that clients can interact with only subject to access control. To provide this trust boundary, starnix runs in a separate userspace process from the client processes. To help avoid privilege escalation, we plan to implement starnix in Rust and to use Rust‘s type system to avoid type confusion. We also plan to use Rust’s type system to clearly distinguish client data, such as addresses in the client's address space and data read from the client address space, from reliable data maintained by starnix itself. Additionally, we need to consider the provenance of the Linux binaries themselves because starnix runs those binaries directly, rather than, for example, in virtual machine or SFI container. We will need to revisit this consideration in the context of a specific, end-to-end product use case that involves Linux binaries. The access control mechanism within starnix will require a detailed security evaluation, ideally including direct participation from the security team in its design and, potentially, implementation. Initially, we expect to have a simple access control mechanism. As the requirements for this mechanism grow more sophisticated, we will need further security scrutiny. Finally, the designs for the high-performance syscall and client memory mechanisms will need careful security scrutiny, especially if we end up using an exotic address space configuration for starnix or attempt to directly transfer register state from the client thread to a starnix thread. This design does not have any immediate privacy considerations. However, once we have a specific, end-to-end product use case that involves Linux binaries, we will need to evaluate the privacy implications of that use case. Testing is a central aspect of building starnix. We will directly unit test the starnix executive. We will also build out our implementation of the Linux system interface by attempting to pass test binaries intended to run on Linux. We will then run these binaries in continuous integration to ensure that starnix does not regress. We will also compare running Linux binaries in starnix with running those same binaries in a virtual machine on Fuchsia. We expect to be able to run Linux binaries more efficiently in starnix, but we should validate that hypothesis. At this stage, we plan to document starnix through this RFC. Once we get non-trivial binaries running, we will need to document how to run Linux binaries on Fuchsia. There is a large design space to explore for how to run unmodified Linux binaries on Fuchsia. This section summarizes the main design decisions. An important design choice is whether to use the Linux kernel itself to implement the Linux system interface. In addition to building starnix, we will also build a mechanism for running unmodified Linux binaries by running the Linux kernel inside a Machina virtual machine. This approach has a small implementation burden because the Linux kernel is designed to run inside a virtual machine and the Linux kernel already contains an implementation of the hundreds of syscalls that make up the Linux system interface. There are several ways we could use the Linux kernel. For example, we could run the Linux kernel in a virtual machine, we could use User-Mode Linux (UML) or we could use the Linux Kernel Library (LKL). However, regardless of how we run it, there is a large cost to running an entire Linux kernel in order to run Linux binaries. At its core, the job of the Linux kernel is to reduce high-level operations (e.g., write) to low-level operations (e.g., DMA data to an underlying piece of hardware). This core function is counter-productive for integrating Linux binaries into a Fuchsia system. Instead of reducing a write operation to a DMA, we wish to translate a write operation into a fuchsia.io/File.Write operation, which is at an equivalent semantic level. Similarly, the Linux kernel comes with a scheduler, which controls the threads in the processes it manages. The purpose of this functionality is to reduce high-level operations (e.g., run a dozen concurrent threads) to low-level operations (e.g., execute this time slice on this processor). Again, this core functionality is counter-productive. We can compute a better schedule for the system as a whole if the threads running for each Linux binary are actually Zircon threads scheduled by the same scheduler as all the other threads in the system. Once we have decided to implement the Linux system interface directly using the Fuchsia system, we need to choose where to run that implementation. We could run the implementation in the same process as the Linux binary. For example, this approach is used by POSIX Lite to translate POSIX operations into Fuchsia operations. However, this approach is less desirable when running unmodified Linux binaries for two reasons: If we run the implementation in-process, we will need to “hide” the implementation from the Linux binary because Linux binaries do not expect the system to be running (much) code in their process. For example, any use of thread-local storage by the implementation must take care not to collide with the thread-local storage managed by the Linux binary's C runtime. Many parts of the Linux system interface imply mutable global state. An in-process implementation would still need to coordinate with an out-of-process server to implement those parts of the interface correctly. For these reasons, we have chosen to start with an out-of-process server implementation. However, we will likely offload some operations from the server to the client for performance. In this approach, the implementation runs in a separate userspace process from the Linux process. This approach is the one we have selected for starnix. The primary challenges with this approach are that we need to carefully design the mechanisms we use for syscalls and client memory access to give sufficient performance. There is some unavoidable overhead to involving a second userspace process because we will need to perform an extra context switch to enter that process, but there is evidence from other systems that we can achieve excellent performance. Finally, we could run the implementation in the kernel. This approach is the traditional approach for providing foreign personalities for operating systems. However, we would like to avoid this approach in order to reduce the complexity of the kernel. Having a kernel that follows a clear object-capability discipline makes reasoning about the behavior of the kernel much easier, resulting in better security. The primary advantage that an in-kernel implementation offers over a userspace implementation is performance. For example, the kernel can directly receive syscalls and already has a high-performance mechanism for interacting with client address spaces. If we are able to achieve excellent performance with a userspace approach, then there will be little reason to run the implementation in the kernel. Linux binaries expect the kernel to run some of their code in async signal handlers. Fuchsia currently does not contain a mechanism for directly invoking code in a process, which means there is no obvious mechanism for invoking async signal handlers. Once we encounter a Linux binary that requires support for async signal handlers, we will need to devise a way to support that functionality. Futexes work differently on Fuchsia and Linux. On Fuchsia, futexes are keyed off virtual addreses whereas Linux provides the option to key futexes off physical addresses. Additionally, Linux futexes offer a wide variety of options and operations that are not available on Fuchsia futexes. In order to implement the Linux futex interface, we will either need to implement futexes in starnix or add functionality to the Zircon kernel to support the functionality required by Linux binaries. There is a large amount of prior art for running Linux (or POSIX) binaries on non-POSIX systems. This section describes two related systems. The design in this document is similar to the first Windows Subsystem for Linux (WSL1), which was an implementation of the Linux system interface on Windows that was able to run unmodified Linux binaries, including entire GNU/Linux distributions such as Ubuntu, Debian, and openSUSE. Unlike starnix, WSL1 ran in the kernel and provided a Linux personality for the NT kernel. Unfortunately, WSL1 was hampered by the performance characteristics of NTFS, which do not match the expectations of Linux software. Microsoft has since replaced WSL1 with WSL2, which provides similar functionality by running the Linux kernel in a virtual machine. In WSL2, Linux software runs against an ext4 file system, rather than an NTFS file system. An important cautionary lesson we should draw from WSL1 is that the performance of starnix will hinge on the performance of the underlying system services that starnix exposes to the client program. For example, we will need to provide a file system implementation with comparable performance to ext4 if we want Linux software to perform well on Fuchsia. QNX Neutrino is a commercial microkernel-based operating system that provides a high-quality POSIX implementation. The approach described in this document for starnix is similar to the proc server in QNX, which services POSIX calls from client processes and maintains the mutable global state implied by the POSIX interface. Similar to starnix, proc is a userspace process on QNX.
https://fuchsia.googlesource.com/fuchsia/+/refs/heads/releases/canary/docs/contribute/governance/rfcs/0082_starnix.md
CC-MAIN-2021-25
refinedweb
3,917
51.38
python USES os.listdir and os.walk to get the path to the file - 2020-06-15 09:46:30 - OfStack This article introduces python's method of using os.listdir and os.walk to get the path of the file. The details are as follows: The os. listdir() method is used to return a list of the files or folder names that the specified folder contains. The list is in alphabetical order. It does not include '.' and '. 'even though it's in the folder. The os. walk() method is used to output the filename in the directory by walking through the directory tree species, up or down. os.listdir: You can use os.listdir when there are only files under 1 directory and no folders We have an file directory (folder) on our desktop with three files in it file(dir)| --|test1.txt --|test2.txt --|test3.txt Get the absolute path to the file using the following procedure: import os path = r'C:\Users\Administrator\Desktop\file' for filename in os.listdir(path): print(os.path.join(path,filename)) os. listdir is used to read all the file names under a directory, and then os. path. join is used to combine the path of the directory and the file name. C:\Users\Administrator\Desktop\file\test1.txt C:\Users\Administrator\Desktop\file\test2.txt C:\Users\Administrator\Desktop\file\test3.txt Case 2: Recursive case, 1 directory under both directories (directory under which there may be directories and files) and how to read all the files inside, using ES47en.walk: os. walk introduction: We set up an file directory on the desktop. The organizational structure is as follows: file(dir): --|file1(dir): --|file1_test1.txt --|file1_test2.txt --|file2(dir) --|file2_test1.txt --|file_test1.txt --|file_test2.txt Run the following code: import os path = r'C:\Users\Administrator\Desktop\file' for dirpath,dirnames,filenames in os.walk(path): print(dirpath,dirnames,filenames) The output results are as follows: C:\Users\Administrator\Desktop\file ['file1', 'file2'] ['file_test1.txt', 'file_test2 .txt'] C:\Users\Administrator\Desktop\file\file1 [] ['file1_test1.txt', 'file1_test2.txt'] C:\Users\Administrator\Desktop\file\file2 [] ['file2_test1.txt'] os. walk enter 1 path name, return 1 3 tuple dirpath, dirnames, filenames as yield (actually a generator), dirpath is the path to the directory, which is 1 string. For example, C:\Users\ Desktop\file \Administrator\ file\file1 and so on. dirnames lists the names of all existing directories under the directory path. For example, under C:\Users\Administrator\Desktop\ file1 and file2, it lists the directory name under this directory path. filenames lists the names of all the files under the directory path. Also under C:\Users\ Desktop\file there are two files file_ES119en1.txt and file_ES122en2.txt which will be listed by the program. How to get 1 path for all the following file paths: import os path = r'C:\Users\Administrator\Desktop\file' for dirpath,dirnames,filenames in os.walk(path): for filename in filenames: print(os.path.join(dirpath,filename)) The results are as follows: C:\Users\Administrator\Desktop\file\file_test1.txt C:\Users\Administrator\Desktop\file\file_test2 .txt C:\Users\Administrator\Desktop\file\file1\file1_test1.txt C:\Users\Administrator\Desktop\file\file1\file1_test2.txt C:\Users\Administrator\Desktop\file\file2\file2_test1.txt
https://ofstack.com/python/25712/python-uses-os.listdir-and-os.walk-to-get-the-path-to-the-file.html
CC-MAIN-2022-21
refinedweb
542
51.34
Hi! Could someone help me. I am using CUDA SDK and have a problem with headers including in cl-files. Let full path to project be C:\FULL\PATH\TO\PROJECT, and its content is something like: cl ________|- include ________________|- cl_header1.h ________|- cl_code1.cl ________|- cl_code2.cl some_code.h some_code.cpp In cl_header1.h: #include <cl_header1.h> ... __kernel void cl_kernel(...) {...} In some_code.cpp: ... err = clBuildProgram(program, 1, &device_id, include_path.c_str(), NULL, NULL); ... If include_path is full: string include_path = "-I C:\\FULL\\PATH\\TO\\PROJECT\\cl\\include"; program runs, but if I set it as relative string include_path = "-I \\cl\\include"; clBuildProgram fails. What I am doing wrong?
https://forums.developer.nvidia.com/t/opencl-clbuildprogram-with-relative-path-for-headers/64117
CC-MAIN-2022-21
refinedweb
109
55.61
Debugging, Parallel Computing, WPF, XPS, GDI, GDI+, Printing (): #include <stdio.h> #include <tchar.h>; std::vector<int> intvector;. If you would like to receive an email when updates are made to this post, please register here RSS This problem is not inherent to vector (and other STL containers), but to its implementation in MSVC. The data-type specific things, namely construction, deletion and assignment (and less-than comparison, for containers other than vector), could be implemented using virtual functions, probably with little impact on performance. The rest would be a completely generic non-templated container class, with a parameter for data-type size. what would the alternative be (but for few simple classes/types such as int/short). One would anyway invent their own equivalents of vector, list etc which would add to the size. I guess this cost is unavoidable in any case In any form, you will need code for the task of "push back", and it may cost more than vector::push_back.
http://blogs.msdn.com/fyuan/archive/2007/03/04/anatomy-of-stl-vector-module-size.aspx
crawl-002
refinedweb
165
62.58
The windows 8 app development tecnology sugessted is very similar to WP7 development. They both based on the Silverlight technology. So the question is from now can we use a single application for windows phone. "Hi, Windows 8 Metro-style apps use XAML for their UI and is similar to the markup in Silverlight. The differenece is in the namespaces that the two use (ie where to get the resource for say a listbox), similarly c# is supported in Windows 8 so out of the box a precompiled WP7 app wouldn't run but a vendor can update the existing code to produce an app targeting Windows 8 Metro. Although not trivial it's not that hard involving a bit of copy/replace and some intellisense." So in conclusion it is possible its just that some code needs to be changed as some of the resources have different locations on each OS. Yes, you can. The easiest way to achieve this effect will be to use javascript, although this isn't much different then just writing browser only applications. asked 2 years ago viewed 128 times active
http://superuser.com/questions/496720/can-windows-8-applications-run-on-windows-phone-8
CC-MAIN-2015-40
refinedweb
187
61.46
Resource Governor is an extremely cool and powerful feature that, when implemented, can manage the consumption of CPU and memory resources. I will not be going into the details of Resource Governor, or even how to set it up as this is extensively documented in Books Online. What I will be talking about today is a tool, in particular a report, that I’ve developed to monitor the current state of Resource Governor usage and the current activity that is taking place. The challenge I’m looking to tackle here today is a solution in order to visualize what is currently happening with resource consumption. I have written an SSRS report (well, actually two reports, but logically it can be considered one monitoring solution) to show this data. The reason I chose to write an SSRS report is because I wanted the ability to bring it into SQL Server Management Studio as a custom report. As SQL Server DBAs, SSMS is our go-to tool of choice. I designed the report to have an overview breakdown of CPU and memory utilization, and then by each particular resource pool in their respective category. The all-encompassing screenshot can be seen below: CPU Breakdown In the main screenshot, focus on the top row of data. This is the CPU monitoring portion of the report. On the left hand side you can see the system CPU summary: This rectangle has a bit of information, including three CPU metrics: Total System CPU utilization, SQL Server process CPU utilization, and other process CPU utilization. Then right below this there is a little sparkline graph to visually show the past hour of this data. One thing to note here is that all of these numbers are pulled from the ring buffers, and this data is only refreshed once a minute (for more information on this please see Amit Banerjee’s blog post on the topic). So this data can be up to 60 seconds stale, and if your CPU utilization for each resource pool (real-time) doesn’t make sense compared to this CPU summary rectangle (refreshed every 60 seconds) then it is because of this update schedule for the ring buffers. Right next to this CPU summary rectangle is a breakdown of current CPU utilization by resource pool: There are three interesting metrics plotted here for each resource pool (named on the y-axis): cap CPU percent (only available in SQL Server 2012 and the corresponding Resource Governor Monitor report), CPU usage, and max CPU percent. The cap CPU percent and the max CPU percent are configuration values for the pool, and CPU usage is the currently amount of CPU that the particular resource pool is consuming. Memory Usage Right below the CPU utilization numbers, we see the horizontal display of memory utilization. The structure is the same as CPU, with the summary on the left: This summary gives us three high-level memory metrics: Total Server Memory, Target Server Memory, and max server memory. To the right is the memory consumption breakdown by resource pool: There are three plotted metrics for each resource pool: max memory, target memory, and currently used memory. Activity and Configuration Summary I also wanted to have enough information on this semi-dashboard to minimize the need to go to diagnostic queries. Connecting the dots is really what it’s all about, and I thought it prudent to have a mapping of workload groups to resource pools in this report: Oftentimes we see a 1:1 relationship between resource pools and workload groups, but if you introduce a one to many relationship then it could get relatively confusing. You see CPU and memory consumption, but you may want to know right off the bat which workload group(s) are consuming that particular resource pool. I put the count of sessions related to each pool, and also the current count of executing requests: This will give you an idea of session/request distribution across the resource pools. And if you want a more detailed look at current requests, just click the resource pool name (drill through), and you’ll get routed to another report showing current activity for that particular resource pool: This report parameterized by resource pool and grouped by workload group, and when you expand a workload group you will see a list of current requests as well as their CPU time, reads, granted query memory, and the corresponding SQL text. Next Steps If you want to start using this report today, follow the below steps: 1. Download the RDL files 2. Unzip the RDL files in your SSMS Custom Reports directory a. Example: C:\Users\YourUserName\Documents\SQL Server Management Studio\Custom Reports 3. Open up SQL Server Management Studio 4. Maximize the Management tab in Object Explorer 5. Right-click on Resource Governor 6. Mouse-over Reports and select Custom Reports… 7. Select the Resource Governor Monitor [2012 | 2008].rdl report Now that you’ve selected the proper report, it’ll appear in the Reports menu of SSMS under Resource Governor for future easy access: This will be a living and maturing report, so if you have something you want to see included in this report regarding Resource Governor monitoring, please leave a comment below and it will be considered and possible added. Enjoy! Thomas Stringer – SQL Server Premier Field Engineer Thanks for this, will come in handy My pleasure, I hope it does prove helpful. Cool… Thank you! Hmm, what to change if this error occurs: An error occurred during local report processing. (Microsoft.ReportViewer.WinForms) The definition of the report 'Main Report' is invalid. (Microsoft.ReportViewer.Common) The report definition is not valid. Details: The report definition has an invalid target namespace 'schemas.microsoft.com/…/reportdefinition& which cannot be upgraded. (Microsoft.ReportViewer.Common) Sven, what version of SSMS are you using? This can be retrieved from the "Help" menu section, and the "About" item. hi, i got the same error as Sven. My SSMS version is 10.50.2500.0. same in my environment sql 2008 (r1) sp3. it doesn not happen in R2 this helps a lot. Thank you. Hi, Would it be possible to make the table on the first page bigger? We're currently using approx. 10-12 resource pools and only 5 names of them appear to the left of the table, whilst it is also not very clear which lines belong to the those 5. Thanks!
https://blogs.msdn.microsoft.com/sql_pfe_blog/2013/06/20/sql-server-resource-governor-monitoring-reports/
CC-MAIN-2016-44
refinedweb
1,076
50.46
Polymorphism means the ability to take different forms. In C#, there are two types of polymorphism - compile-time polymorphism and run time polymorphism. Compile time polymorphism is also known as early binding or late binding. Runtime polymorphism is also known as dynamic binding or late binding. In C#, we can achieve compile time polymorphism with method overloading and runtime polymorphism can be achieved by method overriding which we are going to study in this chapter. C# Method Overloading Same as constructors, we can also overload methods. Method overloading is basically having multiple methods with same name but different arguments. Suppose we want to make a method to add numbers. It is possible that some sometimes we need to add two integer, sometimes two doubles, etc. We can use method overloading to have multiple methods with same name e.g. - Add(int x, int y), Add(int x, int y, int z), Add(double x, double y), Add(int x, double y), etc. Conditions for method overloading are:- - Methods to be overloaded must have the same name. - All methods must have different arguments (either a different number of parameters or different type of parameters). Let's take an example. using System; class Rectangle { public static void PrintArea(int x, int y) { Console.WriteLine(x*y); } public static void PrintArea(int x) { Console.WriteLine(x*x); } public static void PrintArea(int x, double y) { Console.WriteLine(x*y); } public static void PrintArea(double x) { Console.WriteLine(x*x); } static void Main(string[] args) { PrintArea(2, 4); PrintArea(2, 5.1); PrintArea(10); PrintArea(2.3); } } Here, we defined four methods with the same name PrintArea but different parameters. Firstly the method PrintArea is called and 2 and 4 passed to it. Since both 2 and 4 are integers, so the method named PrintArea with both its parameters of type int (int x, int y) is called. After that, method is called with 2 and 5.1. Since 2 is of type int and 5.1 is of type double, so the method with the first parameter of type int and the second one of type double i.e., (int x,double y) is called. Similarly, after that the function with only one integer value as its parameter is called and at last, the function with a single double value as its parameter is called. C# Method Overriding Method overriding is also like method overloading but it performed with parent and child class. Suppose, we have made an Animal class and there is a method Speak in the class which prints "Animal Speach". Now, we have made a subclass Dog of the class Animal and we want the method Speak to print "Bark" in this method. We can override the Speak method of the Animal class in the Dog subclass to print "Bark". We use virtual keyword with the method which we are going to override (in parent class) and override keyword with the method in the child class. Let's look at an example. using System; class Animal { public virtual void Sound() { Console.WriteLine("This is parent class"); } } class Dog: Animal { public override void Sound() { Console.WriteLine("Dogs bark"); } } class Test { static void Main(string[] args) { Dog d = new Dog(); d.Sound(); } } In the above example, the class Dog and its parent class Animal have the same method void sound(). When the object d of class Dog calls this method, then the method of the child class Dog is called, not that of the parent class. Thus, the method of the child class overrides the method in parent class when called by an object of the child class. C# Sealed Method To prevent a method from being overridden, we use sealed keyword. Let's look at an example. using System; class A { public virtual void AMethod() { Console.WriteLine("This is parent class"); } } class B:A { public sealed override void AMethod() { Console.WriteLine("This is parent class"); } } class C:B { public override void AMethod() { Console.WriteLine("This is parent class"); } } class Test { static void Main(string[] args) { } } In the class B, we have sealed the method AMethod. So, we are not able to override it in the class C.
https://www.codesdope.com/course/c-sharp-polymorphism/
CC-MAIN-2022-40
refinedweb
696
74.49
Oxygen XML Plugin for Eclipse To see the differences between the Standalone and Eclipse version of Oxygen click here. Tree-Based Outline View. XML Perspective and Project Support From the dialog box for creating new Eclipse projects, you can choose the type "XML Project". This will change the perspective to Oxygen XML Perspective, allows you to easily access Oxygen actions, and helps to organize your XML files. XSLT/XQuery Debugger Perspectives Oxygen adds two debugger perspectives to the Eclipse IDE providing a special layout that shows the source and the stylesheet/xquery documents side by side as well as the results and special debugging views (Context, Call Stack, Trace History, XPath Watch, Variables, etc.) All debugger capabilities are provided (step into, step over, step out, run, run to cursor, run to end, pause, stop). Oxygen Wizards The Oxygen plugin installs a series of Eclipse wizards that helps you to easily create new documents. Using these wizards, Oxygen will fill in details such as the system ID or schema location of a new XML document, the minimal markup of a DocBook article, or the namespace declarations of a Relax NG schema. Non-Blocking Operations Some operations may take some noticeable time when you work on large documents or you perform complex transformations. Unlike other editors that block these operations and remain unusable for large periods of time, Oxygen performs all these operations in background, keeping the interface usable so you can continue editing the document or switch to other documents or perform other operations. XML Catalog Support The XML Catalog support allows you to specify references to original remote resources (using a public ID or a remote URL) while the application is using your local copy for those resources. Thus, the documents are written in a portable manner, the access to resources is faster because the local copy is used, and the remote resource references can be used even when you are off-line. With Oxygen, you can use OASIS Entity Resolution Technical Committee XML Catalog file, Extended OASIS Entity Resolution Technical Committee XML Catalog files, OASIS Open Catalog files, and "xcatalog" XML Catalog files . XInclude Support Oxygen allows you to enable the XInclude support from the XML Parser preferences page. The XInclude support is based on Xerces. Context-Sensitive Content Completion Assistant Oxygen offers proposals for elements, attributes, and attribute values via context sensitive content completion mechanism. Unlike other editors that offer all the available entries, Oxygen will offer only the entries that are valid in the editing context to help you create valid content while editing. Content Completion Assistant Shows XSLT Output Document Elements While creating an XSLT document as output (HTML, FO, or another XML format), XSLT allows you to specify elements from the target output directly. For example, you can specify <table> ... </table> instead of <xsl:element ... </xsl:element>. Whenever an xsl:element is allowed, the Content Completion Assistant provided by Oxygen will also propose the elements from the target output. The target output document type can be easily configured from options where you can choose from XHTML, FO, and to specify a custom XML Schema or DTD. XSLT Transformations Oxygen allows you to define a stylesheet, an FOP to be applied on your XML document, and how you would like to save or view the transformation result. You can create more transformations for a file, and the current transformation can be executed with one mouse-click or keyboard shortcut. Support for cascading stylesheets is also available. DocBook Documents Support Oxygen plugin includes DocBook DTDs, XML catalog, stylesheets, and document templates so that you can start creating DocBook documents right away. Articles from our site are written in DocBook and their sources are available for download so you can easily have some samples to start from. DocBook documents can be converted to HTML, PDF, or PostScript. TEI Documents Support Oxygen plugin includes TEI DTDs, XML Catalog, stylesheets, and document templates so that you can start working with TEI documents immediately. You can edit documents guided by the context-sensitive Content Completion Assistant, easily validate the edited documents, and transform them to HTML or PDF for presentation. We cooperate with TEI Consortium and are committed to keep the TEI support up to date in future Oxygen releases. Configurable Document Templates Oxygen allows a very flexible document creation process through document templates. You can create new document templates from the editor content and publish your templates to share them with other users. Organizations can maintain a central document templates repository and all the users will be able to create documents using it. Also, Oxygen provides a set of document templates for the most commonly used types of documents. Automatic Generation of Required Content To speed up the content creation, Oxygen can automatically insert the required attributes inside an element and can also automatically insert the required element content of the inserted element. You can also configure the optional content to be inserted, such as the first element from a choice, or the first occurrence of an optional element. Well-Formed Document Checking This check allows you to verify that a document is XML well-formed. This verifies the general document structure and if the structure conforms with a specified XML schema or DTD. Passing this test is a must for a document to be considered an XML document. The well-formedness can be checked at every save operation by simply activating an option in the Oxygen plugin. Validate XML Documents Against W3C XML Schemas, DTDs, Relax NG Schemas, and Namespace Routing Language Schemas Oxygen integrates the latest version of the Xerces-J XML parser to validate documents against XML Schemas. You can also use Oxygen to validate an XML document instance against a specified DTD, Relax NG schemas (both in XML syntax and compact syntax), and Namespace Routing Language schema . Wizard for Schema Association To associate a DTD or a schema with a document, you can use the Associate Schema action that will present a wizard to easily accomplish this task. XSLT Support With Oxygen, you can easily create, edit, test, and validate XSLT documents. The Content Completion Assistant will provide the elements, attributes and attribute values that are specific for XSLT documents. Transformations can be easily configured and run to easily test the XSLT you are creating. You can choose between the most popular XSLT engines (Xalan, Saxon 6.5, Saxon EE) when performing XSLT transformations. You can also configure any JAXP compliant XSLT processor and use it to perform transformations. Other XSLT engines can be configured as external tools. Preview Transformation Oxygen offers an integrated view to show transformation results that will render XML, HTML, or text results. The possibility to show the transformation results in your browser is vital when you are working on a production ready system. For example, this allows you to view HTML or PDF transformation results. XPath Search and Evaluation Oxygen features powerful XPath support, allowing you to both perform XPath searches on an XML document and to evaluate XPath expressions. If location paths are selected by your query, they are presented in the XPath view area together with their text content to allow you to easily visually identify the nodes. Clicking on a result location path will highlight the corresponding part from the document. Note that you can choose to execute your XPath query conforming with the version 1.0 or 2.0 of the standard. FOP Support The Apache FOP is bundled inside Oxygen plugin and it does not require any special configuration to use it. Therefore, you can convert DocBook to PDF or PostScript, for instance, just by setting up a transformation to use the DocBook to FO stylesheet and choose the perform FOP option. If the Apache FOP is not enough for your development and you need to use another FOP, you can very easily add that to Oxygen. In case of XEP, it is even more simple as you just have to browse for its start file. XML Schema, DTD, Relax NG Schema and Namespace Routing Language Schema Support W3C XML Schema documents can be edited and validated with Oxygen. While editing, the user is assisted by the context-sensitive content completion assistance guided by the schema. The schema is validated in accordance with the W3C specification and Oxygen uses the latest version of Xerces-J. The DTD editor features syntax highlighting and validation support. Relax NG schemas can be edited both in XML syntax and in Compact syntax. The Relax NG schemas in XML syntax editing is assisted by the content completion mechanism and validation. Namespace Routing Language schemas can be edited with Oxygen using the Content Completion Assistant and validation. Conversion Between Different Schema Types The Generate/Convert Schema tool (available in the XML. You can convert from a DTD or Relax NG schema (XML or Compact syntax) to a DTD, W3C XML Schema, or Relax NG schema (XML or Compact syntax). Pretty-Print XML Documents XML documents can be formatted and indented with this option in Oxygen. This does a hard wrapping of text content and formatting or to format the elements respectively. Also, you can edit two lists of elements that will be treated as if they have an xml:space attribute with the value "preserve" and "default", respectively. Oxygen also includes some other advanced options for formatting you XML documents. Unicode Support Oxygen offers full Unicode support. The text font for the plugin document editor can be specified independently from the Eclipse settings. >>IMAGE. Mark Selected Text If you have an unstructured document and you want to obtain an XML document, you will find the Surround with option especially useful. This allows you to surround the currently selected text with a specified tag. WSDL Editing and Testing The WSDL files contain information about the published services, such as the name, the message types, and the service bindings. The editor offers you a way to edit WSDL files, which is similar to editing XML. The Content Completion Assistant is driven by a mix of the WSDL and SOAP schema. More that just editing, you can test the definitions directly from the editor. To accomplish this, you can use the integrated WSDL tester. It automatically discovers the services, so you just have to select the service, port, and action, and Oxygen will try to generate as much content as possible for the call skeleton. Usually, you just have to change a few values for the request to be valid. The Content Completion Assistant is available for the request editor and is driven by the schema that defines the current message type. Folding XML Elements Eclipse offers support for folding of Java elements. We have extended it for XML. The folding allows you to collapse elements, leaving only the ones you need to edit in focus. In the following image, you can see that only one of the chapter sections is expanded, while the rest are collapsed. To make the fold operation faster, you can use the contextual menu to collapse or expand all the child folds of an element.
http://www.oxygenxml.com/xml_author/eclipse_plugin.html
CC-MAIN-2019-09
refinedweb
1,845
51.78
I've been having this problem since switching to MVC2. This isn't a new project, so not the usual wrong version type in the web.config file. Anyways, here is the scenario: Two Tables: Projects { public int id { get; set; } public string name { get; set; } } Tasks { public int id { get; set; } public string name { get; set; } public int fk_project_id { get; set; } } I've created these two tables in a linq-2-sql class and I have a strongly typed view of projects. I can loop through the projects just fine, but I get an error when I try to loop through the tasks associated with the projects. "foreach statement cannot operate on variables of type 'System.Data.Linq.EntitySet<Program.Models.Task>' because 'System.Data.Linq.EntitySet<Program.Models.Task>' does not contain a public definition for 'GetEnumerator'" <% foreach (var item in Model) { %> <% foreach (var task in item.Tasks) { %> <% } %> <% } %> View Complete Post I have an app that I am testing with NUNit. The project im testing has several helper classes that are created as public static readonly. When I run the NUnit tests, they all fail with the same error Hi, I recently upgraded to VS 2010. One on of my reports I am getting the following error. Can someone help? The report definition is not valid. Details: The report definition has an invalid target namespace '' which cannot be upgraded.; }???? Hall of Fame Twitter Terms of Service Privacy Policy Contact Us Archives Tell A Friend
http://www.dotnetspark.com/links/28763-entityset-does-not-contain-public-definition.aspx
CC-MAIN-2018-13
refinedweb
246
64.61
. It’s usually used with data from a database, but it’s not limited to databases. For instance, it can also be used with collections of objects and XML. In this post, we’ll see a very simple sample using the GridView. First, let’s define our data. We’ll use a class with a few properties to represent orders. We’ll also define a method to create an array of orders. The properties of the Order class will be the columns and each item in the array will be a row. namespace WebExample.Business { public class Order { public int OrderID { get; set; } public String Customer { get; set; } public DateTime OrderDate { get; set; } public Decimal Total { get; set; } static public Order[] LoadOrders() { List orders = new List<Order>(); Order order = new Order(); order.OrderID = 1001; order.Customer = "Test Customer"; order.OrderDate = new DateTime(2011, 3, 20); order.Total = 1250.50M; orders.Add(order); order = new Order(); order.OrderID = 1002; order.Customer = "Test Customer"; order.OrderDate = new DateTime(2011, 4, 1); order.Total = 2600.0M; orders.Add(order); order = new Order(); order.OrderID = 1003; order.Customer = "Oscar Martinez"; order.OrderDate = new DateTime(2011, 4, 10); order.Total = 800.0M; orders.Add(order); return orders.ToArray(); } } } In a real application, this method would probably read the data from a database and return a DataTable or DataSet. Here we’re using an array of objects to simplify the sample. Next, let’s define the layout of our table. <asp:GridView <Columns> <asp:BoundField <asp:BoundField <asp:BoundField <asp:BoundField </Columns> </asp:GridView> The GridView has the ability to figure out the structure of our data and define the columns of the table. In this case, we want to have control of the layout. With the property AutoGenerateColumns set to false, we’re telling the GridView to not generate the columns for us. Later, inside the <Columns> tag, we define the columns of our table. There are different types of columns available. Here we’re going to use BoundField. This type of column is “tied” to a field. We also have the option to set the header of each column and the format of dates and numbers. Lastly, let’s write the code to load the data and pass it to the GridView with the DataSource property. Later we use the DataBind() method to have the GridView process the data and generate the table. using WebExample.Business; namespace WebExample { public partial class GridTest : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { LoadGrid(); } } private void LoadGrid() { Order[] data = Order.LoadOrders(); GridView1.DataSource = data; GridView1.DataBind(); } } } Now, run the web application. We’ll do some advanced tasks on later posts. Please leave your comments if you have a question or suggestion.
http://blog.oscarscode.com/dot-net/get-started-with-gridview/
CC-MAIN-2019-09
refinedweb
460
61.12
Python: Compute the square of first N Fibonacci numbers, use map function and generate a list of the numbers Python map: Exercise-10 with Solution Write a Python program to compute the square of first N Fibonacci numbers, using map function and generate a list of the numbers. Fibonacci numbers: From Wikipedia, In mathematics, the Fibonacci numbers, commonly denoted Fn, form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, F0 = 0, F1 = 1, and Fn = Fn - 1 + Fn - 2, for n > 1. The beginning of the sequence is thus: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,.... Sample Solution: Python Code : import itertools n = 10 def fibonacci_nums(x=0, y=1): yield x while True: yield y x, y = y, x + y print("First 10 Fibonacci numbers:") result = list(itertools.islice(fibonacci_nums(), n)) print(result) square = lambda x: x * x print("\nAfter squaring said numbers of the list:") print(list(map(square, result))) Sample Output: First 10 Fibonacci numbers: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] After squaring said numbers of the list: [0, 1, 1, 4, 9, 25, 64, 169, 441, 1156] Python Code Editor: Have another way to solve this solution? Contribute your code (and comments) through Disqus. Previous: Write a Python program to create a new list taking specific elements from a tuple and convert a string value to integer. Next: Write a Python program to compute the sum of elements of an given array of integers,
https://www.w3resource.com/python-exercises/map/python-map-exercise-10.php
CC-MAIN-2021-21
refinedweb
265
51.52
Red Hat Bugzilla – Bug 250077 RHEL4 du doesn't report size of unreadable sub directories Last modified: 2007-11-23 12:25:24 EST Description of problem: When using du against a directory target that contains, whithin its tree, non-accessible directories, du will not report the size of these. Since stat can get the size, du should do it as well. Moreover, in the code it seems that this was the intention, but a code bug has prevented this tool to report the size of these directories: -- } else if ((sp->fts_child = fts_build(sp, BREAD)) == NULL) { if (ISSET(FTS_STOP)) return (NULL); /* If fts_build's call to fts_safe_changedir failed because it was not able to fchdir into a subdirectory, tell the caller. */ because it was not able to fchdir into a subdirectory, tell the caller. */ if (p->fts_errno) - p->fts_info = FTS_ERR; + if (p->fts_info != FTS_DNR) + p->fts_info = FTS_ERR; /* FIXME: see if this should be in an else block */ LEAVE_DIR (sp, p, "2"); return (p); -- fts_build will return NULL on problems, and if it couldn't opendir() a directory it will set the flag fts_info to FTS_DNR which is an unreadable directory. So not checking if we just reset the flag and avoid counting the size of that directory, however, if we remember it, we can then stat and count its size. Version-Release number of selected component (if applicable): 5.2.1 How reproducible: Always Steps to Reproduce: 1. cd /tmp 2. mkdir -p du_test/unreadable 3. du -a -b du_test 4096 du_test/unreadable 8192 du_test 4. chmod 000 du_test/unreadable 5. du -b -a du_test du: `du_test/unreadable': Permission denied 4096 du_test Actual results: du: `du_test/unreadable': Permission denied 4096 du_test Only the directories that can be readable are counted. Expected results: du test 4 test/dir du: cannot read directory `test/unreachable-dir': Permission denied 12 test Additional info: Patch attached by Bryan Mason <bjmason@redhat.com> Let me know if you need anything else, Created attachment 160237 [details] Fix report size of unredable subdirectories. Nice one! Thanks. That's a bug upstream,. FYI, I've just applied Jose's patch in upstream gnulib:;a=commitdiff;h=03e1d492b0 Hi, I'm writing the errata for this and I'm pretty sure this behavior occurs on Red Hat Entperise Linux 5: $ cd /tmp $ mkdir -p du_test/unreadable $ du du_test/ 8 du_test/unreadable 16 du_test/ $chmod 000 du_test/unreadable/ $du du_test/ du: `du_test/unreadable': Permission denied 8 du_test/ coreutils: version 5.97, release 12.1.el5 kernel: 2.6.18-8.1.8.el5 Sorry if I've read all of this wrong and it is actually the correct behavior. From this bugzilla I assumed the reponse should be: du test 4 du_test/unreadable du: cannot read directory `du_test/unreadable': Permission denied 12 test Hope this helps. Indeed -- see bug #250087, which this bug.
https://bugzilla.redhat.com/show_bug.cgi?id=250077
CC-MAIN-2017-22
refinedweb
473
52.9
I've two signals, from which I expect that one is responding on the other, but with a certain phase shift. Now I would like to calculate the coherence or the normalized cross spectral density to estimate if there is any causality between the input and output to find out on which frequencies this coherence appear. See for example this image (from here) which seems to have high coherence at the frequency 10: Now I know that I can calculate the phase shift of two signals using the cross-correlation, but how can I use the coherence (of frequency 10) to calculate the phase shift? Code for image: """ Compute the coherence of two signals """ import numpy as np import matplotlib.pyplot as plt # make a little extra space between the subplots plt.subplots_adjust(wspace=0.5) nfft = 256 dt = 0.01 t = np.arange(0, 30, dt) nse1 = np.random.randn(len(t)) # white noise 1 nse2 = np.random.randn(len(t)) # white noise 2 r = np.exp(-t/0.05) cnse1 = np.convolve(nse1, r, mode='same')*dt # colored noise 1 cnse2 = np.convolve(nse2, r, mode='same')*dt # colored noise 2 # two signals with a coherent part and a random part s1 = 0.01*np.sin(2*np.pi*10*t) + cnse1 s2 = 0.01*np.sin(2*np.pi*10*t) + cnse2 plt.subplot(211) plt.plot(t, s1, 'b-', t, s2, 'g-') plt.xlim(0,5) plt.xlabel('time') plt.ylabel('s1 and s2') plt.grid(True) plt.subplot(212) cxy, f = plt.cohere(s1, s2, nfft, 1./dt) plt.ylabel('coherence') plt.show() Let me try to answer my own question and maybe one day it might be useful to others or function as a starting point for a (new) discussion: Firstly calculate the power spectral densities of both the signals, subplot(121) psd(s1, nfft, 1/dt) plt.title('signal1') subplot(122) psd(s2, nfft, 1/dt) plt.title('signal2') plt.tight_layout() show() resulting in: Secondly calculate the cross-spectral density, which is Fourier transform of the cross-correlation function: csdxy, fcsd = plt.csd(s1, s2, nfft, 1./dt) plt.ylabel('CSD (db)') plt.title('cross spectral density between signal 1 and 2') plt.tight_layout() show() Which gives: Than using the cross-spectral density we can calculate the phase and we can calculate the coherence (which will destroy the phase). Now we can combine the coherence and the peaks that rise above the 95% confidence level # coherence cxy, fcoh = cohere(s1, s2, nfft, 1./dt) # calculate 95% confidence level edof = (len(s1)/(nfft/2)) * cxy.mean() # equivalent degrees of freedom: (length(timeseries)/windowhalfwidth)*mean_coherence gamma95 = 1.-(0.05)**(1./(edof-1.)) conf95 = np.where(cxy>gamma95) print 'gamma95',gamma95, 'edof',edof # Plot twin plot fig, ax1 = plt.subplots() # plot on ax1 the coherence ax1.plot(fcoh, cxy, 'b-') ax1.set_xlabel('Frequency (hr-1)') ax1.set_ylim([0,1]) # Make the y-axis label and tick labels match the line color. ax1.set_ylabel('Coherence', color='b') for tl in ax1.get_yticklabels(): tl.set_color('b') # plot on ax2 the phase ax2 = ax1.twinx() ax2.plot(fcoh[conf95], phase[conf95], 'r.') ax2.set_ylabel('Phase (degrees)', color='r') ax2.set_ylim([-200,200]) ax2.set_yticklabels([-180,-135,-90,-45,0,45,90,135,180]) for tl in ax2.get_yticklabels(): tl.set_color('r') ax1.grid(True) #ax2.grid(True) fig.suptitle('Coherence and phase (>95%) between signal 1 and 2', fontsize='12') plt.show() result in: To sum up: the phase of the most coherent peak is ~1 degrees (s1 leads s2) at a 10 min period (assuming dt is a minute measurement) -> (10**-1)/dt But a specialist signal processing might correct me, because I'm like 60% sure if I've done it right
https://codedump.io/share/xKManM2oQBlA/1/how-to-use-the-cross-spectral-density-to-calculate-the-phase-shift-of-two-related-signals
CC-MAIN-2017-43
refinedweb
625
60.01
Hey I am a regular user of Zapier and the power that Zapier gives non-programmers as well as coders is just awesome. I would love if Wix could add Triggers and Actions with Native support for Zapier, it would blow peoples mind if the below could be done... Triggers - Users - When a user logs into my Site - When a new user is registered - When a new user is approved - Data Collection - When a new record is created - When a record is updated - When a record i deleted Actions - Users - Create a new user - Approve a pending site member request - Remove a user - Data Collection - Insert a new records - Update an existing record - Delete a record Just imagine if you go to Zapier, Add Wix in your Zap and choose Trigger "When a new record is created" and it will list the Data Collections you have and then you will get that newly inserted record into your Zap and you can work with the data and then send that to any system within the Zapier Platform or hook up an Action in Wix like "Update an existing record", search for the record, use data from the inserted one and update this one with that. You can work with and create very advanced integrations and workflow with very little coding experience. Hi Andreas, I note that you say "native" support for zapier and there is no import like: import wixZapier from 'wix-zapier' but you can send any request with http-fetch library to a zapier webhook rule you created... Is that your use case? The only issue I would see is if you need to make a zapier rule talk to your wix website as I have not been able to implement API calls to a wix backend yet, i.e., not even the plain vanilla code example that wix provides. Hey I have more than 10 Wix Code Sites already taking both to Zapier and recieves communication from Zapier to backend modules using http-functions modules. But this requires coding by the Wix user. If you could go into Zapier and choose Wix as you can with Google Mail and others that would open this features to more of non-coders and open their possabilities to use this platform together with thousands of others in an easier way. That’s never going to happen lol! I’m a Zapiernuser myself but most of the people don’t like Zapier, idk why, and I’m sure that’s the case with the Wix Code team, they’re simply not intereste. For now continue using webhoks I don't believe Wix Code team is not simply interested in Zapier. Why shouldn't they, more than 1,000 systems will be included in the Wix Code family if they did. I just think that they have so much to do that has a priority that is much higher than this so there is simply no time to do it. Wix Code team is interested in everything that will help the growth of the platform and make happy users. I too am a big Zapier user, integrating a bunch of 3rd party apps (mailparser I/O, Google Sheets, MailChimp, HubSpot, Acuity Scheduling and others. Native support, as described by Andreas, for Zapier in Wix would be huge for me. However, I fear others here might be correct, Wix won't do it. It would cannibalize Wix's own apps that they get revenue from (e-commerce store, online scheduling, mailing, etc.). Just to let you know that we are working on an integration between Wix Automations and Zapier. The way we designed it is that the trigger for the Zap needs to be active automation on Wix Automations (we will improve on that as we go). So, if you'd like to check it out yourself, go to Automations (under the Customer Management section on the dashboard side-menu) and create new automation. You can choose a custom form as the trigger (a form created using Wix Code and connected to a form submission dataset). As an action choose whatever you want ("notify me by email" is the most harmless), and set the timing to "immediately." Click here to accept the invitation to our closed beta on Zapier: Now, create a new Zap: Continue according to the regular flow for creating a Zap (you can skip the tests Zapier is suggesting along the way). You should know what to do from here. Let me know if you have any issues, here or at gil.alroy@wix.com. It says Zapier is having trouble loading the automation data using Wix Automation 1.0.1 using 1.0.0 it doesn't let you connect the Zap to anything. @Brett Franklin Just got same error on April 22nd. Has not been fixed Any progress on this? I just tried to set it up and am having issues. It's not loading automation data, and I don't see anywhere to "Connect to Third Party Apps" as an action when creating a new automation. Hopefully a new release is coming soon! I run a Marketing blog for MBA students. I came across Digital Deepak's Zapier Mastery course and it helped me increase my number of subscribers by 13.8x within 3 days, only because I could use Zapier. I have written about this subscriber growth and about the Zapier Mastery course in my article. Share knowledge! Hi there, Wix Automations in now integrated with Zapier! Zapier allows you to connect your Wix Automations to more than 100 apps, such as Slack or Google Docs, or your Gmail account. Here’s how to get started: Go to your Automations Dashboard. Click + New Automation. Click the title to give your automation a name. Select a trigger. Click Connect to Third-Party Apps. Choose a time for your automation. Click Activate. Then, Log in to your Zapier account. Click Make a Zap! Search for "Wix Automations" under Choose a Trigger App.Select Wix Automations. Click Save + Continue. Click Connect an Account and select your Wix site. Click Allow and Install. Click Save + Continue. Select the automation you want to connect to Zapier.Click Continue. And you Automation is integrated with Zapier!
https://www.wix.com/corvid/forum/community-feature-request/zapier-triggers-and-action-for-wix-code/p-1/dl-5c3493560380c9001cea2773
CC-MAIN-2019-47
refinedweb
1,043
71.04
In this article by Mohsin Hijazee, the author of the book Mastering Google App Engine, we will go through learning, but unlearning something is even harder. The main reason why learning something is hard is not because it is hard in and of itself, but for the fact that most of the times, you have to unlearn a lot in order to learn a little. This is quite true for a datastore. Basically, it is built to scale the so-called Google scale. That's why, in order to be proficient with it, you will have to unlearn some of the things that you know. Your learning as a computer science student or a programmer has been deeply enriched by the relational model so much so that it is natural to you. Anything else may seem quite hard to grasp, and this is the reason why learning Google datastore is quite hard. However, if this were the only glitch in all that, things would have been way simpler because you could ask yourself to forget the relational world and consider the new paradigm afresh. Things have been complicated due to Google's own official documentation, where it presents a datastore in a manner where it seems closer to something such as Django's ORM, Rails ActiveRecord, or SQLAlchemy. However, all of a sudden, it starts to enlist its limitations with a very brief mention or, at times, no mention of why the limitations exist. Since you only know the limitations but not why the limitations are there in the first place, a lack of reason may result to you being unable to work around those limitations or mold your problem space into the new solution space, which is Google datastore. We will try to fix this. Hence, the following will be our goals in this article: - To understand BigTable and its data model - To have a look at the physical data storage in BigTable and the operations that are available in it - To understand how BigTable scales - To understand datastore and the way it models data on top of BigTable So, there's a lot more to learn. Let's get started on our journey of exploring datastore. The BigTable If you decided to fetch every web page hosted on the planet, download and store a copy of it, and later process every page to extract data from it, you'll find out that your own laptop or desktop is not good enough to accomplish this task. It has barely enough storage to store every page. Usually, laptops come with 1 TB hard disk drives, and this seems to be quite enough for a person who is not much into video content such as movies. Assuming that there are 2 billion websites, each with an average of 50 pages and each page weighing around 250 KB, it sums up to around 23,000+ TB (or roughly 22 petabytes), which would need 23,000 such laptops to store all the web pages with a 1 TB hard drive in each. Assuming the same statistics, if you are able to download at a whopping speed of 100 MBps, it would take you about seven years to download the whole content to one such gigantic hard drive if you had one in your laptop. Let's suppose that you downloaded the content in whatever time it took and stored it. Now, you need to analyze and process it too. If processing takes about 50 milliseconds per page, it would take about two months to process the entire data that you downloaded. The world would have changed a lot by then already, leaving your data and processed results obsolete. This is the Kind of scale for which BigTable is built. Every Google product that you see—Search Analytics, Finance, Gmail, Docs, Drive, and Google Maps—is built on top of BigTable. If you want to read more about BigTable, you can go through the academic paper from Google Research, which is available at.... The data model Let's examine the data model of BigTable at a logical level. BigTable is basically a key-value store. So, everything that you store falls under a unique key, just like PHP' arrays, Ruby's hash, or Python's dict: # PHP $person['name'] = 'Mohsin'; # Ruby or Python person['name'] = 'Mohsin' However, this is a partial picture. We will learn the details gradually in a while. So, let's understand this step by step. A BigTable installation can have multiple tables, just like a MySQL database can have multiple tables. The difference here is that a MySQL installation might have multiple databases, which in turn might have multiple tables. However, in the case of BigTable, the first major storage unit is a table. Each table can have hundreds of columns, which can be divided into groups called column families. You can define column families at the time of creating a table. They cannot be altered later, but each column family might have hundreds of columns that you can define even after the creation of the table. The notation that is used to address a column and its column families is like job:title, where job is a column family and title is the column. So here, you have a job column family that stores all the information about the job of the user, and title is supposed to store the job title. However, one of the important facts about these columns is that there's no concept of datatypes in BigTable as you'd encounter in other relational database systems. Everything is just an uninterpreted sequence of bytes, which means nothing to BigTable. What they really mean is just up to you. It might be a very long integer, a string, or a JSON-encoded data. Now, let's turn our attention to the rows. There are two major characteristics of the rows that we are concerned about. First, each row has a key, which must be unique. The contents of the key again consist of an uninterpreted string of bytes that is up to 64 KB in length. A key can be anything that you want it to be. All that's required is that it must be unique within the table, and in case it is not, you will have to overwrite the contents of the row with the same content. Which key should you use for a row in your table? That's the question that requires some consideration. To answer this, you need to understand how the data is actually stored. Till then, you can assume that each key has to be a unique string of bytes within the scope of a table and should be up to 64 KB in length. Now that we know about tables, column families, columns, rows, and row keys, let's look at an example of BigTable that stores 'employees' information. Let's pretend that we are creating something similar to LinkedIn here. So, here's the table: So, 'this is a sample BigTable. The first column is the name, and we have chosen it as a key. It is of course not a good key, because the first name cannot necessarily be unique, even in small groups, let alone in millions of records. However, for the sake of this example, we will assume that the name is unique. Another reason behind assuming the name's uniqueness is that we want to increase our understanding gradually. So, the key point here is that we picked the first name as the row's key for now, but we will improve on this as we learn more. Next, we have two column groups. The personal column group holds all the personal attributes of the employees, and the other column family named professional has all the other attributes pertaining to the professional aspects. When referring to a column within a family, the notation is family:column. So, personal:age contains the age of the employees. If you look at professinal:designation and personal:age, it seems that the first one's contents are strings, while the second one stores integers. That's false. No column stores anything but just plain bytes without any distinction of what they mean. The meaning and interpretation of these bytes is up to the user of the data. From the point of view of BigTable', each column just contains plain old bytes. Another thing that is drastically different from RDBMS is such as MySQL is that each row need not have the same number of columns. Each row can adopt the layout that they want. So, the second row's personal column family can have two more columns that store gender and nationality. For this particular example, the data is in no particular order, and I wrote it down as it came to my mind. Hence, there's no order of any sort in the data at all. To summarize, BigTable is a key-value storage where keys should be unique and have a length that is less than or equal to 64 KB. The columns are divided into column families, which can be created at the time of defining the table, but each column family might have hundreds of columns created as and when needed. Also, contents have no data type and comprise just plain old bytes. There's one minor detail left, which is not important as regards our purpose. However, for the sake of the completeness of the BigTable's data model, I will mention it now. Each value of the column is stored with a timestamp that is accurate to the microseconds, and in this way, multiple versions of a column value are available. The number of last versions that should be kept is something that is configurable at the table level, but since we are not going to deal with BigTable directly, this detail is not important to us. How data is stored? Now that we know about row keys, column families, and columns, we will gradually move towards examining this data model in detail and understand how the data is actually stored. We will examine the logical storage and then dive into the actual structure, as it ends up on the disk. The data that we presented in the earlier table had no order and were listed as they came to my mind. However, while storing, the data is always sorted by the row key. So now, the data will actually be stored like this: OK, so what happened here? The name column indicates the key of the table and now, the whole table is sorted by the key. That's exactly how it is stored on the disk as well. 'An important thing about sorting is lexicographic sorting and not semantic sorting. By lexicographic, we mean that they are sorted by the byte value and not by the textness or the semantic sort. This matters because even within the Latin character set, different languages have different sort orders for letters, such as letters in English versus German and French. However, all of this and the Unicode collation order isn't valid here. It is just sorted by byte values. In our instance, since K has a smaller byte value (because K has a lower ASCII/Unicode value) than letter M, it comes first. Now, suppose that some European language considers and sorts M before K. That's not how the data would be laid out here, because it is a plain, blind, and simple sort. The data is sorted by the byte value, with no regard for the semantic value. In fact, for BigTable, this is not even text. It's just a plain string of bytes. Just a hint. This order of keys is something that we will exploit when modeling data. How? We'll see later. The Physical storage Now that we understand the logical data model and how it is organized, it's time to take a closer look at how this data is actually stored on the disk. On a physical disk, the stored data is sorted by the key. So, key 1 is followed by its respective value, key 2 is followed by its respective value, and so on. At the end of the file, there's a sorted list of just the keys and their offset in the file from the start, which is something like the block to the right: Ignore the block on your left that is labeled Index. We will come back to it in a while. This particular format actually has a name SSTable (String Storage Table) because it has strings (the keys), and they are sorted. It is of course tabular data, and hence the name. Whenever your data is sorted, you have certain advantages, with the first and foremost advantage being that when you look up for an item or a range of items, 'your dataset is sorted. We will discuss this in detail later in this article. Now, if we start from the beginning of the file and read sequentially, noting down every key and then its offset in a format such as key:offset, we effectively create an index of the whole file in a single scan. That's where the first block to your left in the preceding diagram comes from. Since the keys are sorted in the file, we simply read it sequentially till the end of the file, hence effectively creating an index of the data. Furthermore, since this index only contains keys and their offsets in the file, it is much smaller in terms of the space it occupies. Now, assuming that SSTable has a table that is, say, 500 MB in size, we only need to load the index from the end of the file into the memory, and whenever we are asked for a key or a range of keys, we just search within a memory index (thus not touching the disk at all). If we find the data, only then do we seek the disk at the given offset because we know the offset of that particular key from the index that we loaded in the memory. Some limitations Pretty smart, neat, and elegant, you would say! Yes it is. However, there's a catch. If you want to create a new row, key must come in a sorted order, and even if you are sure about where exactly this key should be placed in the file to avoid the need to sort the data, you still need to rewrite the whole file in a new, sorted order along with the index. Hence, large amounts of I/O are required for just a single row insertion. The same goes for deleting a row because now, the file should be sorted and rewritten again. Updates are OK as long as the key itself is not altered because, in that case, it is sort of having a new key altogether. This is so because a modified key would have a different place in the sorted order, depending on what the key actually is. Hence, the whole file would be rewritten. Just for an example, say you have a row with the key as all-boys, and then you change the key of that row to x-rays-of-zebra. Now, you will see that after the new modification, the row will end up at nearly the end of the file, whereas previously, it was probably at the beginning of the file because all-boys comes before x-rays-of-zebra when sorted. This seems pretty limiting, and it looks like inserting or removing a key is quite expensive. However, this is not the case, as we will see later. Random writes and deletion There's one last thing that's worth a mention before we examine the operations that are available on a BigTable. We'd like to examine how random writes and the deletion of rows are handled because that seems quite expensive, as we just examined in the preceding section. The idea is very simple. All the read, writes, and removals don't go straight to the disk. Instead, an in-memory SSTable is created along with its index, both of which are empty when created. We'll call it MemTable from this point onwards for the sake of simplicity. Every read checks the index of this table, and if a record is found from here, it's well and good. If it is not, then the index of the SSTable on the disk is checked and the desired row is returned. When a new row has to be read, we don't look at anything and simply enter the row in the MemTable along with its record in the index of this MemTable. To delete a key, we simply mark it deleted in the memory, regardless of whether it is in MemTable or in the on disk table. As shown here the allocation of block into Mem Table: Now, when the size of the MemTable grows up to a certain size, it is written to the disk as a new SSTable. Since this only depends on the size of the MemTable and of course happens much infrequently, it is much faster. Each time the MemTable grows beyond a configured size, it is flushed to the disk as a new SSTable. However, the index of each flushed SSTable is still kept in the memory so that we can quickly check the incoming read requests and locate it in any table without touching the disk. Finally, when the number of SSTables reaches a certain count, the SSTables are merged and collapsed into a single SSTable. Since each SSTable is just a sorted set of keys, a merge sort is applied. This merging process is quite fast. Congratulations! You've just learned the most atomic storage unit in BigData solutions such as BigTable, Hbase, Hypertable, Cassandara, and LevelDB. That's how they actually store and process the data. Now that we know how a big table is actually stored on the disk and how the read and writes are handled, it's time to take a closer look at the available operations. Operations on BigTable Until this point, we know that a BigTable table is a collection of rows that have unique keys up to 64 KB in length and the data is stored according to the lexicographic sort order of the keys. We also examined how it is laid out on the disk and how read, writes, and removals are handled. Now, the question is, which operations are available on this data? The following are the operations that are available to us: - Fetching a row by using its key - Inserting a new key - Deleting a row - Updating a row - Reading a range of rows from the starting row key to the ending row key Reading Now, the first operation is pretty simple. You have a key, and you want the associated row. Since the whole data set is sorted by the key, all we need to do is perform a binary search on it, and you'll be able to locate your desired row within a few lookups, even within a set of a million rows. In practice, the index at the end of the SSTable is loaded in the memory, and the binary search is actually performed on it. If we take a closer look at this operation in light of what we know from the previous section, the index is already in the memory of the MemTable that we saw in the previous section. In case there are multiple SSTables because MemTable was flushed many times to the disk as it grew too large, all the indexes of all the SSTables are present in the memory, and a quick binary search is performed on them. Writing The second operation that is available to us is the ability to insert a new row. So, we have a key and the values that we want to insert in the table. According to our new knowledge about physical storage and SSTables, we can understand this very well. The write directly happens on the in-memory MemTable and its index is updated, which is also in the memory. Since no disk access is required to write the row as we are writing in memory, the whole file doesn't have to be rewritten on disk, because yet again, all of it is in the memory. This operation is very fast and almost instantaneous. However, if the MemTable grows in size, it will be flushed to the disk as a new SSTable along with the index while retaining a copy of its index in the memory. Finally, we also saw that when the number of SSTables reaches a certain number, they are merged and collapsed to form a new, bigger table. Deleting It seems that since all the keys are in a sorted order on the disk and deleting a key would mean disrupting the sort order, a rewrite of the whole file would be a big I/O overhead. However, it is not, as it can be handled smartly. Since all the indexes, including the MemTable and the tables that were the result of flushing a larger MemTable to the disk, are already in the memory, deleting a row only requires us to find the required key in the in-memory indexes and mark it as deleted. Now, whenever someone tries to read the row, the in-memory indexes will be checked, and although an entry will be there, it will be marked as deleted and won't be returned. When MemTable is being flushed to the disk or multiple tables are being collapsed, this key and the associated row will be excluded in the write process. Hence, they are totally gone from the storage. Updating Updating a row is no different, but it has two cases. The first case is in which not only the values, but also the key is modified. In this case, it is like removing the row with an old key and inserting a row with a new key. We already have seen both of these cases in detail. So, the operation should be obvious. However, the case where only the values are modified is even simpler. We only have to locate the row from the indexes, load it in the memory if it is not already there, and modify. That's all. Scanning a range This last operation is quite interesting. You can scan a range of keys from a starting key to an ending key. For instance, you can return all the rows that have a key greater than or equal to key1 and less than or equal to key2, effectively forming a range. Since the looking up of a single key is a fast operation, we only have to locate the first key of the range. Then, we start reading the consecutive keys one after the other till we encounter a key that is greater than key2, at which point, we will stop the scanning, and the keys that we scanned so far are our query's result. This is how it looks like: In the preceding table, we said that the starting key will be greater than or equal to Ernest and ending key will be less than or equal to Kathryn. So, we locate the first key that is greater than or equal to Ernest, which happens to be Ernest Morrison. Then, we start scanning further, picking and returning each key as long as it is less than or equal to Kathryn. When we reach Judy, it is less than or equal to Kathryn, but Kathryn isn't. So, this row is not returned. However, the rows before this are returned. This is the last operation that is available to us on BigTable. Selecting a key Now that we have examined the data model and the storage layout, we are in a better position to talk about the key selection for a table. As we know that the stored data is sorted by the key, it does not impact the writing, deleting, and updating to fetch a single row. However, the operation that is impacted by the key is that of scanning a range. Let's think about the previous table again and assume that this table is a part of some system that processes payrolls for companies, and the companies pay us for the task of processing their payroll. Now, let's suppose that Sony asks us to process their data and generate a payroll for them. Right now, we cannot do anything of this kind. We can just make our program scan the whole table, and hence all the records (which might be in millions), and only pick the records where job:company has the value of Sony. This would be inefficient. Instead, what we can do is put this sorted nature of row keys to our service. Select the company name as the key and concatenate the designation and name along with it. So, the new table will look like this: So, this is a new format. We just welded the company, department, and name as the key and as the table will always be sorted by the key, that's what it looks like, as shown in the preceding table. Now, suppose that we receive a request from Google to process their data. All we have to do is perform a scan, starting from the key greater than or equal to Google and less then L because that's the next letter. This scan is highlighted in the previous table. Now, the next request is more specific. Sony asks us to process their data, but only for their accounting department. How do we do that? Quite simple! In this case, our starting key will be greater than or equal to Sony-Accounting, and the ending key can be Sony-Accountinga, where a is appended to indicate the end key in the range. The scanned range and the returned rows are highlighted in the previous table. BigTable – a hands-on approach Okay, enough of the theory. It is now time to take a break and perform some hands-on experimentation. By now, we know that about 80 percent of the BigTable and the other 20 percent of the complexity is scaling it to more than one machine. Our current discussion only assumed and focused on a single machine environment, and we assumed that the BigTable table is on our laptop and that's about it. You might really want to experiment with what you learned. Fortunately, given that you have the latest version of Google Chrome or Mozilla Firefox, that's easy. You have BigTable right there! How? Let me explain. Basically, from the ideas that we looked at pertaining to the stored key value, the sorted layout, the indexes of the sorted files, and all the operations that were performed on them, including scanning, we extracted a separate component called LevelDB. Meanwhile, as HTML was evolving towards HTML5, a need was felt to store data locally. Initially, SQLite3 was embedded in browsers, and there was a querying interface for you to play with. So all in all, you had an SQL database in the browser, which yielded a lot of possibilities. However, in recent years, W3C deprecated this specification and urged browser vendors to not implement it. Instead of web databases that were based on SQLite3, they now have databases based on LevelDB that are actually key-value stores, where storage is always sorted by key. Hence, besides looking up for a key, you can scan across a range of keys. Covering the IndexedDB API here would be beyond the scope of this book, but if you want to understand it and find out what the theory that we talked about looks like in practice, you can try using IndexedDB in your browser by visiting. The concepts of keys and the scanning of key ranges are exactly like those that we examined here as regards BigTable, and those about indexes are mainly from the concepts that we will examine in a later section about datastores. Scaling BigTable to BigData By now, you have probably understood the data model of BigTable, how it is laid out on the disk, and the advantages it offers. To recap once again, the BigTable installation may have many tables, each table may have many column families that are defined at the time of creating the table, and each column family may have many columns, as required. Rows are identified by keys, which have a maximum length of 64 KB, and the stored data is sorted by the key. We can receive, update, and delete a single row. We can also scan a range of rows from a starting key to an ending key. So now, the question comes, how does this scale? We will provide a very high-level overview, neglecting the micro details to keep things simple and build a mental model that is useful to us as the consumers of BigTable, as we're not supposed to clone BigTable's implementation after all. As we saw earlier, the basic storage unit in BigTable is a file format called SSTable that stores key-value pairs, which are sorted by the key, and has an index at its end. We also examined how the read, write, and delete work on an in-memory copy of the table and merged periodically with the table that is present on the disk. Lastly, we also mentioned that when the in memory is flushed as SSTables on the disk when reach a certain configurable count, they are merged into a bigger table. The view so far presents the data model, its physical layout, and how operations work on it in cases where the data resides on a single machine, such as a situation where your laptop has a telephone directory of the entire Europe. However, how does that work at larger scales? Neglecting the minor implementation details and complexities that arise in distributed systems, the overall architecture and working principles are simple. In case of a single machine, there's only one SSTable (or a few in case they are not merged into one) file that has to be taken care of, and all the operations have to be performed on it. However, in case this file does not fit on a single machine, we will of course have to add another machine, and half of the SSTable will reside on one machine, while the other half will be on the another machine. This split would of course mean that each machine would have a range of keys. For instance, if we have 1 million keys (that look like key1, key2, key3, and so on), then the keys from key1 to key500000 might be on one machine, while the keys from key500001 to key1000000 will be on the second machine. So, we can say that each machine has a different key range for the same table. Now, although the data resides on two different machines, it is of course a single table that sprawls over two machines. These partitions or separate parts are called tablets. Let's see the Key allocation on two machines: We will keep this system to only two machines and 1 million rows for the sake of discussion, but there may be cases where there are about 20 billion keys sprawling over some 12,000 machines, with each machine having a different range of keys. However, let's continue with this small cluster consisting of only two nodes. Now, the problem is that as an external user who has no knowledge of which machine has which portion of the SSTable (and eventually, the key ranges on each machine), how can a key, say, key489087 be located? For this, we will have to add something like a telephone directory, where I look up the table name and my desired key and I get to know the machine that I should contact to get the data associated with the key. So, we are going to add another node, which will be called the master. This master will again contain simple, plain SSTable, which is familiar to us. However, the key-value pair would be a very interesting one. Since this table would contain data about the other BigTable tables, let's call it the METADATA table. In the METADATA table, we will adopt the following format for the keys: - tablename_ending-row-key - Since we have only two machines and each machine has two tablets, the METADATA table will look like this: The master stores the location of each tablet server with the row key that is the encoding of the table name and the ending row of the tablet. So, the tablet has to be scanned. The master assigns tablets to different machines when required. Each tablet is about 100 MB to 200 MB in size. So, if we want to fetch a key, all we need to know is the following: - Location of the master server - Table in which we are looking for the key - The key itself Now, we will concatenate the table name with the key and perform a scan on the METADATA table on the master node. Let's suppose that we are looking for key600000 in employees table. So, we would first be actually looking for the employees_key600000 key in the table on master machine. As you are familiar with the scan operation on SSTable (and METADATA is just an SSTable), we are looking for a key that is greater than or equal to employees_key600000, which happens to be employees_key1000000. From this lookup, the key that we get is employees_key1000000 against which, IP address 192.168.0.3 is listed. This means that this is the machine that we should connect to fetch our data. We used the word keys and not the key because it is a range scan operation. This will be clearer with another example. Let's suppose that we want to process rows with keys starting from key400000 to key800000. Now, if you look at the distribution of data across the machine, you'll know that half of the required range is on one machine, while the other half is on the other. Now, in this case, when we consult the METADATA table, two rows will be returned to us because key400000 is less then key500000 (which is the ending row key for data on the first machine) and key800000 is less then key1000000, which is the ending row for the data on the second machine. So, with these two rows returned, we have two locations to fetch our data from. This leads to an interesting side-effect. As the data resides on two different machines, this can be read or processed in parallel, which leads to an improved system performance. This is one reason why even with larger datasets, the performance of BigTable won't deteriorate as badly as it would have if it were a single, large machine with all the data on it. The datastore thyself So until now, everything that we talked about was about BigTable, and we did not mention datastore at all. Now is the time to look at datastore in detail because we understand BigTable quite well now. Datastore is an effectively solution that was built on top of BigTable as a persistent NoSQL layer for Google App Engine. As we know that BigTable might have different tables, data for all the applications is stored in six separate tables, where each table stores a different aspect or information about the data. Don't worry about memorizing things about data modeling and how to use it for now, as this is something that we are going to look into in greater detail later. The fundamental unit of storage in datastore is called a property. You can think of a property as a column. So, a property has a name and type. You can group multiple properties into a Kind, which effectively is a Python class and analogous to a table in the RDBMS world. Here's a pseudo code sample: # 1. Define our Kind and how it looks like. class Person(object): name = StringProperty() age = IntegerProperty() # 2. Create an entity of kind person ali = Person(name='Ali', age='24) bob = Person(name='Bob', age='34) david = Person(name='David', age='44) zain = Person(name='Zain', age='54) # 3. Save it ali.put() bob.put() david.put() zain.put() This looks a lot like an ORM such as Django's ORM, SQLAlchemy, or Rails ActiveRecord. So, Person class is called a Kind in App Engine's terminology. The StringProperty and IntegerProperty property classes are used to indicate the type of the data that is supposed to be stored. We created an instance of the Person class as mohsin. This instance is called an entity in App Engine's terminology. Each entity, when stored, has a key that is not only unique throughout your application, but also combined with your application ID. It becomes unique throughout all the applications that are hosted over Google App Engine. All entities of all kinds for all apps are stored in a single BigTable, and they are stored in a way where all the property values are serialized and stored in a single BigTable column. Hence, no separate columns are defined for each property. This is interesting and required as well because if we are Google App Engine's architects, we do not know the Kind of data that people are going to store or the number and types of properties that they would define so that it makes sense to serialize the whole thing as one and store them in one column. So, this is how it looks like: The key appears to be random, but it is not. A key is formed by concatenating your application ID, your Kind name (Person here), and either a unique identifier that is auto generated by Google App Engine, or a string that is supplied by you. The key seems cryptic, but it is not safe to pass it around in public, as someone might decode it and take advantage of it. Basically, it is just base 64 encoded and can easily be decoded to know the entity's Kind name and ID. A better way would be to encrypt it using a secret key and then pass it around in public. On the other hand, to receive it, you will have to decrypt it using the same key. A gist of this is available on GitHub that can serve the purpose. To view this, visit. However, for it to work, you need to edit your app.yaml file so that it includes the following: libraries: - name: pycrypto version: latest Then, you can call the encrypt() method on the key while passing around and decrypt it back using the decrypt() method, as follows: person = Person(name='peter', age=10) key = person.put() url_safe_key = key.urlsafe() safe_to_pass_around = encrypt(SECRET_KEY, url_safe_key) Now, when you have a key from the outside, you should first decrypt it and then use it, as follows: key_from_outside = request.params.get('key') url_safe_key = decrypt(SECRET_KEY, key_from_outside) key = ndb.Key(urlsafe=url_safe_key) person = key.get() The key object is now good for use. To summarize, just get the URL safe key by calling the ndb.Key.urlsafe() method and encrypt it so that it can be passed around. On return, just do the reverse. If you really want to see how the encrypt and decrypt operations are implemented, they are reproduced as follows without any documentation/comments, as cryptography is not our main subject: import os import base64 from Crypto.Cipher import AES BLOCK_SIZE = 32 PADDING='#' def _pad(data, pad_with=PADDING): return data + (BLOCK_SIZE - len(data) % BLOCK_SIZE) * PADDING def encrypt(secret_key, data): cipher = AES.new(_pad(secret_key, '@')[:32]) return base64.b64encode(cipher.encrypt(_pad(data))) def decrypt(secret_key, encrypted_data): cipher = AES.new(_pad(secret_key, '@')[:32]) return cipher.decrypt(base64.b64decode (encrypted_data)).rstrip(PADDING) KEY='your-key-super-duper-secret-key-here-only-first-32-characters-are-used' decrypted = encrypt(KEY, 'Hello, world!') print decrypted print decrypt(KEY, decrypted) More explanation on how this works is given at. Now, let's come back to our main subject, datastore. As you can see, all the data is stored in a single column, and if we want to query something, for instance, people who are older than 25, we have no way to do this. So, how will this work? Let's examine this next. Supporting queries Now, what if we want to get information pertaining to all the people who are older than, say, 30? In the current scheme of things, this does not seem to be something that is doable, because the data is serialized and dumped, as shown in the previous table. Datastore solves this problem by putting the sorted values to be queried upon as keys. So here, we want to query by age. Datastore will create a record in another table called the Index table. This index table is nothing but just a plain BigTable, where the row keys are actually the property value that you want to query. Hence, a scan and a quick lookup is possible. Here's how it would look like: Implementation details So, all in all, Datastore actually builds a NoSQL solution on top of BigTable by using the following six tables: - A table to store entities - A table to store entities by kind - A table to store indexes for the property values in the ascending order - A table to store indexes for the property values in the descending order - A table to store indexes for multiple properties together - A table to keep a track of the next unique ID for Kind Let us look at each table in turn. The first table is used to store entities for all the applications. We have examined this in an example. The second table just stores the Kind names. Nothing fancy here. It's just some metadata that datastore maintains for itself. Think of this—you want to get all the entities that are of the Person Kind. How will you do this? If you look at the entities table alone and the operations that are available to us on a BigTable table, you will know that there's no such way for us to fetch all the entities of a certain Kind. This table does exactly this. It looks like this: So, as you can see, this is just a simple BigTable table where the keys are of the [app ID]-[Kind name]-[entity key] pattern. The tables 3, 4, and 5 from the six tables that were mentioned in the preceding list are similar to the table that we examined in the Supporting queries section labeled Data as stored in BigTable. This leaves us with the last table. As you know that while storing entities, it is important to have a unique key for each row. Since all the entities from all the apps are stored in a single table, they should be unique across the whole table. When datastore generates a key for an entity that has to be stored, it combines your application ID and the Kind name of the entity. Now, this much part of the key only makes it unique across all the other entities in the table, but not within the set of your own entities. To do this, you need a number that should be appended to this. This is exactly similar to how AUTO INCREMENT works in the RDBMS world, where the value of a column is automatically incremented to ensure that it is unique. So, that's exactly what the last table is for. It keeps a track of the last ID that was used by each Kind of each application, and it looks like this: So, in this table, the key is of the [application ID]-[Kind name] format, and the value is the next value, which is 65 in this particular case. When a new entity of kind Person is created, it will be assigned 65 as the ID, and the row will have a new value of 66. Our application has only one Kind defined, which is Person. Therefore, there's only one row in this table because we are only keeping track for the next ID for this Kind. If we had another Kind, say, Group, it will have its own row in this table. Summary We started this article with the problem of storing huge amounts of data, processing it in bulk, and randomly accessing it. This arose from the fact that we were ambitious to store every single web page on earth and process it to extract some results from it. We introduced a solution called BigTable and examined its data model. We saw that in BigTable, we can define multiple tables, with each table having multiple column families, which are defined at the time of creating the table. We learned that column families are logical groupings of columns, and new columns can be defined in a column family, as needed. We also learned that the data store in BigTable has no meaning on its own, and it stores them just as plain bytes; its interpretation and meanings depend on the user of data. We also learned that each row in BigTable has a unique row key, which has a length of 64 KB. Lastly, we turned our attention to datastore, a NoSQL storage solution built on top of BigTable for Google App Engine. We briefly mentioned some datastore terminology such as properties (columns), entities (rows), and kinds (tables). We learned that all data is stored across six different BigTable tables. This captured a different aspect of data. Most importantly, we learned that all the entities of all the apps hosted on Google App Engine are stored in a single BigTable and all properties go to a single BigTable column. We also learned how querying is supported by additional tables that are keyed by the property values that list the corresponding keys. This concludes our discussion on Google App Engine's datastore and its underlying technology, workings, and related concepts. Next, we will learn how to model our data on top of datastore. What we learned in this chapter will help us enormously in understanding how to better model our data to take full advantage of the underlying mechanisms. Resources for Article: Further resources on this subject: - Google Guice[article] - The EventBus Class[article] - Integrating Google Play Services [article]
https://www.packtpub.com/books/content/understanding-datastore
CC-MAIN-2017-22
refinedweb
7,803
68.1
. Step 2: Let's Get Started Open Flash and create a new Flash File (ActionScript 3). Set the stage size to 600x350 and add a gray radial gradient (#EEEEEE, #DDDDDD). Step 3: Adding a Preloader We're going to add a preloading animation to tell the user when the content is loading. In this case I used the Apple inspired preloader that we created before. Since we're going to use only the animation, there's no need to import the class or use an Export Identifier. Place the preloader on the stage and center it. Step 4: Embedding a Font We're going to embed a font, a super easy task when adding a TextField to the Stage in the Flash IDE, but a little different using ActionScript. Open the Library Panel and right-click in the items area without selecting one, a contextual menu will appear. Click on "New Font" to open a dialog window, give a name to your font and select the one you want to use as shown in the following image. This will create a class of the font you selected, we'll instantiate this in Step 9. Step 5: XML Let's create the XML file. Open your prefered XML or Text editor and write: <?xml version="1.0" encoding="UTF-8"?> <images> <image src="images/image.jpg" title="This is image 1"/> <image src="images/image2.jpg" title="This is image 2"/> <image src="images/image3.jpg" title="This is image 3"/> <image src="images/image4.jpg" title="This is image 4"/> <image src="images/image5.jpg" title="This is image 5"/> </images> When you're done, save it as "images.xml" in your xml folder. Step 6: ActionScript The code that we'll use will be written in a single class that will be used as the Document Class in the FLA file. Create a new ActionScript File (File > New) Save it as "Main.as". Step 7: Package We'll begin with: package classes { The package keyword allows you to organize your code into groups that can be imported by other scripts, it's recommended to name them starting with a lowercase letter and use intercaps for subsequent words for example: galleryClasses. If you don't want to group your files in a package or you have only one class, you can use it right from your source folder, but the idea is to be organized. Step 8: Required Classes import flash.display.Sprite; import flash.display.MovieClip; import flash.net.URLLoader; import flash.net.URLRequest; import flash.display.Loader; import flash.events.Event; import flash.filters.BitmapFilter; import flash.filters.DropShadowFilter; import flash.text.TextFormat; import flash.text.TextField; import flash.text.AntiAliasType; import flash.events.MouseEvent; import fl.transitions.Tween; import fl.transitions.easing.Strong; import fl.transitions.TweenEvent; These are the classes that we'll need to make this gallery. If you need help with a specific class please use the Flash Help (F1). Step 9: Extending the Class public class Main extends MovieClip { The extends keyword defines a class that is a subclass of another class. The subclass inherits all the methods, properties and functions, that way we can use them in our class. We're going to use MovieClip specific methods and properties so we extend using the MovieClip Class. Step 10: Variables var xml:XML; // The XML Object that will parse the XML File var images:Array = new Array(); //This array will store the images loaded var imagesLoaded:int = 0; //A counter, counts the images loaded var imagesTitle:Array = new Array(); //The title properties of the XML File var tween:Tween; //Handles the animation var zoomed:Boolean = false; //Checks if a picture is zoomed, false by default var canClick:Boolean = true; //Checks if the user can click a picture to zoom it, true by default var lastX:int; //Stores the x property of the last picture that was clicked var lastY:int; //Stores the y property of the last picture that was clicked var textformat:TextFormat = new TextFormat(); //A TextFormat Object var screen:Sprite = new Sprite(); //A black screen to focus on the active picture var formatFont:Avenir = new Avenir(); //This is the embedded font Step 11: Constructor The constructor is a function that runs when an object is created from a class. This code is the first to execute when you make an instance of an object or when using the Document Class. In this function we'll set the properties of the TextFormat object that we'll use to display a title or a description of each image. Create the black screen that appears when the user clicks on a picture and call the function which loads the desired XML file. public function Main():void { textformat.color = 0xFFFFFF; textformat.font = formatFont.fontName; textformat.size = 17; //Use the same size you used when embedding the font from the Library screen.graphics.beginFill(0x111111, .75); screen.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight); screen.graphics.endFill(); loadXML("xml/images.xml"); } Step 12: XML Loader Function This function loads the XML file provided by the "file" parameter. We also add a listener to handle when the load is complete. private function loadXML(file:String):void { var urlLoader:URLLoader = new URLLoader(); var urlReq:URLRequest = new URLRequest(file); urlLoader.load(urlReq); urlLoader.addEventListener(Event.COMPLETE, handleXML); } Step 13: Parse XML Here we convert the loaded XML file to a valid XML object using the parameter "data" of the URLLoader. Then we use a "for" statement to create a Loader for every image in the XML. Additional information is found in the commentary. private function handleXML(e:Event):void { xml = new XML(e.target.data); for (var i:int = 0; i < xml.children().length(); i++) { var loader:Loader = new Loader(); loader.load(new URLRequest(String(xml.children()[i].@src))); images.push(loader); //Adds the Loaders to the images Array to gain access to them outside this function imagesTitle.push(xml.children()[i].@title); //Adds the title attribute content to the array to use it outside this function loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaded); //A listener to the function that will be executed when an image is loaded } } Step 14: Images Loaded When a Loader has loaded an image from the XML, the following code is executed: private function loaded(e:Event):void { imagesLoaded++; //Adds one to the imagesLoaded variable if (xml.children().length() == imagesLoaded) //When all images are loaded... { removeChild(preloader); //Removes the Preloader MovieClip prepareImages(); //This function is explained in the next step } } Step 15: Prepare Images This function will add the frame, the TextField to display the title or description, the black background used for that and a Shadow Filter. Let's take it in parts. private function prepareImages():void { for (var i:int = 0; i < images.length; i++) //These actions will be applied to all the images loaded so we use a "for" and the "images" array to do that { var container:Sprite = new Sprite(); //A container that will store the image, frame, TextField, TextField background and shadow var frame:Sprite = new Sprite(); //The Frame Sprite var infoArea:Sprite = new Sprite(); //The TextField background var infoField:TextField = new TextField(); //The TextField Step 16: Image Frame This creates a white frame around the image. frame.graphics.beginFill(0xFFFFFF); frame.graphics.drawRect(-20, -20, images[i].width + 40, images[i].height + 80); frame.graphics.endFill(); The rectangle will be positioned under the image to be used as a frame. Step 17: Information Background This creates a black rectangle in the bottom part of the image, where the TextField will be. infoArea.graphics.beginFill(0x111111, 0.75); infoArea.graphics.drawRect(0, 0, images[i].width, 60); infoArea.graphics.endFill(); infoArea.y = images[i].height - 60; Step 18: Image Information The following code sets the TextField properties and adds its contents. infoField.defaultTextFormat = textformat; infoField.embedFonts = true; //You have to add this to use the embedded font infoField.antiAliasType = AntiAliasType.ADVANCED; //This property will display the text more clearly infoField.width = images[i].width - 5; infoField.height = 20; infoField.text = imagesTitle[i]; //The content, obtained from the XML and stored in the Array Step 19: Resizing the Images Here we set the desired scale of the images. Since everything will be inside the Container Sprite, we only need to resize it. container.scaleX = 0.3; container.scaleY = 0.3; Step 20: Position The images will have a random position based on the center of the Stage area. We use Math for that. container.x = stage.stageWidth / 4 + Math.floor(Math.random() * (stage.stageWidth / 4)); container.y = stage.stageHeight / 5 + Math.floor(Math.random() * (stage.stageHeight / 5)); Step 21: Shadow Filter This will create a Shadow Filter. var shadowFilter:BitmapFilter = new DropShadowFilter(3, 90, 0x252525, 1, 2, 2, 1, 15); //Distance, angle, color, alpha, blur, strength, quality var filterArray:Array = [shadowFilter]; container.filters = filterArray; //Apply the filter Step 22: Adding to Stage Time to add the Children, the order in which we add them is the order they will take in the Display List, so be sure to add them in this way. infoArea.addChild(infoField); //Adds the TextField to the TextField Background container.addChild(frame); //Adds the Frame to the Container container.addChild(images[i]); //Adds the Image on top of the Frame in the Container infoArea.visible = false; //We set the image information to invisible by default container.addChild(infoArea); //Adds the information area in top of everything Step 23: Listeners Although we could add the Listeners to every Sprite before, I'm going to add them now that they are inside the Container to show you how the Display List works. container.getChildAt(1).addEventListener(MouseEvent.MOUSE_UP, zoomHandler); //This is the Image loaded by the XML, this is the Loader object container.getChildAt(0).addEventListener(MouseEvent.MOUSE_DOWN, dragImage); //This is the Frame container.getChildAt(0).addEventListener(MouseEvent.MOUSE_UP, stopDragImage); //Frame addChild(container); //Lastly, we add the Container to the Stage Step 24: Drag Functions In the previous step we added two listeners to the Frame of the images. These functions will take care of the drag. We use "parent" beacuse we want to drag all the objects, since the "target" is the Frame Sprite, the parent object is the Container. private function dragImage(e:MouseEvent):void { e.target.parent.startDrag(); } private function stopDragImage(e:MouseEvent):void { e.target.parent.stopDrag(); } Step 25: Zoom This function is in charge of zooming in and out. Its Listener is in the actual image, so clicking in the Frame will not call this function. Editor's Note: For some reason, the else if () statement within this zoomHandler function was making our syntax highlighter crash. As it doesn't want to display on the page, I've made the function available for download. Sorry for any inconvenience, Ian. Step 26: Motion Finish Some actions need to be executed when the Tweens are finished, these are those actions. private function zoomInFinished(e:TweenEvent):void { zoomed = true; //Modify the variables according to the event canClick = true; tween.obj.getChildAt(2).visible = true; //Sets the Information area to visible } private function zoomOutFinished(e:TweenEvent):void { zoomed = false; removeChild(screen); //Removes the black screen tween.obj.getChildAt(0).addEventListener(MouseEvent.MOUSE_DOWN, dragImage); //Adds the drag listener back to the Frame Sprite } Step 27: Document Class Go back to the FLA and add Main as the Document Class in the Properties Panel. If you save your class in a package you have to add the name of the package too, something like: yourpackage.Main Test your file and see your gallery working! Conclusion As always, try different things in your code to make the gallery just as you want. I hope you enjoyed this tut, thanks for reading! Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
https://code.tutsplus.com/tutorials/create-a-shuffle-gallery-in-flash-using-xml-and-actionscript-30--active-1369
CC-MAIN-2019-22
refinedweb
1,971
56.86
#include <LiquidCrystal.h>LiquidCrystal lcd(12, 11, 6, 5, 4, 3);volatile int coins = 0;void setup(){ lcd.begin(16, 2); Serial.begin(9600); attachInterrupt(0, coinInserted, CHANGE );}void coinInserted(){//delay(1000); coins = coins + 1;}void loop(){ lcd.setCursor(1,0); lcd.print(coins);} attachInterrupt(0, coinInserted, CHANGE ); I have been searching but i haven't found any link for the datasheet of the coin acceptor. vendor explained briefly what output is generated when coins are inserted. Yes i am certain that it is one of the fixed products. Worse, too many pulses were being generated: the Five peso coin churns out 40 pulses; the ten peso coin generates 80 pulses! Even at its fastest pulse rate setting, one will have to wait 40 seconds before the acceptor finishes the pulse transfer of a 10 peso coin. Just a Quick Question about Arduino...If i'm using PIN 2 as Interrupt pin, does the required voltage, being above 3V is HIGH and below 3V is LOW, still a necessity? #include <LiquidCrystal.h>LiquidCrystal lcd(12, 11, 6, 5, 4, 3);volatile int coins = 0;void setup(){ lcd.begin(16, 2); pinMode (2,INPUT_PULLUP); attachInterrupt(0, coinInserted, FALLING);}void coinInserted(){ coins = coins + 1;}void loop(){ lcd.setCursor(1,0); lcd.print(coins);} Please enter a valid email to subscribe We need to confirm your email address. To complete the subscription, please click the link in the Thank you for subscribing! Arduino via Egeo 16 Torino, 10131 Italy
http://forum.arduino.cc/index.php?topic=138209.msg1038091
CC-MAIN-2015-06
refinedweb
246
57.37
23 October 2007 11:57 [Source: ICIS news] LONDON (ICIS news)--Third quarter net profits at SABIC were 37% higher than the year ago period at SR7.4bn ($1.98bn) including a first-time contribution for the advanced plastics businesses acquired earlier in the year from GE, it said on Tuesday. Saudi Basic Industries Corp (SABIC) said that higher prices and new capacities had helped lift nine-month 2007 operating profits 37% to SR29.6bn. Nine-months net profit was up 42% at SR20.2bn. Nine-month sales were up 36% at SR86.5bn. Volume production and sales were up 13% over the period, SABIC said. The SABIC expansions on-stream so far this year include a Jubail United Petrochemical company (United) ethylene glycol plant, urea and ammonia plants at Saudi Arabian Fertilizer Company (Safco) and a reinforced steel plant at Saudi Iron & Steel Company (Hadeed). Production was also added in the ?xml:namespace> The Saudi Arabian petrochemicals, fertiliser and steel giant said its newly created SABIC Innovative Plastics (SIP) business would carry the full finance costs of its $11.6bn acquisition of GE Plastics that it completed in August. ($1 = SR
http://www.icis.com/Articles/2007/10/23/9072121/sabic-q3-net-profit-up-37-on-new-capacity.html
CC-MAIN-2015-22
refinedweb
192
53.41
This notebook originally appeared as a post on the blog Pythonic Perambulations. The content is BSD licensed. A github repo with some of the code appearing below can be found. Too often, tutorials about optimizing Python use trivial or toy examples which may not map well to the real world. I've certainly been guilty of this myself. Here, I'm going to take a different route: in this post I will outline the process of understanding, implementing, and optimizing a non-trivial algorithm in Python, in this case the Non-uniform Fast Fourier Transform (NUFFT). Along the way, we'll dig into the process of optimizing Python code, and see how a relatively straightforward pure Python implementation, with a little help from Numba, can be made to nearly match the performance of a highly-optimized Fortran implementation of the same algorithm. First, I want to answer the inevitable question: why spend the time to make a Python implementation of an algorithm that's already out there in Fortran? The reason is that I've found in my research and teaching that pure-Python implementations of algorithms are far more valuable than C or Fortran implementations, even if they might be a bit slower. This is for a number of reasons: Pure-Python code is easier to read, understand, and contribute to. Good Python implementations are much higher-level than C or Fortran, and abstract-away loop indices, bit twiddling, workspace arrays, and other sources of code clutter. A typical student reading good Python code can immediately understand and modify the algorithm, while the same student would be lost trying to understand typical optimized Fortran code. Pure-python packages are much easier to install than Python-wrapped C or Fortran code. This is especially true on non-Linux systems. Fortran in particular can require some installation prerequisites that are non-trivial for many users. In practice, I've seen people give up on better tools when there is an installation barrier for those tools. Pure-python code often works for many data types. Because of the way it is written, pure Python code is often automatically applicable to single or double precision, and perhaps even to extensions to complex numbers. For compiled packages, supporting and compiling for all possible types can be a burden. Pure-python is easier to use at scale. Because it does not require complicated installation, pure Python packages can be much easier to install on cloud VMs and/or shared clusters for computation at scale. If you can easily pip-install a pure-Python package on a VM, then services like AWS and TravisCI are much easier to set up. Certainly code speed will overcome these considerations if the performance gap is great enough, but I've found that for many applications a pure Python package, cleverly designed and optimized, can be made fast enough that these larger considerations win-out. The challenge is making the Python fast. We'll explore this below. The Fast Fourier Transform (FFT) is perhaps the most important and fundamental of modern numerical algorithms. It provides a fast, $O[N\log N]$ method of computing the discrete Fourier transform: $$ Y_k^\pm = \sum_{n=0}^{N-1} y_n e^{\pm i k n / N} $$ You can read more about the FFT in my previous post on the subject. One important limitation of the FFT is that it requires that input data be evenly-spaced: that is, we can think of the values $y_n$ as samples of a function $y_n = y(x_n)$ where $x_n = x_0 + n\Delta x$ is a regular grid of points. But what about when your grid is not uniform? That is, what if you want to compute this result: $$ Y_k^\pm = \sum_{j=1}^N y(x_j) e^{\pm i k x_j} $$ where $y(x)$ is evaluated at an arbitrary set of points $x_j$? In this case, the FFT is no longer directly applicable, and you're stuck using a much slower $O[N^2]$ direct summation. Stuck, that is, until the NUFFT came along. The NUFFT is an algorithm which converts the non-uniform transform into an approximate uniform transform, not with error-prone interpolation, but instead using a clever "gridding" operation motivated by the convolution theorem. If you'd like to read about the algorithm in detail, the Courant Institute's NUFFT page has a nice set of resources. Below we'll take a look at implementing this algorithm in Python. When developing optimized code, it is important to start with something easy to make sure you're on the right track. Here we'll start with a straightforward direct version of the non-uniform Fourier transform. We'll allow non-uniform inputs $x_j$, but compute the output on a grid of $M$ evenly-spaced frequencies in the range $-M/2 \le f/\delta f < M/2$. This is what the NUFFT group calls the Type-1 NUFFT. First we'll implement nufftfreqs(), which returns the frequency grid for a given $M$, and nudft() which computes the non-uniform discrete Fourier transform using a slow direct method. The arguments for the latter include iflag, which is a positive or negative number indicating the desired sign of the exponent: from __future__ import print_function, division import numpy as np def nufftfreqs(M, df=1): """Compute the frequency range used in nufft for M frequency bins""" return df * np.arange(-(M // 2), M - (M // 2)) def nudft(x, y, M, df=1.0, iflag=1): """Non-Uniform Direct Fourier Transform""" sign = -1 if iflag < 0 else 1 return (1 / len(x)) * np.dot(y, np.exp(sign * 1j * nufftfreqs(M, df) * x[:, np.newaxis])) Again, I can't emphasize this enough: when writing fast code, start with a slow-and-simple version of the code which you know gives the correct result, and then optimize from there. We can double-check that this is producing the desired result by comparing to the Fortran NUFFT implementation, using Python wrappers written by Dan Foreman-Mackey, available at: # Install nufft from from nufft import nufft1 as nufft_fortran x = 100 * np.random.random(1000) y = np.sin(x) Y1 = nudft(x, y, 1000) Y2 = nufft_fortran(x, y, 1000) np.allclose(Y1, Y2) True The results match! A quick check shows that, as we might expect, the Fortran algorithm is orders of magnitude faster: %timeit nudft(x, y, 1000) %timeit nufft_fortran(x, y, 1000) 10 loops, best of 3: 47.9 ms per loop 1000 loops, best of 3: 265 µs per loop On top of this, for $N$ points and $N$ frequencies, the Fortran NUFFT will scale as $O[N\log N]$, while our simple implementation will scale as $O[N^2]$, making the difference even greater as $N$ increases! Let's see if we can do better. Here we'll attempt a pure-Python version of the fast, FFT-based NUFFT. We'll follow the basics of the algorithm presented on the NUFFT page, using NumPy broadcasting tricks to push loops into the compiled layer of NumPy. For later convenience, we'll start by defining a utility to compute the grid parameters as detailed in the NUFFT paper. def _compute_grid_params(M, eps): # Choose Msp & tau from eps following Dutt & Rokhlin (1993) if eps <= 1E-33 or eps >= 1E-1: raise ValueError("eps = {0:.0e}; must satisfy " "1e-33 < eps < 1e-1.".format(eps)) ratio = 2 if eps > 1E-11 else 3 Msp = int(-np.log(eps) / (np.pi * (ratio - 1) / (ratio - 0.5)) + 0.5) Mr = max(ratio * M, 2 * Msp) lambda_ = Msp / (ratio * (ratio - 0.5)) tau = np.pi * lambda_ / M ** 2 return Msp, Mr, tau def nufft_python(x, c, M, df=1.0, eps=1E-15, iflag=1): """Fast Non-Uniform Fourier Transform with Python""" Msp, Mr, tau = _compute_grid_params(M, eps) N = len(x) # Construct the convolved grid ftau = np.zeros(Mr, dtype=c.dtype) Mr = ftau.shape[0] hx = 2 * np.pi / Mr mm = np.arange(-Msp, Msp) for i in range(N): xi = (x[i] * df) % (2 * np.pi) m = 1 + int(xi // hx) spread = np.exp(-0.25 * (xi - hx * (m + mm)) ** 2 / tau) ftau[(m + mm) % Mr] += c[i] * compare this to the previous results. For convenience, we'll define a single routine which validates the results and times the execution: from time import time def test_nufft(nufft_func, M=1000, Mtime=100000): # Test vs the direct method print(30 * '-') name = {'nufft1':'nufft_fortran'}.get(nufft_func.__name__, nufft_func.__name__) print("testing {0}".format(name)) rng = np.random.RandomState(0) x = 100 * rng.rand(M + 1) y = np.sin(x) for df in [1, 2.0]: for iflag in [1, -1]: F1 = nudft(x, y, M, df=df, iflag=iflag) F2 = nufft_func(x, y, M, df=df, iflag=iflag) assert np.allclose(F1, F2) print("- Results match the DFT") # Time the nufft function x = 100 * rng.rand(Mtime) y = np.sin(x) times = [] for i in range(5): t0 = time() F = nufft_func(x, y, Mtime) t1 = time() times.append(t1 - t0) print("- Execution time (M={0}): {1:.2g} sec".format(Mtime, np.median(times))) test_nufft(nufft_python) test_nufft(nufft_fortran) ------------------------------ testing nufft_python - Results match the DFT - Execution time (M=100000): 1.6 sec ------------------------------ testing nufft_fortran - Results match the DFT - Execution time (M=100000): 0.043 sec The good news is that our Python implementation works; the bad news is that it remains several orders of magnitude slower than the Fortran result! Let's make it faster. We know that our Python function is slow, but we'd like to determine where this speed bottleneck lies. One convenient way to do this is with the line_profiler utility, a Python/IPython addon which can be installed using $ pip install line_profiler Once it's installed, we can load the line profiler extension into the IPython notebook using the %load_ext magic function: %load_ext line_profiler With the line profiler loaded, the %lprun magic function is now available, which we can use to profile our function line-by-line. In order to display these results here, we'll save them to file and then use %cat to view the file. The lines wrap in the notebook, making it difficult to read, so you may wish to view the raw file instead. %lprun -s -f nufft_python -T lp_results.txt nufft_python(x, y, 1000) %cat lp_results.txt ***, eps) 17 1 3 3.0 0.0 N = len(x) 18 19 # Construct the convolved grid 20 1 19 19.0 0.0 ftau = np.zeros(Mr, dtype=c.dtype) 21 1 2 2.0 0.0 Mr = ftau.shape[0] 22 1 3 3.0 0.0 hx = 2 * np.pi / Mr 23 1 11 11.0 0.0 mm = np.arange(-Msp, Msp) 24 1001 1493 1.5 3.7 for i in range(N): 25 1000 2801 2.8 7.0 xi = (x[i] * df) % (2 * np.pi) 26 1000 3024 3.0 7.5 m = 1 + int(xi // hx) 27 1000 21048 21.0 52.5 spread = np.exp(-0.25 * (xi - hx * (m + mm)) ** 2 / tau) 28 1000 11406 11.4 28.4 ftau[(m + mm) % Mr] += c[i] * spread 29 30 # Compute the FFT on the convolved grid 31 1 2 2.0 0.0 if iflag < 0: 32 Ftau = (1 / Mr) * np.fft.fft(ftau) 33 else: 34 1 183 183.0 0.5 Ftau = np.fft.ifft(ftau) 35 1 15 15.0 0.0 Ftau = np.concatenate([Ftau[-(M//2):], Ftau[:M//2 + M % 2]]) 36 37 # Deconvolve the grid using convolution theorem 38 1 14 14.0 0.0 k = nufftfreqs(M) 39 1 32 32.0 0.1 return (1 / N) * np.sqrt(np.pi / tau) * np.exp(tau * k ** 2) * Ftau The output shows us where, line-by-line, the algorithm is spending the most time. We see that nearly 99% of the execution time is being spent in the single for loop at the center of our code. The loop is so expensive that even the FFT computation is just a trivial piece of the cost! This is actually pretty typical: due to dynamic typing, loops are generally very slow in Python. One of the surest strategies for speeding-up your code is to use broadcasting tricks in NumPy to remove these kinds of large loops: you can read one of my course lectures on the subject here. We'll do this next. Let's rewrite the above implementation and use broadcasting tricks to elliminate the loops. Because of the structure of this problem, the approach is a bit complicated here, but it turns out that we can take advantage here of the little-known at() method of NumPy's ufunc (available since NumPy 1.8). Briefly, >>> np.add.at(x, i, y) is similar to >>> x[i] += y but works as desired even if the incides i have duplicate entries. Using this, we can adjust our implementation as follows: def nufft_numpy(x, y, M, df=1.0, iflag=1, eps=1E-15): """Fast Non-Uniform Fourier Transform""" Msp, Mr, tau = _compute_grid_params(M, eps) N = len(x) # Construct the convolved grid ftau: # this replaces the loop used above ftau = np.zeros(Mr, dtype=y.dtype) hx = 2 * np.pi / Mr xmod = (x * df) % (2 * np.pi) m = 1 + (xmod // hx).astype(int) mm = np.arange(-Msp, Msp) mpmm = m + mm[:, np.newaxis] spread = y * np.exp(-0.25 * (xmod - hx * mpmm) ** 2 / tau) np.add.at(ftau, mpmm % Mr, it: test_nufft(nufft_numpy) test_nufft(nufft_python) test_nufft(nufft_fortran) ------------------------------ testing nufft_numpy - Results match the DFT - Execution time (M=100000): 0.45 sec ------------------------------ testing nufft_python - Results match the DFT - Execution time (M=100000): 1.6 sec ------------------------------ testing nufft_fortran - Results match the DFT - Execution time (M=100000): 0.044 sec It worked! We gained around a factor of 4 speedup in replacing the Python loop with the np.add.at() call. Still, though, we're sitting at about a factor of 10 slower than the Fortran version. The problem is that the np.add.at() call here requires construction of some very large and costly temporary arrays. If we want a faster execution time, we need to further optimize that main loop, and we can't do this with NumPy alone. When NumPy broadcasting tricks aren't enough, there are a few options: you can write Fortran or C code directly, you can use Cython, Weave, or other tools as a bridge to include compiled snippets in your script, or you can use a tool like Numba to speed-up your loops without ever leaving Python. Numba is a slick tool which runs Python functions through an LLVM just-in-time (JIT) compiler, leading to orders-of-magnitude faster code for certain operations. In this case, we need to optimize what amounts to a nested for-loop, so Numba fits the bill perfectly. For clarity, we'll pull-out the grid construction code that we want to optimize, and write it as follows: import numba # nopython=True means an error will be raised # if fast compilation is not possible. @numba.jit(nopython=True) def build_grid(x, c, tau, Msp, ftau): Mr = ftau.shape[0] hx = 2 * np.pi / Mr for i in range(x.shape[0]): xi = x[i] % (2 * np.pi) m = 1 + int(xi // hx) for mm in range(-Msp, Msp): ftau[(m + mm) % Mr] += c[i] * np.exp(-0.25 * (xi - hx * (m + mm)) ** 2 / tau) return ftau def nufft_numba(x, c, M, df=1.0, eps=1E-15, iflag=1): """Fast Non-Uniform Fourier Transform with Numba""" Msp, Mr, tau = _compute_grid_params(M, eps) N = len(x) # Construct the convolved grid ftau = build_grid(x * df, c, tau, Msp, np.zeros(Mr, dtype=c this now: test_nufft(nufft_numba) test_nufft(nufft_fortran) ------------------------------ testing nufft_numba - Results match the DFT - Execution time (M=100000): 0.1 sec ------------------------------ testing nufft_fortran - Results match the DFT - Execution time (M=100000): 0.046 sec Much better! We're now within about a factor of 3 of the Fortran speed, and we're still writing pure Python! Having plucked all the low-hanging fruit, any further optimization will now be very low-level: that is, thinking about things like reduction of the number of exp() evaluations through application of mathematical identities. This type of careful logic is one reason the Fortran implementation is so fast, and many of these low-level strategies are discussed in the NUFFT paper linked above. To gain some more speed, we can follow their advice and optimize the expressions at this level by precomputing expensive expressions and recombining these expressions later: This obfuscates the logic of the algorithm a bit, but it does lead to some faster execution. Here is an example of this: import numba @numba.jit(nopython=True) def build_grid_fast(x, c, tau, Msp, ftau, E3): Mr = ftau.shape[0] hx = 2 * np.pi / Mr # precompute some exponents for j in range(Msp + 1): E3[j] = np.exp(-(np.pi * j / Mr) ** 2 / tau) # spread values onto ftau for i in range(x.shape[0]): xi = x[i] % (2 * np.pi) m = 1 + int(xi // hx) xi = (xi - hx * m) E1 = np.exp(-0.25 * xi ** 2 / tau) E2 = np.exp((xi * np.pi) / (Mr * tau)) E2mm = 1 for mm in range(Msp): ftau[(m + mm) % Mr] += c[i] * E1 * E2mm * E3[mm] E2mm *= E2 ftau[(m - mm - 1) % Mr] += c[i] * E1 / E2mm * E3[mm + 1] return ftau def nufft_numba_fast(x, c, M, df=1.0, eps=1E-15, iflag=1): """Fast Non-Uniform Fourier Transform with Numba""" Msp, Mr, tau = _compute_grid_params(M, eps) N = len(x) # Construct the convolved grid ftau = build_grid_fast(x * df, c, tau, Msp, np.zeros(Mr, dtype=c.dtype), np.zeros(Msp + 1, dtype=x the result: test_nufft(nufft_numba_fast) test_nufft(nufft_fortran) ------------------------------ testing nufft_numba_fast - Results match the DFT - Execution time (M=100000): 0.06 sec ------------------------------ testing nufft_fortran - Results match the DFT - Execution time (M=100000): 0.047 sec This is looking good! With a bit of effort we are now within about 25% of the Fortran speed, and we retain all the advantages of having pure Python code! %matplotlib inline import matplotlib.pyplot as plt # use seaborn for nice default plot settings import seaborn; seaborn.set() Mrange = (2 ** np.arange(3, 18)).astype(int) t_python = [] t_numpy = [] t_numba = [] t_numba_fast = [] t_fortran = [] for M in Mrange: x = 100 * np.random.random(M) c = np.sin(x) t1 = %timeit -oq nufft_python(x, c, M) t2 = %timeit -oq nufft_numpy(x, c, M) t3 = %timeit -oq nufft_numba(x, c, M) t4 = %timeit -oq nufft_numba_fast(x, c, M) t5 = %timeit -oq nufft_fortran(x, c, M) t_python.append(t1.best) t_numpy.append(t2.best) t_numba.append(t3.best) t_numba_fast.append(t4.best) t_fortran.append(t5.best) plt.loglog(Mrange, t_python, label='python') plt.loglog(Mrange, t_numpy, label='numpy') plt.loglog(Mrange, t_numba, label='numba #1') plt.loglog(Mrange, t_numba_fast, label='numba #2') plt.loglog(Mrange, t_fortran, label='fortran') plt.legend(loc='upper left') plt.xlabel('Number of Elements') plt.ylabel('Execution Time (s)'); As we see, all the algorithms scale as $\sim O[N\log N]$ in the large $N$ limit, albeit with very different constants of proportionality. Our final optimized Numba implementation nearly matches the Fortran version as $N$ grows large, and because it is written in pure Python, it retains all the advantages of pure Python code listed above. For that benefit, I think the cost of a ~25% slow-down is well worth it! I hope you've enjoyed this exploration of how to write fast numerical code in pure Python. As you think about writing efficient implementations of useful algorithms, I invite you to consider the points I listed above: in particular, how difficult will it be for your users to install, read, modify, and contribute to your code? In the long run, this may be much more important than shaving a few milliseconds off the execution time. Writing a fast implementation of a useful algorithm is an excellent and useful pursuit, but we should be careful to not forget the costs that come along with such optimization. If you're interested in using the pure-Python NUFFT implementation, I've adapted much of the above code in a repository at. It contains a packaged and unit-tested version of some of the above code, as well as a (hopefully) growing compendium of related routines.
https://nbviewer.ipython.org/url/jakevdp.github.io/downloads/notebooks/NUFFT.ipynb
CC-MAIN-2021-43
refinedweb
3,382
65.12
25 March 2013 By clicking Submit, you accept the Adobe Terms of Use. Prior experience with CSS is required to make the most of this article. Intermediate In Douglas Crockford's "JavaScript: The Good Parts", Crockford names global variables as the worst part of JavaScript. He writes, "Global variables can be a convenience in very small programs, but they quickly become unwieldy as programs get larger. Because a global variable can be changed by any part of the program at any time, they can significantly complicate the behavior of the program. Use of global variables degrades the reliability of the programs that use them." Crockford continues, "Global variables make it harder to run independent subprograms in the same program. If the subprograms happen to have global variables that share the same names, then they will interfere with each other and likely fail, usually in difficult to diagnose ways." Whether or not you agree with Crockford about globals, JavaScript, at the very least, has well documented and widely accepted ways to deal with them. Module patterns, object namespacing, and function closures are a few examples. CSS, on the other hand, is not so lucky.. This can be extremely difficult when multiple people are working on the same project; eventually two people will inadvertently pick the same class name or style the same tag in conflicting ways. Even a single developer can easily forget rules written just a few months prior. Not only are CSS rules global, they also inherit from parent elements down to their children. This inheritance cannot be stopped or turned off. Once an element is added to the DOM, it will inherit values from every one of its ancestors. Your only defense is to explicitly unset the properties you don't want and hope you haven't missed any. For framework and library authors the situation is even worse. You have absolutely no idea what kind of crazy rules the users of your library might have written, and there's no foolproof way to account for it. If a third-party site that uses your framework contains a rule like #content div { width: 25%!important; }, things are probably going to break. So what can you do? In this article I'll talk about some strategies for dealing with the global nature of CSS. I talk about finding the balance between paranoid over-protection and just asking for trouble. I'll also talk about some exciting things already making their way into the CSS spec that will provide real encapsulation in the future. When writing CSS you're usually either defining styles for your own project or writing a library for use by other people. The strategies for these two situations are actually quite different. In the following section I'll address strategies for you own projects, and in the next section I'll discuss writing CSS libraries and frameworks. With your own projects your primary concern should be future maintainability. You want your code to be scalable and react well to change. This is true even for small sites or applications on which you're the sole developer. You never know how a project will evolve, so you should code in a way that can withstand such unpredictability. Every time you define a rule on an unqualified HTML tag (a type selector) you pollute the entire tree from that element down through all of its children. Consider the following rule: #sidebar a { background: lightyellow; color: blue, text-decoration: underline; } Rules like this may seem simple and harmless, but if you add a third-party calendar widget to your sidebar, the above rule will apply to the calendar’s links as well, and that is probably not what you want. Even if the author of the calendar widget explicitly set values for color, background, and text-decoration, your rule has a high specificity and will probably win out. This situation could have been completely avoided had you used a class selector instead of a type selector. Sure it’s more work to put a class on each link in the sidebar, but with the extra work comes added peace of mind knowing that your styles are more predictable and stable when changes are made in the future. There are a limited number of element types in HTML but there are an unlimited number of class names. The chances of someone else picking your exact class name are fairly small, but the chances of them using some of the same element types are practically guaranteed. It’s common for developers to scope their subobject classes within a parent selector, secure in the knowledge that the scoped styles won’t leak out. For example: .widget { } .widget .title { } And they're correct. The styles defined on .widget .title will only apply when .title is used within .widget. That, however, is only half of the concern. If the class selector .title is defined elsewhere in the stylesheet, those styles will apply to all elements with the class title including elements within .widget. Encapsulation is a two part process. You have to worry about styles leaking out, but you also have to worry about outside styles leaking in. Unwanted style leakage is especially problematic with names like "title". Developers frequently pick generic names like this, and the likelihood of two people unknowingly choosing the same one is fairly high. This problem can be solved by namespacing your classes. Instead of relying on descendent combinators, simply class the subelements and use the component's base name as a prefix: .widget { } .widget-title { } Namespacing has many advantages in addition to providing better encapsulation. It lowers the specificity of each rule, it expresses more meaning in the markup, and it provides a common hook should you need to test your implementation or globally change the selector name in the future. Unfortunately, many CSS frameworks today are hostile toward their host environment. They litter the global scope with rules defined on tags and extremely common class names, practically guaranteeing conflicts with your existing codebase. They also make the usually incorrect assumption that users of their framework have the luxury of completely redoing their site's CSS, and then using that framework (and only that framework) until the next redesign. But this simply does not reflect the situation most developers are in. Most of the time you already have a site, and it's a struggle to incorporate a new framework into it. Developers also frequently want just bits and pieces of multiple frameworks, but few frameworks are designed to "play nice" with others. In an ideal world, framework code would be completely modular and encapsulated. You could easily pick and choose the parts of the framework you wanted without fear of it conflicting with your existing site or another framework. Unfortunately this goal just isn't possible given the current state of CSS, but that doesn't give framework developers permission to do the opposite. Framework authors should strive to make their code as compatible as possible. That work shouldn't fall on the shoulders of the framework user. Fortunately there are a number of ways framework authors can make their libraries more global-friendly. If you're creating a new CSS framework, contributing to an open source project, or writing any CSS that gets used on sites outside of your control, consider the suggestions and practices that follow. Arguably the main cause of CSS framework incompatibility is overreliance on aggressive global resets. The most prominent example of this is in ZURB's Foundation, which sets the box-sizing property of every element to border-box: *, *:before, *:after { box-sizing: border-box; } The box-sizing property enables you to alter the default box-model used by the browser. The traditional box model calculates the width and height of an element by the size of its content-box. In contrast, the border-box model includes the size of the padding and borders in those measurements. That means you can add a style of width: 50%; to a column <div> and safely add borders and padding without worrying about the column becoming wider than you want. Many developers prefer the border-box model over the traditional box model and consider it a more intuitive approach. I personally use it in all my new projects. However, for a popular framework to require it globally on every element will practically guarantee its incompatibility with the vast majority of existing websites. Most sites still use the content-box model and have widths and heights defined in tens or hundreds of places throughout. Forcing a rule like this on an existing codebase is unreasonable. Fortunately, there's an easy compromise. With a CSS preprocessor you can have it both ways. You can default to a global box model reset while simultaneously providing a fallback for sites that can't make the switch. This enables you to promote some exciting new patterns without alienating millions of websites. Here's an example written in Sass. /* The placeholder rule */ %border-box-model { @include box-sizing(border-box); } /* The reset conditional */ if $global-border-box-model == true { *, *:before, *:after { box-sizing: border-box; } } /* Individual component conditionals */ .tooltip { if $global-border-box-model == false { %extend %border-box-model; } } The above technique enables sites to opt into a global border-box model reset, or gracefully fall back to defining it on individual components. Because this all happens in a preprocessor, it doesn't add any bloat to the compiled CSS. In general, CSS preprocessors are great tools for letting end users customize a framework. Preprocessor variables are commonly used for customizing sizes and colors, but they can be great for customizing your site architecture as well. Another example of an overdependence on global resets is the unsetting of user-agent styles. Many frameworks will unset list, link, or heading styles and then define components assuming those resets will still be in place, but this assumption is often false. For example, if your framework includes a tabbed navigation component that uses a <ul> element, it's probably a good idea to reset the list-style, padding , and margin properties, even if you've already reset them in a base stylesheet. Not resetting those properties assumes that your framework's users are always including the base styles, and not overriding any of them. Don't assume that. The same is also true of link styles. If the tab elements in the previous example are coded with <a> tags, it's probably wise to explicitly set the color and text-decoration properties on both the normal and :hover states. The line between paranoid overprotection and naive assumptions isn't easy to find, but it is important to be sensible. Aggressive attempts to reset every single property will lead to unnecessary code bloat, but relying too heavily on your base resets may lead to unexpected bugs. I leave it up to you to find your own balance. Twitter Bootstrap, Zurb Foundation, and similar libraries define style rules on common class names, including .tabs, .alert, and .row. If you're working on an existing application, the chances are very high that you've already picked at least one of these names. But since the framework isn't going to change, you have to. This is a terrible inconvenience put on framework users. jQuery UI takes a much better approach. It namespaces all class names with the prefix ui-, significantly reducing the possibility of conflict. The namespaced approach may be more verbose, but it's much more considerate of library users' time. Namespacing is a great start, but it is not guaranteed to prevent all naming conflicts, especially with shorter, less unique namespaces like ui-. However, if the library uses a preprocessor, it can take the namespacing technique one step further. When all the styles of a particular component are prefixed with the component's name (like I recommended earlier), it's trivial to set that name with a variable. Imagine a CSS framework named "Flux" that defines a messagebox component. Here's how the selectors could be named dynamically: $flux-messagebox-name: "messagebox" !default; .#{$flux-messagebox-name} { } .#{$flux-messagebox-name}-heading { } .#{$flux-messagebox-name}-body { } Users of the Flux framework can now set their own namespace by simply overriding the variable: $flux-messagebox-name: "some-other-name"; The beauty of this technique is that it empowers users to choose the names they want. If they like clean and simple names like those used in Bootstrap and Foundation, they can have them. If they prefer a consistent prefix like jQuery UI uses, they can have that. And if they need to completely change the name of a component to resolve conflicts, they can do that too. It’s entirely up to the users. Dynamic namespacing supports short and simple names for the majority of use cases and only requires extra effort for those who actually need it. It doesn't impose a verbose prefix on anyone and keeps the barrier to entry low. Those who want to make changes can dive in and edit the Sass file, and those who just want to use it out of the box can simply grab the compiled CSS. Everybody wins. For more detail on this technique, see Dynamic Selectors, an article that I recently wrote and posted on my personal website. Dealing with globals in CSS is a pain; luckily there are several exciting developments in the works to make real CSS encapsulation possible. Currently, the only way to achieve real encapsulation is to use an <iframe>, but for most scenarios iframe elements create more problems than they solve. Three new HTML and CSS features that will make dealing with globals easier are scoped styles, the all property, and Web Components. Scoped styles HTML5 introduced the scoped attribute of the <style> tag, which allows the tag to be used within the body of an HTML document (previously <style> declarations could only be in <head>). Scoped style declarations apply their contained CSS rules only to the document tree in which they're defined. In other words, if a <style> tag is inserted directly within <div id="sidebar">, then its styles will only apply to child elements of that sidebar. Scoped styles offer a good way to ensure that a set of rules do not leak out and conflict with the rest of the document. However, as with descendent combinators, they do not prevent outside styles from leaking in. Scope styles will be particularly useful when injecting code into an existing document. They'll enable you to transmit some CSS along with your markup in a way that is valid (remember non-scoped style declarations are only allowed in <head>) and in a way that won't conflict with the existing page. The downside of scoped styles is that browsers that don't support them treat them like regular style declarations. That means that not only will you not have two-way encapsulation, you won't even have one-way encapsulation. Because of this, my recommendation is to stay away from scoped style declarations until they're fully supported in all browsers. If you do use them, treat them as regular style declarations and anticipate rules leaking out. For more information on scoped styles, see The Scoped Attribute on HTML5 Doctor. CSS recently introduced the all property, which can be thought of as a shorthand way to set or reset everything. The all property accepts CSS-wide keywords such as initial and inherit, making it easy to reset all previously defined styles for a given component without having to list each of them individually. Here's an example: .widget { all: initial; background-color: gray; border: 1px solid black; font-family: sans-serif; text-align: center; } Setting the all property helps prevent unwanted styles from being inherited. For example, imagine you created a widget that someone included on their page; unfortunately, that page contained all sorts of weird base styles like letter-spacing: 1em; and text-indent: -2em;. It would be impossible for you to anticipate this, and absurd for you to explicitly reset these properties (since they're so rarely used), but in this particular situation not resetting them breaks your widget. With the all property you don't have to worry. You can easily reset everything and start fresh. It's important to be aware that all is just like any other CSS property and its applicability depends on the cascade just like all other properties. Consider the following: #sidebar p { text-decoration: line-through; } .widget { all: initial; } If you use the above widget in your sidebar, its all declaration won't override the previous rule's text-decoration value because #sidebar p has a higher specificity than .widget. If you're tempted to try declaring all: initial!important; to ensure your reset works, please reconsider. Doing so is extremely destructive. Keep in mind that the all property is just shorthand for listing every single CSS property individually. To illustrate the danger, the following example shows the CSS equivalent of declaring .widget { all: initial!important; }: .widget { background-attachment: scroll!important; background-color: transparent!important; background-image: none!important; background-position: 0% 0%!important; background-repeat: repeat!important; border-collapse: separate!important; border-spacing: 0!important; border-style: none!important; border-width: medium!important; bottom: auto!important; caption-size: top!important; clear: none!important; clip: auto!important; /* and the list goes on... */ } As you can see, the !important flag gets applied to each CSS property, which is almost certainly not what you want. Keep in mind that !important carries an even higher specificity than inline styles, making it nearly impossible to override. In fact, all: inherit!important; will even override subsequent declarations within the same rule unless they also use !important. CSS importance is a powerful tool that should only be used when absolutely necessary, and applying it to every single property is almost never necessary. The all property is a great addition to CSS, and it can vastly reduce redundancy with style resets. However, since it is still subject to normal CSS cascading, it can't achieve true style encapsulation. You can think of Web Components as similar to native browser controls like <input type="date"> or the <audio> element. Both of these are just single elements in the HTML markup, but there's obviously more than that going on behind the scenes. For example, <input type="date"> elements display a calendar that is visually styled and responds to click events, and <audio> elements have controls for playback. How is this possible with just one HTML element? Actually, within those single HTML elements lives a hidden DOM (known as a shadow DOM) that is self-contained and packages its own logic and styling. Web Components have a shadow DOM as well, and you can customize it. The shadow DOM enables you to include HTML, CSS, and JavaScript on a page in a way that can be completely encapsulated from the master document. According to the W3C specification, "The component model for the Web (also known as Web Components) ... let[s] web application authors define widgets with a level of visual richness not possible with CSS alone, and ease of composition and reuse not possible with script libraries today." To include a Web Component on your page, you simply reference a file where the component is defined: <link rel="components" href="alert-component.html"> The contents of that component document will include a custom-named element and all the logic, styling, and markup that goes along with it; for example: <html> <head> <style> .alert { background: yellow; border: 1px solid red; color: red; } h1 { font-size: 1.25em; margin: 0; } </style> </head> <body> <element name="alert"> <template> <div class="alert"> <h1>Watch Out!</h1> <content></content> </div> </template> </element> </body> </html> The last step is to instantiate your new custom element in an existing element within the master document. You do this with the is attribute. <div is=”alert”>This is the contents of the alert</div> When you declare that the above <div> is an instance of your custom alert element, the browser automatically renders the markup of the custom alert element's <template> as the shadow DOM of the master document's <div>. You might be wondering what happens to the text inside the <div> once the browser inserts the shadow DOM inside of it. This is where the <content> tag in the component document comes into play. The <content> tag is just a placeholder for whatever content the element in the master document provides to it. In this case, the text "This is the contents of the alert" would get rendered in the new component inside the content tag. Component documents can define more than one <content> tag and use the selected attribute to determine which of the master document's elements get rendered where, but that is beyond the scope of this article. This introduction is just the tip of the iceberg of what is possible with Web Components. The main point to take away is that with Web Components you can completely separate the presentation and logic of a component from its content. You might have noticed I broke two of my own rules when declaring the CSS of the alert component above. First, I used a generic class name ( .alert), and second, I defined styles for an HTML tag ( h1). However, with Web Components, this doesn't matter. I don't have to worry about whether someone already defined a conflicting .alert or h1 rule because the styles of the component exist in a completely separate scope from those of the master document. The styles of the master document do not touch the component document, and the styles of the component document do not touch the master document—real encapsulation at last. The Web Component specification is still evolving and many of the details will likely change. Here are a few excellent resources if you want to learn more and be on the cutting edge: Currently the state of globals in CSS is not great. The temptation for Web developers to write their CSS selectors as minimalistically as possible is very high, but it comes at a much higher cost as your sites increase in size and complexity. With a little discipline and the future in mind, writing CSS to avoid conflicts isn’t so hard. In fact, writing CSS in this way usually leads to a more manageable architecture. As CSS grows and matures as a language, many of these concerns will no longer apply, but they probably won’t disappear entirely. A firm understanding of how and why conflicts arise is essential to knowing when to code defensively and when it doesn’t matter. When in doubt, code defensively. This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.
http://www.adobe.com/devnet/html5/articles/css-everything-is-global-and-how-to-deal-with-it.html
CC-MAIN-2014-41
refinedweb
3,832
54.22
Hi guys, am pretty new to java, i have few websites with alot of tutorials and help, besides that i have a friend also who started programming java this year, long story short, am getting a lot of help. But i learned some of the very very basics and played with Karel etc. So i decided to build my own calculator from scratch just to see what am i actually capable to do with what i have learned without looking at anyone else's code, because if i was looking at other codes, i would basicaly copy it and not let my brain to think by its self, you get the point. Every so and then if am looking for a method or some specific command i would be googling and that way i would learn something else, but i found my self stuck right now. So this calculator is very simple: 1. It asks me for my first number (then you enter it) 2. Then it asks you for your second number (then you enter it) 3. Then it asks you for your desired operation (then you choose the operation) 4. And finally you get the result. Here's the problem i managed to do everything until the no.3 i have no idea how to make my program to read what i have typed in and then create an actual method that would allow me to choose the operation and then execute it, i have googled around and have found literally nothing, maybe am searching for the wrong things. I don't really want someone to solve this for me, for it my own assignment. What i need is if someone could shed some light towards which direction i should go, or even possible let me know whats the method/command missing and explain it to me, or even if they know some links that would explain what is needed. Heres my code: package project1; import java.util.Scanner; public class Learning { public static void main(String args[]) { double number1, operations, number2, sum; Scanner input = new Scanner(System.in); //values valuesObject = new values(); System.out.println("Enter First Number: "); String typing = input.nextLine(); System.out.println("Enter Second Number: "); String typing2 = input.nextLine(); System.out.println("Choose Operation: "); } } //values valuesObject = new values(); This is another class created separately which i thought would actually help me, but then i realised that i dont really need it, so i just shaded it with comment line (//) So i basically called the object out of that class, it really has nothing to do with the calculator, but just posting it so you can actually understand why its shaded. // i have no idea wtf this does, but ill will figure out soon package project1; public class values { public String valueValue; public void value(String donkeyBalls) { valueValue = donkeyBalls; } }
http://www.javaprogrammingforums.com/java-theory-questions/36953-building-calculator.html
CC-MAIN-2017-30
refinedweb
474
57
Your own while / else Help! awhitehand #1 It reminded me "Something went wrong......", but I don't know and cannot find where the wrong place was.I wonder if the system is wrong. awhitehand #2 And it reminded that a invalid syntax in line 9 what do you enter when you are prompted for input by raw_input? Can you copy paste your code to the forum so i can run it? awhitehand #4 from random import randint # Generates a number from 1 through 10 inclusive random_number = randint(1, 10) guesses_left = 3 # Start your game! while guesses_left > 0: guess = int(raw_input("Your guess: ")) if guess == random_number: print "You win!" break guesses_left -= 1 else: print "You lose." here: else: whatever you use after else, its not a colon. It looks like one, but it isn't. use a colon awhitehand #6 Thank you so much, I was confused for a long time. I just messed the Chinese input method and the English input method up. It's so ignoring! Thanks a lot!
https://discuss.codecademy.com/t/your-own-while-else-help/77713
CC-MAIN-2018-39
refinedweb
170
85.79
Today I will discuss about how can we develop a simple Asp.Net MVC Application. As a first article about Asp.Net MVC i will today discuss about a very simple Application development. MVC: The Model View Controller (MVC) architectural pattern separates an application into three main components: · Models: Model objects are the parts of the application that implement the domain logic. Often, model objects also retrieve and store model state in a database. ·. · Controllers: Controllers are the components that handle user interaction, manipulate the model, and ultimately select a view to render the UI. In an MVC application, the view only displays information; the controller handles and responds to user input and interaction. ASP.NET MVC: The ASP.NET MVC framework is a lightweight, highly testable presentation framework that is integrated with existing ASP.NET features, such as master pages and membership-based authentication. You must have the following items to develop asp.net mvc application o Microsoft Visual Studio 2008 SP1 o Microsoft ASP.NET MVC 1.0 (visit for downloading ) o Microsoft SQL 2005 or Microsoft SQL 2008 (Express edition or above) o Test database (Create a database named ‘Test’ and then run ‘test.sql’) Before building/running this application please create a database named "Test" and run the "tables.sql" script. 1. File -> New -> Project -> Asp.Net MVC Web Application 2 Allow with not select to create Unit test Project 3. Solution Explorere will be like that Now I would like you to give a little description of the different folders use in Solution: Content: Content hold the necessary Style sheet file Controller: Contains the Controller class. This is the entry point of any operation. For any user action, controller listen the action and process that action through ‘Model’ and finally return a ‘View’ associated with this action. Script: Contains the related javascript used by the application Views: Views are returned by Controller. So for every controller like ‘HomeController’ there will be created a ‘Home’ in views and ‘AccoutController’ there will be created a ‘Account’ as well. There is also a folder in “Views” that is “Shared”. This “Shared” contains the necessary Master Pages and user controll. That’s all the little description about the folder structure used by Asp.net Mvc. 4. Right click the Model folder and add a new “Ado.net Entity DataModel” 5. Create Test.edmx with two tables Customer And Orders (Scripts is attached with source code) Right click the “Controller” and Add a “Controller” named “CustomerController”. Check the “Add Right click the “Controller” and Add a “Controller” named “CustomerController”. Check the “Add action methods for Create, Update, and Details scenarios” Now Modify CustomerController.cs like that: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Ajax; using MvcApplication1.Models; namespace MvcApplication1.Controllers { public class CustomerController : Controller { // // GET: /Customer/ TestEntities entities = new TestEntities(); public ActionResult Index() { return View(entities.Customer); } // // GET: /Customer/Details/5 public ActionResult Info(string id) { var information = entities.Customer.Where(a => a.CustomerID == id).First(); return View(information); } As today is our first Article so We will work only Selecting a list of customers with details. There have to need a study about the internal functionalities and architecture. So if you want ot know details please visit. Here i have used the TestEntities class. The different methods work actually how you want to interact with Model and finally you will get a View() like ActionResult Index() will return a Customer entity which will be the index page of Customer View. public ActionResult Info() will return a perticular Customer Info using a ID Now 7. Right click inside the "public ActionResult Index()" method and Add View selecting the check box "create a strongly-typed view", and select "Data Class" as "Customer" and "View Contenet" as "List" 8. You will see a page "Index.aspx" has been added to "Views\Customer\" 9. Right click also inside the "public ActionResult Info(string id)" method and add View selecting the check box "create a strongly-typed view", and select "Data Class" as "Customer" and "View Contenet" as "Details" Thats all. You will get all the customer in Index.aspx page with Details Information. You need just a little adjustment in Index.aspx and Info.aspx page as "Create New" will not work as we did not use the " public ActionResult Create()" method. So modify the Page as i did in source code. When will run the application, you will get all the customer information and when you will click the Details link, you will find details information about that customer..
http://www.codeproject.com/Articles/61770/How-to-ASP-NET-MVC-Article
CC-MAIN-2015-40
refinedweb
770
50.12
I've been using the WebCamTexture class to implement device camera views on mobile devices (both iPhones and Androids). However, I've noticed that the aspect ratio of the camera on a device does not necessarily match the aspect ratio of the screen (esp. on the wide-screen Androids). I can force the aspect to be 4:3 (which suits MOST cases), but what if the device's camera uses something different? I can't find any information in WebCamTexture or WebCamDevice to help get the appropriate aspect ratio. Can anyone help? Answer by Fattie · Apr 16, 2014 at 10:54 AM Hope it helps someone! Thanks, Fattie! Most helpful. It's too bad this seems to be a very low-priority for Unity. It's really useful for augmented reality applications, but Unity Tech seems to favour AAA game features. Answer by Jason-RT-Bond · Feb 08, 2013 at 11:41 PM This is quite belated, but I was prepping a test project to submit with a bug report, and discovered a solution. Following what rutter suggested, you can indeed request a high resolution and framerate, and will generally get the best available (e.g ask for 1080p at 60fps and you'll get 720p at 30fps). This is NOT ideal by any means, but it gets you something. The problem then is with the "16x16" size Unity seems to report for the camera texture, as mentioned by BTamas. This is what Unity gives back on an iPad even with the latest version (4.0.1) after requesting Play on the camera texture. With these (incorrect) numbers it seems impossible to set the dimensions correctly. HOWEVER, the cause of this seems to be that starting the camera is asynchronous. By constantly checking them after starting the camera, I found that I would soon get correct values across all my devices (iPads 2, 3 and 4, iPhone 5 and Samsung Galaxy wifi 5.0 all worked). There doesn't seem to be any way of knowing when these values will be correct, though, so you must monitor them in a script, rather than simply setting the size of your plane/surface/shader at one particular moment. The solution in brief: Set the desired resolution to be very high, as rutter suggested. After asking the camera to start, monitor the size of the texture for a while (keep checking the width and height in the Update method of a script). It should be set to the correct size eventually. (Possibly several frames?) Note: This solution will only allow you to get the highest available resolution. It would still be better to be able to read a set of supported resolutions ahead of time so you can choose a more appropriate one. Hey, Thanks for explaining it, but I'm still a little lost. I've followed all the suggestions but i am still having issues. We have a RawImage 480x480 - here is the code I'm using as suggested by the above answer: using UnityEngine; using System.Collections; using UnityEngine.UI; public class ShowCameraScript : MonoBehaviour { public RawImage rawimage; private WebCamTexture webcamTexture; void Start () { WebCamDevice[] devices = WebCamTexture.devices; webcamTexture = new WebCamTexture(devices[0].name,480,480,30); rawimage.texture = webcamTexture; rawimage.material.mainTexture = webcamTexture; webcamTexture.Play(); } void Update() { if ( webcamTexture.width < 100 ) { Debug.Log("Still waiting another frame for correct info..."); Debug.Log("width is: " + webcamTexture.width.ToString()); return; } // change as user rotates iPhone or Android: int cwNeeded = webcamTexture ( webcamTexture.videoVerticallyMirrored ) ccwNeeded += 180; // you'll be using a UI RawImage, so simply spin the RectTransform rawimage.rectTransform.localEulerAngles = new Vector3(0f,0f,ccwNeeded); float videoRatio = (float)webcamTexture.width/(float)webcamTexture.height; AspectRatioFitter rawImageARF = rawimage.GetComponent<AspectRatioFitter>(); rawImageARF.aspectRatio = videoRatio; if ( webcamTexture.videoVerticallyMirrored ) rawimage.uvRect = new Rect(1,0,-1,1); // means flip on vertical axis else rawimage.uvRect = new Rect(0,0,1,1); // means no flip Debug.Log ("videoRatio: "+ videoRatio.ToString()); } } Now our aspect ratio should be 1:1 because we are using a 480x480 RawImage but the aspect is ratio is incorrect and is stretched or squashed depending how i hold the device. I've included two images so that you can see what i mean: is it not possible to make a 1:1 ratio? I've even tried forcing it, but no result. please if anyone can explain or shed some light on the matter it would be appreciated. We really want to use the 480X480 resolution for our image. so if anyone has a solution for me, that would be awesome. On the other side, if this is a problem, should i submit a bug report? Thank you in advance for reading this. I guess the problem is you are getting (for example) 640x480 images from the camera when you're holding the device in horizontal position, and 480x640 in vertical position. You then squeeze these images to fit into 480x480, so once you get horizontal squeezed images (640 to 480 width) and once vertical squeezed images (640 to 480 height). Yes, that's most likely the problem. You can't really force a camera chip to a certain aspect ratio since the native aspect ratio is always there. The image would need to be "cropped" in some way so some information of the image would be lost. It certainly doesn't automatically crop the image since there are multiple ways how you could crop an image to a certain resolution. So you would need to: either crop the image manually by copying only the part you want into your square texture or change UV coordinates of the quad so it only shows the wanted portion In the following calculations we assume that width is the larger edge and height is the smaller one. If the image is rotated you have to take that into account. You probably want to crop evenly left and right. So the amount you have to crop on the larger side is: float amount = (width - height) * 0.5f; So "amount" pixels need to be removed from both sides of the larger side. To calculate the UV coordinates it's quite similar float u = (1f - height / width) * 0.5f; While the "v" coordinates stay at max (one is "0" the other is "1") the u coordinate (along the larger edge of your image) need to be "u" and "1f - u" Answer by MorphVGX · Jan 07, 2017 at 01:05 AM What I found is that the ratio will be correct after the device is set and you call Play() on the WebcamTexture. it possible to render Unity graphics elements on top of iPhone / Android video feed? 2 Answers Halo effect perfomance on mobile devices 1 Answer GUI refresh time on platforms slower than Unity Editor 1 Answer QR-Code Decoding for iOS and Android 0 Answers how to convert Input.mousePosition into iphone/android accelerometer? 1 Answer
https://answers.unity.com/questions/232168/how-can-i-get-the-device-camera-aspect-ratio.html
CC-MAIN-2020-29
refinedweb
1,144
56.35
Every programmer in every language, sometime early in their learning, has written a program called "Hello world!" that prints exactly that. The idea behind it is it's an excellent introduction to the language and programming environment. In CircuitPython, our Hello World! is also known as Blink. Every CircuitPython compatible board has a little red LED on it, and you can use a simple program to make it blink. After all, making things blink is great! Here is what the basic Blink looks like on the Circuit Playground Express. Try loading it on your board to see what happens! import time from adafruit_circuitplayground.express import cpx while True: cpx.red_led = not cpx.red_led time.sleep(0.5) import time from adafruit_circuitplayground.express import cpx while True: cpx.red_led = not cpx.red_led time.sleep(0.5) The little red LED is True when it's on, and False when it's off. This code cycles back and forth between the LED being on for 0.5 seconds and off for 0.5 seconds. For this project, we will be using the built in NeoPixels. So, for this example, we've written a version of Blink that uses the first NeoPixel instead. However, setting a NeoPixel to a color is not a True or False situation. We're setting it to a color which is done using a tuple in (Red, Green, Blue) format. Cycling back and forth here involves cycling between red which is (255, 0, 0) and off which is (0, 0, 0). So, to do this, we're going to need to do a little math. The absolute value of a number can be thought of as that number's distance from zero. For example, the absolute value of 255 is 255. The absolute value of -255 is also 255, because even though it's a negative number, it is still 255 away from zero. To obtain the absolute value of a number using CircuitPython, you use abs(). You can get the absolute value of a single number or you can get the absolute value result of an equation. Try typing different numbers into your REPL to see the results. For example: -255 and 0 - 255 are both equal to -255, however, as you can see, the absolute value of both is 255. What does this have to do with blinking our NeoPixel? We're going to use abs() in our Blink code to cycle between 255 and 0. This will allow us to cycle back and forth between red and off. Since we're only changing one number in the (R, G, B) tuple, our NeoPixel Blink code looks like this:) This cycles between cpx.pixels[0] = (255, 0, 0) and cpx.pixels[0] = (0, 0, 0). Load it on your Circuit Playground Express and see the difference! Next, we're going to use this example to learn a new concept!
https://learn.adafruit.com/hacking-ikea-lamps-with-circuit-playground-express/blink-vs-blink
CC-MAIN-2019-35
refinedweb
483
76.62
How Symfony2 Differs from Symfony1 How Symfony2 Differs from Symfony1¶ The Symfony2 Framework embodies a significant evolution when compared with the first version of the framework. Fortunately, with the MVC architecture at its core, the skills used to master a symfony1 project continue to be very relevant when developing in Symfony2. Sure, app.yml is gone, but routing, controllers and templates all remain. This article walks through the differences between symfony1 and Symfony2. As you'll see, many tasks are tackled in a slightly different way. You'll come to appreciate these minor differences as they promote stable, predictable, testable and decoupled code in your Symfony2 applications. So, sit back and relax as you travel from "then" to "now". Directory Structure¶ When looking at a Symfony2 project - for example, the Symfony Standard Edition - you'll notice a very different directory structure than in symfony1. The differences, however, are somewhat superficial. The app/ Directory¶ In symfony1, your project has one or more applications, and each lives inside the apps/ directory (e.g. apps/frontend). By default in Symfony2, you have just one application represented by the app/ directory. Like in symfony1, the app/ directory contains configuration specific to that application. It also contains application-specific cache, log and template directories as well as a Kernel class ( AppKernel), which is the base object that represents the application. Unlike symfony1, almost no PHP code lives in the app/ directory. This directory is not meant to house modules or library files as it did in symfony1. Instead, it's simply the home of configuration and other resources (templates, translation files). The src/ Directory¶ Put simply, your actual code goes here. In Symfony2, all actual application-code lives inside a bundle (roughly equivalent to a symfony1 plugin) and, by default, each bundle lives inside the src directory. In that way, the src directory is a bit like the plugins directory in symfony1, but much more flexible. Additionally, while your bundles will live in the src/ directory, third-party bundles will live somewhere in the vendor/ directory. To get a better picture of the src/ directory, first think of the structure of a symfony1 application. First, part of your code likely lives inside one or more applications. Most commonly these include modules, but could also include any other PHP classes you put in your application. You may have also created a schema.yml file in the config directory of your project and built several model files. Finally, to help with some common functionality, you're using several third-party plugins that live in the plugins/ directory. In other words, the code that drives your application lives in many different places. In Symfony2, life is much simpler because all Symfony2 code must live in a bundle. In the pretend symfony1 project, all the code could be moved into one or more plugins (which is a very good practice, in fact). Assuming that all modules, PHP classes, schema, routing configuration, etc. were moved into a plugin, the symfony1 plugins/ directory would be very similar to the Symfony2 src/ directory. Put simply again, the src/ directory is where your code, assets, templates and most anything else specific to your project will live. The vendor/ Directory¶ The vendor/ directory is basically equivalent to the lib/vendor/ directory in symfony1, which was the conventional directory for all vendor libraries and bundles. By default, you'll find the Symfony2 library files in this directory, along with several other dependent libraries such as Doctrine2, Twig and Swift Mailer. 3rd party Symfony2 bundles live somewhere in the vendor/. The web/ Directory¶ Not much has changed in the web/ directory. The most noticeable difference is the absence of the css/, js/ and images/ directories. This is intentional. Like with your PHP code, all assets should also live inside a bundle. With the help of a console command, the:publish-assets command. Autoloading¶ One of the advantages of modern frameworks is never needing to worry about requiring files. By making use of an autoloader, you can refer to any class in your project and trust that it's available. Autoloading has changed in Symfony2 to be more universal, faster, and independent of needing to clear your cache. In symfony1, autoloading was done by searching the entire project for the presence of PHP class files and caching this information in a giant array. That array told symfony1 exactly which file contained each class. In the production environment, this caused you to need to clear the cache when classes were added or moved. In Symfony2, a tool named Composer handles this process. The idea behind the autoloader is simple: the name of your class (including the namespace) must match up with the path to the file containing that class. Take the FrameworkExtraBundle from the Symfony2 Standard Edition as an example: The file itself lives at vendor/sensio/framework-extra-bundle/Sensio/Bundle/FrameworkExtraBundle/SensioFrameworkExtraBundle.php. As you can see, the second part of the path follows the namespace of the class. The first part is equal to the package name of the SensioFrameworkExtraBundle. The namespace, Sensio\Bundle\FrameworkExtraBundle, and package name, sensio/framework-extra-bundle, spells out the directory that the file should live in ( vendor/sensio/framework-extra-bundle/Sensio/Bundle/FrameworkExtraBundle/). Composer can then look for the file at this specific place and load it very fast. If the file did not live at this exact location, you'd receive a Class "Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle" does not exist. error. In Symfony2, a "class does not exist" error means that the namespace of the class and physical location do not match. Basically, Symfony2 is looking in one exact location for that class, but that location doesn't exist (or contains a different class). In order for a class to be autoloaded, you never need to clear your cache in Symfony2. As mentioned before, for the autoloader to work, it needs to know that the Sensio namespace lives in the vendor/sensio/framework-extra-bundle directory and that, for example, the Doctrine namespace lives in the vendor/doctrine/orm/lib/ directory. This mapping is entirely controlled by Composer. Each third-party library you load through Composer has its settings defined and Composer takes care of everything for you. For this to work, all third-party libraries used by your project must be defined in the composer.json file. If you look at the HelloController from the Symfony Standard Edition you can see that it lives in the Acme\DemoBundle\Controller namespace. Yet, the AcmeDemoBundle is not defined in your composer.json file. Nonetheless are the files autoloaded. This is because you can tell Composer to autoload files from specific directories without defining a dependency: This means that if a class is not found in the vendor directory, Composer will search in the src directory before throwing a "class does not exist" exception. Read more about configuring the Composer autoloader in the Composer documentation. Using the Console¶ In symfony1, the console is in the root directory of your project and is called symfony: In Symfony2, the console is now in the app sub-directory and is called console: Applications¶ In a symfony1 project, it is common to have several applications: one for the front-end and one for the back-end for instance. In a Symfony2 project, you only need to create one application (a blog application, an intranet application, ...). Most of the time, if you want to create a second application, you might instead create another project and share some bundles between them. And if you need to separate the front-end and the back-end features of some bundles, you can create sub-namespaces for controllers, sub-directories for templates, different semantic configurations, separate routing configurations, and so on. Of course, there's nothing wrong with having multiple applications in your project, that's entirely up to you. A second application would mean a new directory, e.g. my_app/, with the same basic setup as the app/ directory. Bundles and Plugins¶ In a symfony1 project, a plugin could contain configuration, modules, PHP libraries, assets and anything else related to your project. In Symfony2, the idea of a plugin is replaced by the "bundle". A bundle is even more powerful than a plugin because the core Symfony2 Framework is brought in via a series of bundles. In Symfony2, bundles are first-class citizens that are so flexible that even core code itself is a bundle. In symfony1, a plugin must be enabled inside the ProjectConfiguration class: In Symfony2, the bundles are activated inside the application kernel: Routing ( routing.yml) and Configuration ( config.yml)¶ In symfony1, the routing.yml and app.yml configuration files were automatically loaded inside any plugin. In Symfony2, routing and application configuration inside a bundle must be included manually. For example, to include a routing resource from a bundle called, configuration is a bit like app.yml in symfony1, except much more systematic. With app.yml, you could simply create any keys you wanted. By default, these entries were meaningless and depended entirely on how you used them in your application: In Symfony2, you can also create arbitrary entries under the parameters key of your configuration: - YAML - XML - PHP article titled "Service Container". This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
http://symfony.com/doc/2.8/introduction/symfony1.html
CC-MAIN-2018-22
refinedweb
1,556
54.42
castsY classesTo. I couldn't resist to create a method to deal with a scenario even less common than WhenSome. The crazy scenario here is that you have N tasks of type Task<T> and you want to return when a random task completes. The easiest way to do this is to just pick a random task and wait for it like this: 1: public static Task<T> WhenRandom<T>(params Task<T>[] tasks) 2: { 3: var random = new Random(); 4: return (from task in tasks 5: orderby random.Next() 6: select task).FirstOrDefault(); 7: } However what if you want to be able to cancel the WhenRandom call you need to be a little more creative I guess: 8: public static async Task<T> WhenRandom<T>(CancellationToken cancellationToken, 9: params Task<T>[] tasks) 10: { 11: var random = new Random().Next(0, tasks.Length); 12: var remainingTasks = new List<Task<T>>(tasks); 13: while (remainingTasks.Count > 0) 14: { 15: await Task.WhenAny(remainingTasks); 16: for (int i = 0; i < remainingTasks.Count; i++) 17: { 18: if (remainingTasks[i].IsCompleted) 19: { 20: if (random-- == 0) 21: { 22: return await remainingTasks[i]; 23: } 24: 25: remainingTasks.RemoveAt(i--); 26: } 27: } 28: 29: cancellationToken.ThrowIfCancellationRequested(); 30: } 31: 32: return default(T); 33: } In this last version I don't pick a random task and wait for it but I rather pick a random completed task, i.e. given the same random number the order in which tasks complete will affect which task is returned.
http://blogs.msdn.com/b/cellfish/archive/2012/12.aspx?PostSortBy=MostViewed&PageIndex=1
CC-MAIN-2015-32
refinedweb
249
62.88
Change icon of commanddata On 08/03/2013 at 02:23, xxxxxxxx wrote: User Information: Cinema 4D Version: 13 Platform: Windows ; Language(s) : C++ ; --------- Hello, I like to exchange the icon of a commanddata plugin. For objects it's working fine with the MSG_GETCUSTOMICON message and set it in GetCustomIconData. But not for a commanddata. I recieve this message also, but it's not updated the icon. How does it works for commanddata plugins? regards Marky On 08/03/2013 at 02:30, xxxxxxxx wrote: Well, very hacky one, but you could blit on the bitmap returned by GetIcon();. -Niklas On 08/03/2013 at 02:51, xxxxxxxx wrote: oh, sorry, I don't understand. In the commanddata I don't have a GetIcon() function. Do you have a short exmaple? On 08/03/2013 at 03:23, xxxxxxxx wrote: There's a GetIcon function in the SDK, lib_customicon or sth like that. Not at home atm. -Niklas On 08/03/2013 at 04:31, xxxxxxxx wrote: Something like this, not tested, but should give you the gist of it: #include <lib_iconcollection.h> IconData* ico = GetIcon(PLUGIN_ID); if (ico && ico->bmp) { BaseBitmap* bmp = ico->bmp; for (LONG i=ico->x; i < ico->x + ico->w; i++) { for (LONG j=ico->y; j < ico->y + ico->h; i++) { Real lower = static_cast<Real>((i - ico->x) * (j - ico->y)); Real upper = static_cast<Real>(ico->w * ico->h); LONG x = (lower / upper) * 255; bmp->SetPixel(i, j, x, x, x); } } } On 08/03/2013 at 22:23, xxxxxxxx wrote: super, thanks a lot
https://plugincafe.maxon.net/topic/7005/7903_change-icon-of-commanddata
CC-MAIN-2020-40
refinedweb
260
71.65
Talk:Key:shop Contents - 1 Values for electronic vehicles like segway? - 2 Feature Page Shops - 3 shop=communication - 4 Mapnik render - 5 Repair, Rental, Clothes... Semantic improvements - 6 how to tag wholesale supermarkets? - 7 delicatessen shop - 8 Value suggestion: home_care - 9 shop=houseware - 10 [Retired] shop=wedding_office - 11 shop=swimming_pool? - 12 Values carpet and flooring - 13 self-checkout suggestion - 14 shops and housenumbers - 15 Catering service - 16 Dairy - 17 Value suggestion: health_supplies or medical_supplies - 18 mobile store / shop-van / van-shop - 19 Game shops - 20 shop values for _supply, _supplies, _supplement, _supplements - 21 TOC location and alignment - 22 shop=mail vs shop=shipping vs amenity=post_office (united states) - 23 Missing tags: shop=lottery vs shop=bookmaker - 24 Coffee & tea - 25 shop=furnace vs. British English - 26 Shop that handles pre-orders only - 27 Nut shop - 28 Namespaces for shops Values for electronic vehicles like segway? Do we already have values for shops selling electronic vehicles like segway, e-scooters, electronic skateboards etc _but not_ e-bikes or e-motorcycles, or all of them? One shop as example. I did not find anything "official", i.e. in the wiki, but only a hand full of different values in taginfo - which makes searching & rendering quite difficult. As the amount of such shops is increasing quicker and quicker, IMHO we shall define a basic mapping scheme quickly to avoid a big clean-up / consolidation task requiring to find many different shop-values that are used in the wild. As we have a value "vehicles" I suggest either - to use shop=vehicles because many shops selling/renting EVs do also sell/rent other kinds of vehicles (normal bikes or motorcycles), and add a wiki page for vehicletype:type where we define values like e-scooter etc (so we do not end up with all typing variants). This is not used so far. - a shop value "EV" or "electric vehicles" but not "BEV" / "Battery Electric Vehicles" because then other types of energy source besides battery (solar panels, fuel cells etc) would not be covered. This value could be used in conjunction with other shop values, e.g. electronics, motorcycle or bicycle, if a shop sells also those things. To clarify which kind of EVs are sold, I suggest EV:type just like for motorcycle:type. It's list of values could grow over time, but finding shops that sell/repair/rent/... some kind of EV would be easy due to common shop=EV. What do you think of the suggestions? Do you have others? --Schoschi (talk) 08:55, 3 June 2018 ) shop=communication For a shop selling telephone and internet access, all the rage at the moment. Longbow4u 22:20, 25 August 2008 (UTC) - See Talk:Key:internet_access#internet access shop -- Harry Wood 18:25, 18 July 2009 (UTC) Mapnik render If shop can be attached on , than the renderer does wrong by writing the name on the edge see here --Shmias 15:47, 30 March 2009 (UTC) As, unfortunately, mapnik overlays the house number with the shop icon when both are defined on a way (area), one may prefer to define the shop and name key only on the lower left node of the area (example house 78). --A Pirard 13:12, 13 June 2012 (BST)) shops and housenumbers The following is a text fragment I cut from the definition page and stored here for documentation purposes -- Dieterdreist 17:03, 13 June 2012 (BST) - As, unfortunately, mapnik overlays the house number with the shop icon when both are defined on a way (area), one may prefer to define the shop and name key only on the lower left node of the area (example house 78). - The mapping should take place independently from current mapnik rendering behaviour. The suboptimal treatment of housenumbers together with other features like gates, shops and similar will most probably change in the near future. The above suggestion leads IMHO to topology errors: a node part of the area is topologically defining an object on this way (in the case of a building outline I am tempted to interpret this as most likely an object attached on the outside wall, e.g. a vending machine). If a shop is inside a building, please put it inside the building (i.e. not on the outline). --Dieterdreist 17:08, 13 June 2012 (BST) Catering service What about a catering service? Any ideas? Anyone? --Neil Dewhurst, Lyon France (talk) 12:09, 12 February 2013 (UTC) Dairy How about shop=dairy for smalls shop that sell mostly dairy products such as milk and cheese? I think that shop=convenience is closest, but a bit of an overstatement when it comes to the range of products available. --OSMfan (talk) 15:19, 12 March 2013 (UTC) - As of today, there are 58 instances of this in taginfo, though not a single one of those instances is in the United States. There are also a few outliers like "cheese_dairy", "Dairy", "dairy_products", "cheese dairy", "butcher; dairy" and "dairy produce". There are a lot more "cheese" instances (247) and additional outliers like "Cheese", "deli; cheese", "cheese;coffee;tea"; "seafood;cheese" and "cheese, milk products, fish". --Ceyockey (talk) 21:58, 4 May 2013 (UTC) Value suggestion: health_supplies or medical_supplies A shop where you can by "personal medical equipment" stuff like: Exercise balls, Bandages, Crutches, Arch support, Orthotics, Sphygmomanometers, Glucometer, ... In germany usually called "Sanitätshaus" ... not sure know how to translate this. -- Jaldhaka (talk) 15:44, 27 April 2013 (UTC) In the United States you would typically refer to this assortment as 'medical supplies'. There are stores which are dedicated to this, which could be tagged with shop=medical_supply (216 uses); such shops tend not to include a pharmacy. Often a store having an internal pharmacy typically stocks a subset of materials (e.g. Walgreens, Walmart, larger supermarkets); in this case, you could use medical_supply=yes, though this tag is not in use at present. --Ceyockey (talk) 13:43, 4 May 2013 (UTC) mobile store / shop-van / van-shop Does some tag, showing, that a shop is a mobile store (shop-van / van-shop, not to be confused with shops that sell mobile phones and accessories), exist? It is a real situation, when there is some place, designated for mobile store. Sometimes a car arrives a few days a week and works only a few hours (so a place, designated for store usually is empty), sometimes, a car is standing at its place during a day, departures for a night and comes back next morning, sometimes, a car is standing almost all time (so such mobile store looks like building because of its fixed location). I think, that we should have 3 next tags: 1) tag, showing, that a shop is a mobile store (perhaps, mobile_store=yes, shop-van=yes, van-shop=yes?); 2) tag, showing working hours of a store (we've already have such tag - opening_hours=*); 3) tag, showing the period, when a car is usually located on its place (perhaps, arrangement=...?). Dinamik (talk) 06:07, 25 June 2013 (UTC) Game shops There should be someway to tag shops that sell games (ex: EB Games, Gamestop). As of now, shop=video_games and shop=games are in use, and I think both should be documented; shop=video_games for EB Games, Gamestop, and shop=games for board game stores like 401 Games, The Hairy Tarantula. -Cdrini (talk) 03:12, 30 June 2013 (UTC) shop values for _supply, _supplies, _supplement, _supplements Discussion on Tagging email list in the August 2013 archive; initial posting entitled "shop values for _supply, _supplies, _supplement, _supplements?" → --Ceyockey (talk) 23:08, 30 August 2013 (UTC) TOC location and alignment The alignment of the TOC in [1] makes the page unreadable, as the normal text is placed at a small area left to the TOC. I've simplified it into a standard TOC in this change [2]. What is the better location for the TOC? I prefer simple things. --Werner2101 (talk) 16:05, 26 May 2014 (UTC) shop=mail vs shop=shipping vs amenity=post_office (united states) I am thinking that locations for FedEx, UPS and their ilk could be designated using "shop=mail", but I'm wondering what others have used. There are right now only 5 instances of use for shop=mail. Thanks for your input. --Ceyockey (talk) 12:59, 25 October 2014 (UTC) - Most likely amenity=post_office + operator=UPS or something like that, but you should ask your local community to be sure. --Jgpacker (talk) 13:36, 25 October 2014 (UTC) - Due to the lack of other options, I have used exactly that (amenity=post_office + name=DHL + operator=DHL) around here. But I'd welcome other suggestions. Jotam (talk) 22:06, 4 July 2015 (UTC) - Tagging these as amenity=post_office seems a little off since they're private businesses, not part of the public postal system. I understand that that line is blurred in some countries but in the USA there's a clear distinction. - It's even more awkward to tag independent shipping shops as amenity=post_office since they don't really have an operator and offer shipping by a variety of companies: DHL, FedEx, UPS, etc. - I'm going to recommend shop=shipping, which is about 25 times more common than shop=mail. I'd like to be able to run a query to count the use of amenity=post_office for these private mail shops, but there's no effective way to write such a query (the operator tag is not employed in a consistent fashion) which again leads me to believe that amenity=post_office is the wrong tag here, if there's a very clear real-world distinction that can't be made clear in the tagging. Jmapb (talk) 16:37, 6 May 2018 (UTC) Both tags are missing at shop page, but I believe we should choose one first. Xxzme (talk) 10:01, 6 November 2014 (UTC) - I don't think we need to choose one. They seem to be different things. --Jgpacker (talk) 18:21, 6 November 2014 (UTC) - PS: We don't need to add all shop=* tags in this list. All documented shop=* tags are already listed at Category:Tag descriptions for key "shop". But feel free to add the ones you find useful. --Jgpacker (talk) 18:26, 6 November 2014 (UTC) Coffee & tea There are shop=coffee and shop=tea, but what if a shop is selling both? shop=coffee;tea doesn't render good. --Bbbz (talk) 03:17, 16 September 2015 (UTC) shop=furnace vs. British English Using the word "furnace" to refer to any kind of domestic heating unit is not correct in British English. That word is used to refer to industrial furnaces including waste disposal, power generation and perhaps even crematoria. A domestic unit for heating your house is termed a "boiler". A more universal term may be HVAC - which covers heating, ventilation and air conditioning. The use of "sidewalk" (a US term) is accepted because it is frequently understood and doesn't cause any confusion in the UK. But the word "furnace" is widely understood in the UK to mean something different to its US usage, so it should be avoided in tagging. --Csmale (talk) 18:49, 20 December 2015 (UTC) Shop that handles pre-orders only Trying to accurately map a groceries shop that handles online orders and then delivers online orders only through a physical branch. Is there any special tag and value for this? (link to said shop is here) Nut shop I am adding some stores that sell peanuts, almonds, nuts, dried fruits and stuff. I don't know what's the best tag for them. In the discussion of shop=spices Talk:Tag:shop=spices, there is a recommendation to use shop=nuts. Looking into taginfo, I see there are only 24 shops tagged as nuts, 8 as nut and a few others tagged nut_something. I could use shop=greengrocer. What's the recommended tag for them? --Cserpell (talk) 03:23, 19 May 2017 (UTC) - I have the same question, for now I am putting shop=nuts as well, because there is no appropriate classification that I can find. Not sure what the process is for adding a new classification to this page. —Ynhockey (talk) 23:54, 3 November 2017 (UTC) - How about - * shop=greengrocer - * fruit:type=nuts - I'm in favor of namespace subtags instead of inventing a new shop type for every purpose, - so you may describe any mixture of shops (respectively their services or goods) rtfm Rtfm (talk) 08:39, 4 November 2017 (UTC) Namespaces for shops As already mentioned by User:Peter Reed in the Talk:shops talk, there's a need "to categorise the more difficult types of shop". - Shops which sell several products currently need a second "shop=" node / way - Services they offer can't be easily differentiated (in a standardised way) - Tags like second_hand=yes or repair=yes may be confusing as you don't know which product is meant (and if the whole shop is second hand or they just also offer it beside) Instead of re-inventing each shop tagging for a more detailed specification, there should be a namespace scheme for shops in general (as it otherwise leads to a mess of tags and endless discussions). As an example, check shop=bicycle and shop=motorcycle and leave your comment here. I'd like to collect some opinions before starting a proposal, especially for different kind of shops (while shop=computer is comparable to the above mentioned, other shops may have other needs). rtfm Rtfm (talk) 12:19, 20 May 2017 (UTC)
https://wiki.openstreetmap.org/wiki/Talk:Key:shop
CC-MAIN-2019-35
refinedweb
2,262
57.71
Hi, I am working on a code and i need to change the code to make it easier to maintain. I have learned about re use of code so im thinking this is the way i shud be looking at the code but I cant seem to find anything to change. the code is: public class Product { /* Instance variables */ public int stockLevel; // The number of items of this product in stock which is updated // by the deliver() and acquire() methods. Objects of other // classes will need to find out its value. public String description; // The name of the product which will be set to a meaningful // string by the constructor, and then never changed. // Objects of other classes will need to find out its value. /** Constructor for objects of class Product public Product(String aDescription) { super(); this.stockLevel = 0; this.description = aDescription; } /* Instance methods */ /** * Reduce the stock level by the value of the argument. * Method presumes availability has already been checked. */ public void deliver(int anAmount) { this.stockLevel = this.stockLevel - anAmount; } /** * Increase the stock level by the value of the argument */ public void acquire(int anAmount) { this.stockLevel = this.stockLevel + anAmount; } /** * Returns a string giving details of the product */ public String productDetails() { return "Product " + this.description + ": " + this.stockLevel + " in stock."; } }what I have come up with so far is I will declare if someone could help that wud be great. Thanks
http://www.javaprogrammingforums.com/whats-wrong-my-code/1509-maintainability.html
CC-MAIN-2017-30
refinedweb
231
65.01
start rendering in pictureviewer via script On 23/09/2015 at 05:55, xxxxxxxx wrote: i want to start a rendering without a mouseclick on a remote maschine. to archived that i wrote a script which is able to call c4d like: ('"C:\Program Files\MAXON\CINEMA 4D R16\CINEMA 4D.exe" -render "'+c4d+'"') were c4d = the c4d file but i need to see the progress in the picture viewer. is there a sneaky way to get my desired results? an alternative is to use the autostart python thing for it. On 24/09/2015 at 07:08, xxxxxxxx wrote: Hi, I don't think Commandline Renderer has such an option. But the "autostart python thing" can be used for it. Simply introduce your own commandline option, like so: import sys import c4d def PluginMessage(id, data) : if id == c4d.C4DPL_COMMANDLINEARGS: for arg in sys.argv: if arg.find("-render2pv") == 0: argComponents = arg.split(' ') c4d.documents.LoadFile(argComponents[1]) c4d.CallCommand(12099, 12099) break return True I suggest to create an render2pv folder in your plugins folder. Then store the above code in a render2pv.pyp file into this folder. Then you can call Cinema 4D like so: C:\Program Files\MAXON\CINEMA 4D R16\CINEMA 4D.exe "-render2pv myscenefile.c4d" Just note, that I wrote the commandline parsing so that you have to pass -render2pv and the scenefile as one argument, thus the quotation marks. Because otherwise C4D would load the scene file automatically and then you run into problems, because C4D will load the file after this code and you'll end up with a requester asking if the identical file should be loaded again. Only remaining drawback, there will be a warning about the unknown commandline argument in the console. On 26/09/2015 at 02:10, xxxxxxxx wrote: yay this is a quite neat solution for that! thank you!
https://plugincafe.maxon.net/topic/9088/12067_start-rendering-in-pictureviewer-via-script
CC-MAIN-2020-50
refinedweb
313
65.83
. public String feedback; You can then add your new method. Obviously, unless you call your new method somehow, it's useless. Locate yourObviously, unless you call your new method somehow, it's useless. Locate yourPagemethod and make some magic.. Okay. Now on to some more interesting topics. From within your project, open your EOModel file. It will most likely be listed under the Resources Group. Opening the EOModel should launch the EOModeler application. In your Toolbar, you will find a button to generate Java class files for your Entities. If you've been following along with the past articles, you should only have one Entity named User. It should be configured similar to this:. public class _User extends EOGenericRecord { public _User() { super(); } Next, you should create a new file. When presented with the Assistant, select the WebObjects Java class option. You should name your new class " User.java" and select the Application Server as the Target. In order to implement the pattern, you'll simply inherit from ? You should now be able to build and run your application. When you receive the Login form, try: Usernameor Passwordfields empty.. You'll notice D2W is displaying the property nameFull without prettifying it. You can change the display by simply selecting nameFull under the Show list and entering Full Name in the Display field: username attribute, and simply renamed both the name and. User Entity. User, and the D2WDisplayMailTo. By selecting this component, whenever a List page for a User needs to display the mailto: link. Therefore, clients will be able to simply click on a User's While still viewing the List page, you will be able to edit a User by clicking the Edit button . The D2WAssistant should update to reflect the fact you are now viewing an Edit page. Again, select the When you click on the Save button, in the D2WAssistant, you should notice your web page update. You can now edit a User's
http://www.macdevcenter.com/lpt/a/4530
crawl-002
refinedweb
326
67.55
A TensorFlow variable is the recommended way to represent shared, persistent state your program manipulates. This guide covers how to create, update, and manage instances of tf.Variable in TensorFlow. Variables are created and tracked. Setup This notebook discusses variable placement. If you want to see on what device your variables are placed, uncomment this line. import tensorflow as tf # Uncomment to see where your variables get placed (see below) # tf.debugging.set_log_device_placement(True) Create a variable To create a variable, provide an initial value. The tf.Variable will have the same dtype as the initialization value. my_tensor = tf.constant([[1.0, 2.0], [3.0, 4.0]]) my_variable = tf.Variable(my_tensor) # Variables can be all kinds of types, just like tensors bool_variable = tf.Variable([False, False, False, True]) complex_variable = tf.Variable([5 + 4j, 6 + 1j]) A variable looks and acts like a tensor, and, in fact, is a data structure backed by a tf.Tensor. Like tensors, they have a dtype and a shape, and can be exported to NumPy. print("Shape: ", my_variable.shape) print("DType: ", my_variable.dtype) print("As NumPy: ", my_variable.numpy()) Shape: (2, 2) DType: <dtype: 'float32'> As NumPy: [[1. 2.] [3. 4.]] Most tensor operations work on variables as expected, although variables cannot be reshaped. print("A variable:", my_variable) print("\nViewed as a tensor:", tf.convert_to_tensor(my_variable)) print("\nIndex of highest value:", tf.math.argmax(my_variable)) # This creates a new tensor; it does not reshape the variable. print("\nCopying and reshaping: ", tf.reshape(my_variable, [1,4])) A variable: <tf.Variable 'Variable:0' shape=(2, 2) dtype=float32, numpy= array([[1., 2.], [3., 4.]], dtype=float32)> Viewed as a tensor: tf.Tensor( [[1. 2.] [3. 4.]], shape=(2, 2), dtype=float32) Index of highest value: tf.Tensor([1 1], shape=(2,), dtype=int64) Copying and reshaping: tf.Tensor([[1. 2. 3. 4.]], shape=(1, 4), dtype=float32) As noted above, variables are backed by tensors. You can reassign the tensor using tf.Variable.assign. Calling assign does not (usually) allocate a new tensor; instead, the existing tensor's memory is reused. a = tf.Variable([2.0, 3.0]) # This will keep the same dtype, float32 a.assign([1, 2]) # Not allowed as it resizes the variable: try: a.assign([1.0, 2.0, 3.0]) except Exception as e: print(f"{type(e).__name__}: {e}") ValueError: Cannot assign value to variable ' Variable:0': Shape mismatch.The variable shape (2,), and the assigned value shape (3,) are incompatible. If you use a variable like a tensor in operations, you will usually operate on the backing tensor. Creating new variables from existing variables duplicates the backing tensors. Two variables will not share the same memory. a = tf.Variable([2.0, 3.0]) # Create b based on the value of a b = tf.Variable(a) a.assign([5, 6]) # a and b are different print(a.numpy()) print(b.numpy()) # There are other versions of assign print(a.assign_add([2,3]).numpy()) # [7. 9.] print(a.assign_sub([7,9]).numpy()) # [0. 0.] [5. 6.] [2. 3.] [7. 9.] [0. 0.] Lifecycles, naming, and watching In Python-based TensorFlow, tf.Variable instance have the same lifecycle as other Python objects. When there are no references to a variable it is automatically deallocated. Variables can also be named which can help you track and debug them. You can give two variables the same name. # Create a and b; they will have the same name but will be backed by # different tensors. a = tf.Variable(my_tensor, name="Mark") # A new variable with the same name, but different value # Note that the scalar add is broadcast b = tf.Variable(my_tensor + 1, name="Mark") # These are elementwise-unequal, despite having the same name print(a == b) tf.Tensor( [[False False] [False False]], shape=(2, 2), dtype=bool) Variable names are preserved when saving and loading models. By default, variables in models will acquire unique variable names automatically, so you don't need to assign them yourself unless you want to. Although variables are important for differentiation, some variables will not need to be differentiated. You can turn off gradients for a variable by setting trainable to false at creation. An example of a variable that would not need gradients is a training step counter. step_counter = tf.Variable(1, trainable=False) Placing variables and tensors For better performance, TensorFlow will attempt to place tensors and variables on the fastest device compatible with its dtype. This means most variables are placed on a GPU if one is available. However, you can override this. In this snippet, place a float tensor and a variable on the CPU, even if a GPU is available. By turning on device placement logging (see Setup), you can see where the variable is placed. If you run this notebook on different backends with and without a GPU you will see different logging. Note that logging device placement must be turned on at the start of the session. with tf.device('CPU:0'): # Create some tensors a = tf.Variable([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]) c = tf.matmul(a, b) print(c) tf.Tensor( [[22. 28.] [49. 64.]], shape=(2, 2), dtype=float32) It's possible to set the location of a variable or tensor on one device and do the computation on another device. This will introduce delay, as data needs to be copied between the devices. You might do this, however, if you had multiple GPU workers but only want one copy of the variables. with tf.device('CPU:0'): a = tf.Variable([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) b = tf.Variable([[1.0, 2.0, 3.0]]) with tf.device('GPU:0'): # Element-wise multiply k = a * b print(k) tf.Tensor( [[ 1. 4. 9.] [ 4. 10. 18.]], shape=(2, 3), dtype=float32) For more on distributed training, refer to the guide. Next steps To understand how variables are typically used, see our guide on automatic differentiation.
https://www.tensorflow.org/guide/variable?hl=no
CC-MAIN-2022-21
refinedweb
1,013
59.8
NAME ksql_stmt_alloc— allocate a statement on a database connection LIBRARYlibrary “ksql” SYNOPSIS #include <sys/types.h> #include <stdint.h> #include <ksql.h>enum ksqlc ksql_stmt_alloc(struct ksql *sql, struct ksqlstmt **stmt, const char *sqlstmt, size_t id); DESCRIPTIONThe ksql_stmt_allocfunction allocates a SQL statement sqlstmt on a database connection sql previously opened with ksql_open(3). It must be matched by a call to ksql_stmt_free(3). Upon success, this will fill in the stmt pointer. The id is used to identify the statement in error messages and should uniquely identify the statement. If a non-empty cfg->stmts structure documented in ksql_cfg_defaults(3) is passed to ksql_alloc(3) or ksql_alloc_child(3), the stored statement is looked up by id and the sqlstmt value is ignored. If id is not a valid index of cfg->stmts.stmtsz or if the current role does not permit access to the statement, an error message is emitted on stderrand the program is immediately terminated. The ksql_stmt_allocfunction handles a locked database (specifically, SQLITE_BUSY, SQLITE_LOCKED, or SQLITE_PROTOCOL) by sleeping for a random interval, then trying again infinitely. RETURN VALUESThis returns KSQL_MEMon allocation failure, KSQL_NOTOPENif the database isn't connected, or KSQL_DBif there were errors invoking sqlite3_prepare_v2(3), otherwise KSQL_OKon success.
https://kristaps.bsd.lv/ksql/ksql_stmt_alloc.3.html
CC-MAIN-2021-21
refinedweb
201
55.95
I wanted to test Locust for my Project on Windows 10. The Script seems to run properly (no Errors in CMD), but i can't connect to the web interface (ERR_CONNECTION_REFUSED). I am guessing, that this has to do with Browser/Windows config, but i can't find the problem. I have no Proxy set up in Lan settings, i get my ip from DNS, and i have no changes in my hosts file. locustfile.py from locust import HttpLocust, TaskSet, task class UserBehavior(TaskSet): def on_start(self): """ on_start is called when a Locust start before any task is scheduled """ self.login() def on_stop(self): """ on_stop is called when the TaskSet is stopping """ self.logout() def login(self): self.client.post("/login", {"username":"tester", "password":"abcd1234"}) def logout(self): self.client.post("/logout", {"username":"ellen_key", "password":"education"}) @task(2) def index(self): self.client.get("/") @task(1) def profile(self): self.client.get("/profile") class WebsiteUser(HttpLocust): task_set = UserBehavior min_wait = 5000 max_wait = 9000 host="" CMD D:\workspace\WebTesting>locust CMD result : [2019-05-13 09:49:45,069] LB6-001-DTMH/INFO/locust.main: Starting web monitor at *:8089 [2019-05-13 09:49:45,070] LB6-001-DTMH/INFO/locust.main: Starting Locust 0.11.0 When i interrupt the script in the command line i get the "KeyboardInterrupt" message and some statistics without data python -m http.server 8089 seems to work
https://techqa.club/v/q/cant-reach-locust-webinterface-err-connection-refused-c3RhY2tvdmVyZmxvd3w1NjEwODY1MA==
CC-MAIN-2021-39
refinedweb
234
59.5
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "az_aztec.h" #include "azk_komplex.h" Include dependency graph for azk_create_vector.c:). Create Komplex vector from Complex vector. Transforms a complex-valued vector vc to a real vector where vc in Fortran complex format, i.e., if dimension of complex system is N then vc is of length 2*N and the first complex value is stored with the real part in vc[0] and the imaginary part in vc[1] and so on. Create Komplex vector from Real and Imaginary Parts. Transforms a complex vector where double precision arrays hold the real and imaginary parts separately. Create Komplex vector from Real and Imaginary Parts. Transforms a complex vector where double precision arrays hold the real and imaginary parts separately.
http://trilinos.sandia.gov/packages/docs/r10.0/packages/komplex/doc/html/azk__create__vector_8c.html
crawl-003
refinedweb
129
61.53
A small collection of ideas for MOP 2 ideas by Jochen: - we should no longer directly invoke methods like equals, setProperty and such.(see GROOVY-2635 for example) - we should think about changing GroovyObject into a pure marker interface (if setProperty is needed in the logic we have problems) - the MetaClass should be able to overwrite all methods including setProperty (this implies that we do not directly call setProperty) - Comparable needs a rethought. This interface is not well to be used if you have to handle objects of different types - it would be nice to be able to define only one operand like < or > instead of having to define both. At last being able to define these additionally - we have to test if creating direct method call classes in call sites is doable. This would be like Reflector, but only for a single method, allowing the JIT to inline the method without much hazzle. currently reflection means to have a border where the JIT can not really inline the call. Maybe we should also have different modes here, to allow users to still use reflection if this version has a problem on certain VMs or in certain scenarios - as a design goal I would like to transform the MetaClass from a directly method invoking to a request oriented method returning class. This would be especially interesting for call site caching. The user could still write his invokeMethod method, but instead of calling that method directly in the Metaclass we would let the MetaClass return a method wrapper that can do the call to invokeMethod. - I would also like to add a Listener to each MetaClass which allows other parts of the program to be informed when a MetaClass is changed in any kind. This could probably also be used to invalidate call site caches. - A version information added to the MetaClass allows a very fast check for changes. We could also think about adding an additional version cache for method names. the idea here is to have a simple array and to let a call site cache the index to the array, which means the index is equal to a complete method signature or only to name. By checking the information in there(for example an referential identity check with the cached method) would allow the call site to quickly know if it needs to update or not. Such an array would grow other time if it needs to reflect dynamically added methods as well. So we should do this maybe only for the default methods. - another design goal should be that if a code modifies a Metaclass, then as much changes as possible should be done by the thread modifying the metaclass. that means that this thread will for example call all the listeners, probably update caches, reorganize structures.. what ever - The allow call sites faster access without going through the registry it would be good to have some kind of handle that can be used to directly access the MetaClass. This means that either the real MetaClass must not be replaced (only on the implementation side of course) or that the handle is update if a replacement happens. - I would also like to add a module concept based on different meta class registries. For this a class using a module will contain some kind of information that will cause all code directly in this class to use only the meta classes from the registry and probably no per instance meta class. As some kind of namespace is required to differentiate one module from another we could couple this with the package "package foo with module" or by using a package like reference to a constant "module Foo.myRegistry" (Foo is a normal class, myRegistry is a final public static field of type MetaClassRegistry or an alibi type. Annotations seem not to be fitted for this, as they would have to use enums, classes, primitives or strings and none but strings seem to fit that. enums won't work as I would have to define all possibilities in the runtime not allowing the user to define his own ideas of how it should work. Using classes would work, but where is the connection here to make it clear what we mean? primitives lack memorization, the user would have not only to remember a number, he would also have to make sure that it is not used somewhere else too. Strings are better, but there might still a name conflict. An Annotation would be doable if we want to make the module per class, but I am not sure this makes much sense. - we should also look if we can not reduce the amount of MOP methods. We need one for each non public method, true, but we possibly do not need all these super$ methods - as Java still does direct calls we should think about adding the ability to methods to check if their MetaClass has a new version for this method. This way Java could easily access the meta class stored method. Of course we then have to also find a way to access the original method as well, as this method may be needed - we should also think if we should add mechanisms we add for method calls should also be added for property access. - we need to look at method caching in builders.... or maybe this is not needed as a builder might not be executed often - for the meta class implementation we should also think about having special method selectors like I have in ClosureMetaClass. - if we do call site caching, then we should probably remove the method caching inside the MetaClass, especially if we add specialized method selectors - a point of discussion is if a method added to the parent classes metaclass should also affect the current metaclass or not. - we need also to test if rewriting the method itself at runtime is possible and what it will cost. - we need to investigate if inlining primitive type operations at compile time is possible. This can help avoiding boxing and direct usage of primitive types. Of course before doing something like that we would have to check the Metaclasses and all operations if this is allowed. If we do the idea with the method signature arrays we could also define constants for certain operations like +,-,*,/ to do the check very fast. If I do for example 1+1 I could compile this as: "if (Integer.metaclass.version==0 && Integer.metaclass.ops1==0) {iload 1; iload 1; iadd;}" 0 would show it is the default version and 1 is a numeric constant to see if the operation + is still the default or not. - maybe the module concept can be used to enable calling private methods/fields. With this we could disable access to private from outside the class per default.. of course onlny after we solved the Closure problem (information loss with getProperty) - invokeMethod should loose its double role for being a method missing and at the same time a direct invocation way from Java
http://docs.codehaus.org/display/GROOVY/MOP+2.0+ideas
CC-MAIN-2014-15
refinedweb
1,179
63.73
>> I have faced an issue on 24.3.90.2 when using my extension that >> includes an expression like: >> (cl-loop with (a b c) = '(1 2 3) return (+ a b c)) > It should be fixed now. Only in `trunk', tho. > I'd appreciate if Stefan took a look at the fix, trunk revision > 117000. I don't know why that (eq body 'setq) test was there in the > first place, but removing it doesn't seem to break anything. I installed the patch below in emacs-24, which is a bit more careful (your patch ends up let-binding variables redundantly, and it renames vars in cases where it's not necessary). Stefan === modified file 'lisp/emacs-lisp/cl-macs.el' --- lisp/emacs-lisp/cl-macs.el 2014-03-24 20:41:08 +0000 +++ lisp/emacs-lisp/cl-macs.el 2014-04-21 21:09:22 +0000 @@ -1542,12 +1542,14 @@ (if (and (cl--unused-var-p temp) (null expr)) nil ;; Don't bother declaring/setting `temp' since it won't ;; be used when `expr' is nil, anyway. - (when (and (eq body 'setq) (cl--unused-var-p temp)) + (when (or (null temp) + (and (eq body 'setq) (cl--unused-var-p temp))) ;; Prefer a fresh uninterned symbol over "_to", to avoid ;; warnings that we set an unused variable. (setq temp (make-symbol "--cl-var--")) ;; Make sure this temp variable is locally declared. - (push (list (list temp)) cl--loop-bindings)) + (when (eq body 'setq) + (push (list (list temp)) cl--loop-bindings))) (push (list temp expr) new)) (while (consp spec) (push (list (pop spec)
https://lists.gnu.org/archive/html/emacs-devel/2014-04/msg00303.html
CC-MAIN-2019-35
refinedweb
262
79.19
Using GDI+ and Visual Basic .NET Ken Getz MCW Technologies, LLC June 2003 Summary: Provides a simple but demonstrative example of how a clock demo can take advantage of the GDI+ features made available by the .NET Framework, as well as sharpen up your Visual Basic .NET skills. (6 printed pages) Download the GDIPlus.msi sample file. Note To run the sample application, you will need a version of Microsoft Windows® with version 1.0 Service Pack (SP) 2 of the .NET Framework installed. All code presented in this article is Visual Basic® .NET version, written and tested using Visual Studio® 2002. Testing was done on a system with Windows XP Professional SP1. Introduction Using the Application Application Design Issues How It Works Conclusion Introduction GDI+, a group of classes provided by the System.Drawing namespace in the .NET Framework, makes it possible for developers to easily create graphic applications by taking advantage of the graphics capabilities built into Windows. This simple application demonstrates many of the GDI+ objects and their members, including (but not limited to) working with Pen, Brush (solid and gradient), Point, Rectangle, Ellipse, and Region objects. It's amazing how many GDI+ features you can pack into a simple clock demo! Using the Application The sample application allows you to display the current time using either an analog display (as shown in Figure 1 below) or a digital display. Figure 1. GDI+ handles all of the graphics work for this simple clock application To get started, load the solution into Visual Studio .NET and press F5 to load and run the project. By default, the clock appears in its analog guise with its form border showing, but you can alter the behavior as follows: - Resize the form to resize the clock. The clock face always centers itself as a circle in the minimum of the width and height of the form's client area. - Double-click the form (or right-click and select Show Frame from the Context menu) to toggle the display of the form surrounding the clock face. From the Context menu, you can try out these options: - Select Analog or Digital to display the clock in analog or digital format. The digital format is much simpler, but less interesting. - Select Always on Top to allow the clock to float on top of all other windows. (Selecting this option sets the form's TopMost property.) - Select the Run at Startup option to have the application add the appropriate entry in the Windows registry, causing the clock to load each time you log in. (To be honest, when testing this application, one of the testers liked it so much he requested this option so that the clock would always be running on his desktop. I've adopted this mode, as well. We both really miss the Windows NT® Clock application.) - If you're displaying the clock in analog mode, select CountDown (and an interval) to display a pie-shaped region indicating a time delay. Originally added to demonstrate the FillPie method, this feature allows you to set a timer and see a flashing warning when the time has expired. - If you're displaying the clock in analog mode, select Gradient (and a particular gradient) to display one of the four preset gradient fills for the clock. You can investigate the code to see how the gradients work, but each of the four gradients shows off different features of GDI+. - Select Fill Color, and one of the available colors, to set the clock's background color. Note that this particular menu shows off another use for the GDI+ features—this owner-draw menu includes a rectangle showing the colors. Creating owner-draw menus isn't difficult, and it's well documented. You can use this example as a starting point for your own individualized menus, displaying graphics, or bitmaps. - Select Text Color, which uses the color-picker common dialog to select a color for the text on the clock. Application Design Issues In addition to using a clock as the inspiration for this GDI+ demonstration, the sample application splits its functionality between the sample form, frmClock.vb (which handles all the menus and user-interface for the application) and the class Clock.vb (which displays the clock itself). By separating the form from the clock, you'll find that you can reuse the Clock class in any application that requires an analog clock. All you need to do is instantiate a Clock instance, set a few properties, and then call the appropriate method of the Clock object from a Paint event. See the How It Works section below for more information. To use the Clock class outside of this application, add the Clock.vb file to your own project. The constructor for the Clock object expects you to supply a Form object: Then, in the code that handles your form's Paint event, call the appropriate code to display either a digital or analog version of the clock: For the analog clock, you must supply a radius and origin (the coordinates of the upper-left corner of the clock, not the center). For the digital clock, you simply supply a Rectangle object describing the area in which you'd like to display the clock (normally, the ClientRectangle property of a form). You're probably expecting to find a Timer control on the form itself, updating the display every second. That's a reasonable design, but not the one used here. The Clock class itself maintains its own timer, and simply invalidates its parent form when it determines that it's time to update the display. Using this technique, you can have multiple clocks, each maintaining its own time, without needing to worry about the various timers. (It's useful to note that the clock doesn't invalidate the entire parent form—that would be too expensive, and unnecessary. Instead, the clock only invalidates the region of the form where it's displaying content—the region describing the clock.) When the Clock class invalidates the parent form (or a region of the form), the form's Paint event code runs again, and the clock gets redisplayed. Because almost every method in GDI+ requires a Graphics object as a context in which to display output, it's simplest to pass that Graphics context as a parameter to the clock's Draw method from the Paint event of the form. The event procedure receives, as its parameter, a PaintEventArgs object that includes the form's graphics context as one of its properties. The sample project uses code like this, from the form's Paint event handler: How It Works Once you get past the concept of the seemingly backwards manner in which the application works (that is, the form calling the Draw method of the Clock class from its Paint event handler, and the timer in the Clock class raising the form's Paint event by invalidating a region of the form), you may want to dig into various aspects of how the GDI clock works. Handling the Timer Because you can't really be sure a timer's Tick event will occur at absolutely regular intervals, you can't set the Interval property of a Windows Timer to exactly one second and expect that your clock will update correctly. Instead, this clock uses an alternate technique. It sets the interval to 1/10 second, and each time the code runs, it compares the current second to the previously displayed second. If the values are different, the Clock class knows it's time to update the display, and then (and only then) triggers the parent form's invalidation. You'll find code like this in the Clock class's Timer_Tick event handler: The Dreaded Trigonometry You probably thought you would never use high-school trig again (if you even survived it once), but it's crucial when you want to work with circular objects. In this application, most of the "math" work is done in converting to and from angles around the clock face to actual points on the form display, so that the code can draw the necessary lines and circles on the screen. In the Clock class, the GetPoint, GetHourDegrees, GetMinuteDegrees, and GetSecondDegrees procedures handle the ugly work of converting from circular coordinates to rectangular coordinates, and back. (See the GetHourDegrees method for an explanation of what the code is doing.) Yes, you're going to need to dig into the dark recesses of your brain to figure out what the Sin and Cos functions are doing, but the most important facts to remember are (look at a clock face as you work through this): - The circle (the clock face) is divided into 360 even units (called "degrees"), with 0 degrees at the 3 o'clock position, 90 degrees at 12 o'clock, and so on. You can also treat angles as negative values, so that –90 degrees is at 6 o'clock, –180 degrees is at 9 o'clock, and so on. - Rectangular positions are measured as Point objects (or PointF objects, if you need floating-point accuracy), measured as x and y coordinates. In this example, the Origin parameter passed to the Draw method of the clock indicates the upper-left corner of the clock face (imagine a rectangle drawn around the clock, with the origin being the upper-left corner of that rectangle). The x coordinate grows as you move to the right. The y coordinate grows as you move down. - The GetPoint function converts from an angle, a center point, and a distance from the center, to a standard point. That is, this procedure converts from polar (circular) coordinates to rectangular coordinates, taking into account the particular geometry of this application. - The GetHour/Minute/SecondDegrees methods convert the hour, minute, and second portions of the current time and return the position of the particular clock hand, in degrees, for the current time. For example, at 21:00, the GetHourDegrees method returns –180 degrees. - The Clock class uses the return value from the GetHourDegrees method (and its siblings) to render the clock hands. The code calls the GDI+ DrawLine method to draw each hand, using different Pen objects for each hand. The constructor for the Clock class sets up some specific pens for use while the clock displays its time, including the use of the StartCap and EndCap properties of the Pen object. Using these properties, the hands can automatically include the arrow on one end, and the "ball" on the other. - The Clock class calls the GetPoint method, using a somewhat abbreviated radius, to calculate the points at which to draw the "tick" marks and the hour numbers on the clock face, as well. (The path gradient also uses this method, calculating the locations of points along the circle's edge.) It will take some studying to completely understand the trigonometry used by the Clock class. If you only care about the GDI+ functionality, you can probably get by with just believing that it works, but in that case, you can instead focus on the methods that call GDI+ members directly, drawing lines and circles, brushes, pens, and so on. Owner-Draw Menus GDI+ also makes it possible (and relatively easy) to handle the drawing of each menu item from within your code. This example uses owner-draw techniques for the Fill Color menu, selecting from a range of colors described in an array in the form's class: Private LightColors() As Color = _ {Color.LightBlue, Color.LightCoral, _ Color.LightCyan, Color.LightGoldenrodYellow, _ Color.LightGray, Color.LightGreen, _ Color.LightPink, Color.LightSalmon, _ Color.LightSeaGreen, Color.LightSkyBlue, _ Color.LightSlateGray, Color.LightSteelBlue, _ Color.LightYellow, Color.White} In order to create an owner-draw menu, you must set the OwnerDraw property of the menu item to True (either in code or in the designer). Setting this property moves the responsibility for creating and displaying the menu item to your code. Yyou must react to the DrawItem and MeasureItem events of each menu item, and your event-handling code must provide the necessary information to display each item. The sample application draws a small rectangle, in each color, next to text containing the name of each item. This code uses GDI+ to display both the rectangle and the text. Setting Form Styles Displaying a gradient on the clock isn't very difficult (see the GradientFill1, GradientFill2, and GradientFill3 procedures in Clock.vb), but updating the gradient fill takes processing power, and it's not something you want to do every second. To solve the problem, you need some way of keeping a cached copy of the form's contents in memory, and only updating the small portion of the form that needs updating each second (normally, just the second hand and the seconds display in the digital portion). You could manage this all yourself, but a simpler solution is to allow the form to "double-buffer." You can have the form manage its own updating, so that displaying a background gradient doesn't cause your clock to flash every second. In addition, by default, there's no code handling the form's Resize event. Without taking extra steps, if you simply call the Clock class from your form, resizing the form won't cause the clock to repaint until the next second ticks by and the Clock class invalidates its parent. You can solve both these problems using the SetStyle method of the Form class. The frmClock_Load procedure includes code like this (see the documentation for the SetStyle method for more information): Saving User Settings At the request of testers who decided to actually use the GDIClock application daily, the sample application includes code to save and restore your settings to a configuration file. The sample includes the AppSettings class that handles the details of reading and writing from the configuration file (in the Documents and Settings/<UserName>/Application Data/GDIClock folder), and the RegSettings class which handles saving the "run at startup" information in the registry. If you're interested in how to read and write information in configuration files, you might want to check out those classes as well. Conclusion There you have it. A simple but demonstrative example of how a clock demo can take advantage of the GDI+ features made available by the .NET Framework, as well as sharpen up your Visual Basic skills.
https://msdn.microsoft.com/en-us/library/aa289159(vs.71).aspx
CC-MAIN-2016-30
refinedweb
2,405
59.03
public class Solution { public int findMin(int[] nums) { int result=nums[0]; for(int i=0;i<nums.length-1;i++){ if(nums[i]>nums[i+1]){ result=nums[i+1]; } } return result; } } No, this is not a best solution. I just want a java solution which is much faster, since binary search is not much faster than this solution. @wansongsong.jack, I disagree with your argument. Binary search is and should be much faster than your method. The reason you don't see a difference in running time at OJ is only because the test cases here are not tough enough as I mentioned here. Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.
https://discuss.leetcode.com/topic/16544/is-there-a-faster-solution
CC-MAIN-2017-51
refinedweb
122
65.12
When most of use began programming, we started looking for various project ideas to try. I've noticed card games come up a lot, so let's have a look at some ways to implement a card game. We will be focusing on the core of many card games, the cards and the deck. The Card class is fairly simple, although it can be done a number of ways. I've chosen to use numeric variables for the internal data about the suit and rank, which will get converted to strings via predefined arrays when they need to be outputed. This lets us easily compare the suits and ranks (see if they're equal or sequential), without trying to use strings to represent them internally. If we used strings, we'd have to use if ( card1.rank.equals("three") && card2.rank.equals("four") ) with a whole bunch of other checks for different numbers, as opposed to if ( card1.rank + 1 == card2.rank) So, we end up with something like package javacards; public class Card { private int rank, suit; private static String[] suits = { "hearts", "spades", "diamonds", "clubs" }; private static String[] ranks = { "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King" }; Card(int suit, int rank) { this.rank=rank; this.suit=suit; } public @Override String toString() { return ranks[rank] + " of " + suits[suit]; } public int getRank() { return rank; } public int getSuit() { return suit; } } So we have read-only suit and rank variables, a simple constructor, and a toString method. The class will be ultra fast as it knows which strings to output just by accessing indexes of static arrays. We don't even have to use String.ParseInt(). The Card class really isn't that complicated, so most of our time will be spent on the Deck. Our Deck class will have to make and dole out Cards. To hold our Cards, we can use a number of different storage methods/structures. I will show examples using an array and an ArrayList. Each storage method will have a constructor to make the cards, a drawFromDeck() method that will return a random card, and a getTotalCards() method that will return the number of cards left in the Deck. The hard part is, once we return a card we have to make sure it isn't used again. Using Array:; do { index = generator.nextInt( 52 ); } while (cards[index] == null); i--; Card temp = cards[index]; cards[index]= null; return temp; } public int getTotalCards() { return i; } } [code] First we have a constructor which fills our deck will the cards of various suits and ranks. Every time we add a card at x we increment x to put us at a fresh spot. drawFromDeck() returns a random card from our container. We need to get a random index and return that card. We have a post-test loop that finds an array index (less than 52) that isn't null. When we find one, we return its card and set it to null. Our deck might need to give feedback on how many cards are left, (maybe to determine if there are enough for another round of black jack or if we need to add all the cards back), so we make a variable i that represents the number cards left in the deck. i starts at 51 and is decremented everytime we take a card out. So if i is -1, then we know we're out of cards. Now we need to write a test for this program. We want to make sure the cards that get drawn really are drawn in a random order. So we have main: [code] package javacards; public class Main { public static void main(String[] args) { Deck deck = new Deck(); Card C; System.out.println( deck.getTotalCards() ); while (deck.getTotalCards()!= 0 ) { C = deck.drawFromDeck(); System.out.println( C.toString() ); } } When we run this, we get a good look at how the cards would come off the deck. They seem random enough, so we're okay. However, this tutorial would be pretty int if I just ended it here, and many of you are probably looking at the drawFromDeck() method with disdain at its ineffeciency, so we press on...... This is really a pretty sloppy way of doing things, as we just keep trying to find an index in the array with a card in it. If the index doesn't have a card in it, we look in a new index, unti we finally get one. We really should only have to use one index, and we can do that if we make sure that we're only looking through places that actually have cards in them. So to fix this, we use our variable i that represents the number of cards in the array that aren't used up yet. Now we need to make sure our selection comes only from that set of cards. Say the first card we take out is at index 4. We set that to null and decrement the number of cards. But index 4 is still null. We know we have 51 cards left, but we don't know where they are in the deck. There could be empty/null indexes all over the place, at 4, 7, 20, and all we can do is just keep our fingers crossed that we don't land on one of them. How about we organize our empty card spots a little better? Maybe we can switch the chosen card's empty spot with the last card in the deck? Let's put our i variable to work. array example number 2:; index = generator.nextInt( i ); Card temp = cards[index]; cards[index]=cards[i]; cards[i]=null; i--; return temp; } } Our random index now is some number within the boundaries of the cards left, instead of always 52. If we have 40 cards left, index won't be 48. We get a random card, SWITCH IT'S NOW NULL LOCATION WITH THE LAST CARD IN THE DECK, and then return the random card. we picked the fourth card, and put the last card in its place. The null value we get when we take out the card at index 4 is now located at spot 51, the last spot in the deck, as opposed to some random spot in the middle of the deck. This ensures that the indexes up through i always have cards in them, and that the null values are always moved to the end of the array. When we get a random index between 0 and i, we can be 100% sure that there is a fresh card in that spot. To test this method, we can use the exact same test code as we did for the first example, as all that's changed is the internal workings of the deck class. In fact, we will use that test code for all our Deck implementations. We've implemented a lot of features with arrays that could've easily been done with generics, like an ArrayList (adding a card to the end of the array, removing a card by setting its place to null, keeping track of the size of the array, etc. ). An ArrayList has most of the features we need built in already, so we don't have to write our own code to do them. ArrayList example: package javacards; import java.util.Random; import java.util.ArrayList; public class Deck { private ArrayList<Card> cards; Deck() { cards = new ArrayList<Card>(); for (int a=0; a<=3; a++) { for (int b=0; b<=12; b++) { cards.add( new Card(a,b) ); } } } public Card drawFromDeck() { Random generator = new Random(); int index= generator.nextInt( cards.size() ); return cards.remove(index); } public int getTotalCards() { return cards.size(); } } We can just add a card to the end of the ArrayList with add(), as opposed to making our own variable to keep track of what index we're on. cards.size() automatically keeps track of how many cards are left in the array. When we return a card, we can actually remove it from the ArrayList, thus decrementing the size, leaving us with a collection that only has cards left in it. (as opposed to just replacing its spot with the last card in the array, and setting the last spot to null) Run the test code again to make sure everything still works. To mention other data structures, we could have used a linked list to hold the cards, but our primary purpose is to extract a card from the deck, not to iterate through the cards, making a linked list not the best choice. One of the goals of OO programming is to emulate the real world. When we return a card from our deck, we remove it from the deck so it's not used again, just like a real dealer would. But when a dealer gives you a card, they just take it off the top of the deck, they don't fish through the deck to get a random card. They shuffle the deck, randomizing the cards before hand, so they can just pop cards off the top later and know that they're random. This leads us to another example: ArrayList 2: shuffling the cards before we deal them package javacards; import java.util.Random; import java.util.ArrayList; public class Deck { private ArrayList<Card> cards; Deck() { cards = new ArrayList<Card>(); int index_1, index_2; Random generator = new Random(); Card temp; for (int a=0; a<=3; a++) { for (int b=0; b<=12; b++) { cards.add( new Card(a,b) ); } } for (int i=0; i<100; i++) { index_1 = generator.nextInt( cards.size() - 1 ); index_2 = generator.nextInt( cards.size() - 1 ); temp = (Card) cards.get( index_2 ); cards.set( index_2 , cards.get( index_1 ) ); cards.set( index_1, temp ); } } public Card drawFromDeck() { return cards.remove( 0 ); } public int getTotalCards() { return cards.size(); } } We put the cards in the ArrayList, then randomly take 100 pairs of cards and switch them, shuffling our deck. To draw from the deck, we just return the last element/card, and then remove that card from the deck. All the randomization is done before hand in the constructor (prior to any actually dealing of the cards), making our drawFromDeck method much simpler and less processor intensive. Piece of cake! I hoped you've enjoyed and learned something from this tutorial! Please post any and all questions, comments, concerns, or commentary! --------CrazyJugglerDrummer This post has been edited by crazyjugglerdrummer: 20 June 2009 - 10:20 AM
https://www.dreamincode.net/forums/topic/110380-deck-of-cards-using-various-methods/
CC-MAIN-2018-43
refinedweb
1,756
79.3
Created attachment 169753 [details] Use plain isfinite() in science/veusz During the exp-run in bug 208158, it was found that science/veusz gives errors with libc++ 3.8.0 [1]: veusz/helpers/src/qtloops/qtloops.cpp:354:10: error: no member named 'isfinite' in namespace 'std'; did you mean simply 'isfinite'? if( ! isFinite(val) ) ^~~~~~~~~~~~~ veusz/helpers/src/qtloops/isnan.h:58:24: note: expanded from macro 'isFinite' # define isFinite(_a) (std::isfinite(_a)) ^~~~~ This is because the file includes <math.h>, not <cmath>, and the isnan.h header checks whether isfinite() is a macro. Since it is a function in libc++, it attempts to use std::isfinite(), which is only defined if you include <cmath>. Fix this by letting isnan.h always use the plain isfinite() for FreeBSD. This is similar to how it always selects the plain isnan() for FreeBSD, just above that definition. [1] testbuilds are fine. A commit references this bug: Author: pi Date: Fri May 13 18:29:13 UTC 2016 New revision: 415127 URL: Log: science/veusz: Fix build with libc++ 3.8.0 PR: 209094 Submitted by: dom Approved by: devel@stasyan.com (maintainer timeout) Changes: head/science/veusz/files/ head/science/veusz/files/patch-veusz_helpers_src_qtloops_isnan.h Committed, thanks!
https://bugs.freebsd.org/bugzilla/show_bug.cgi?format=multiple&id=209094
CC-MAIN-2020-50
refinedweb
206
60.41
07. December 2020 Parsing JSON Especially when testing websites, you are now and then faced with the problem of having to parse JSON (=JavaScript Object Notation) strings. Often, for this, a JSON library is downloaded and placed into the corresponding plugin directory. After a restart it is then possible to e.g. use the Python JSON library in Jython scripts. In this blog article, however, the JSON library provided by QF-Test should be described. This library is based on the minimal-json-library and has the advantage that: - it is already supplied with QF-Test (so not a plugin first must be installed) - It is available in both Jython and Groovy scripts The following chapters describe how this library can be used for JSON parsing and JSON generation. JSON parsing The general code to parse a JSON string using this library looks like this: from de.qfs.lib.json import Json jsonStr = """{"a" : 1, "b" : "zzz", "c" : [1,2,3]}""" json = Json.parse(jsonStr) (Jython Code to parse a Jython String) import de.qfs.lib.json.Json def jsonStr = """{"a" : 1, "b" : "zzz", "c" : [1,2,3]}""" def json = Json.parse(jsonStr) (Groovy Code to parse a Jython String) Afterwards, you can easily access the different values defined in the JSON string: qf.println(json["a"]) # Output: 1 qf.println(json["b"]) # Output: zzz qf.println(json["c"]) # Output: [1,2,3] qf.println(json["c"][0]) # Output: 1 qf.println(json["c"][1]) # Output: 2 qf.println(json["c"][2]) # Output: 3 (Jython Code in order to access the various values / output them on the terminal) qf.println(json["a"]) // Output: 1 qf.println(json["b"]) // Output: zzz qf.println(json["c"]) // Output: [1,2,3] qf.println(json["c"][0]) // Output: 1 qf.println(json["c"][1]) // Output: 2 qf.println(json["c"][2]) // Output: 3 (Groovy Code in order to access the various values / output them on the terminal) In Groovy, the following notation is also possible for JSON Maps: qf.println(json.a) // Output: 1 (Groovy Code in order to access the various values / output them on the terminal) which makes it possible to "save" further characters in the script. In this context let me also point to Groovy's ?-Notation which is helpful when a certain value can be present in the JSON string but does not have to be present. Generating JSON The general code to generate a JSON string using this library looks like this: from de.qfs.lib.json import JsonBuilder obj = { "a" : [1,2,3,4] } jsonStr = JsonBuilder.toJsonValue(obj) (Jython code to generate a JSON string from an object) import de.qfs.lib.json.JsonBuilder def obj = [ "a" : [1,2,3,4] ] def jsonStr = JsonBuilder.toJsonValue(obj) (Groovy code to generate a JSON string from an object)
https://www.qfs.de/en/blog/article/2020/12/07/parsing-json.html
CC-MAIN-2021-04
refinedweb
468
50.53
Custom EasingCurve Hi, While there are workarounds for this problem, I'm just curious on how this works. I was playing around trying to pass a custom easing curve. I can't find any examples online how to implement it. From the looks of it, qreal myEasingFunction(qreal progress); is the function signature I have to use. However, when I try to set the types and etc, I feel like a dog trying to catch his tail. For the timeline, for setEasingCurve, I'm supposed to pass in QEasingFunction::Custom, which is really a static equation. However, to make it return a custom type is tricky. I'm supposed to pass in the easing function into setCustomType, but the ideas that I tried don't work. Thanks Hi This compiles and runs like expected but its not what u mean ? #include <QEasingCurve> qreal myEasingFunction(qreal progress) { return progress*0.5; } -- (in button click) QEasingCurve c; c.setCustomType(myEasingFunction); for(qreal t = 0.0; t < 1.0; t += 0.1) { qDebug() << ">" << t << " is " << c.valueForProgress(t); } @mrjj said in Custom EasingCurve: QEasingCurve c; c.setCustomType(myEasingFunction); for(qreal t = 0.0; t < 1.0; t += 0.1) { qDebug() << ">" << t << " is " << c.valueForProgress(t); } Hi mrjj, Thanks for your response. That was something that I tried initially, but I was unable to get it to compile. I get this compile-time error: C:\Users\chris\Documents\Qt Projects\untitled6\mainwindow.cpp:26: error: C3867: 'MainWindow::myEasingFunction': non-standard syntax; use '&' to create a pointer to member. I know, somewhat confusing. But what it is trying to say, is that I need myEasingFunction() instead of myEasingFunction. And even with myEasingFunction(), I still need to pass in a variable. I'm thinking your code sample has no errors, but maybe there is something small that I need to do. Because, myEasingFunction is a pointer to a function and I have seen examples of such implementation. - mrjj Qt Champions 2016 Hi It expects a normal function pointer. Not a member function pointer as you tried. its not the same as a standalone function pointer (unless static) as it requires an object to be activated. so void myfunc() is not the same as void mainwindow::myfunc() in this regards. - mrjj Qt Champions 2016 Hi yes You cannot use a member function. It must be free (global) non member function as in my sample. Okay, reading your comment, I got rid of MainWindow part, but still something else is causing that error. just put it above like qreal myEasingFunction(qreal progress) { return progress*0.5; } ... use it here then it should just work. You're really good. I was just looking at my code and realized that I'm using C++, not C#, so you must have the signature declared beforehand and I came back to the forum with you pointing that out. Silly me! Thanks Qt Champion and you were a lot of help like always. I'm sure others will find this useful. Yep, has to see it before use :) Also just as a note You can use a member functions, if its declared with static (in the class .h ) but a normal function is better in my book.
https://forum.qt.io/topic/87754/custom-easingcurve
CC-MAIN-2018-09
refinedweb
534
68.67
Creating a shared library for both managed and unmanaged environment Hi, I'm planning to create a dll design to use for both managed (.NET) and unmanaged (Delphi) environment. The final image has not to be the same. I can build them differently. And I even can have some different and platform dependent wrapper code, no problem. I just want to have a singular cross platform business logic and infrastructure code. What's the best way to achieve this? I know there are ActiveQt and Wrapper for C++/CLI but as I'm not experienced in this area, it would be better to hear from experienced devs. Say, we'd selected the proposed style. Would it be possible to use some structs, enums etc between the caller and our dll or do we have to use only standard types like int, float, double etc. Thanks in advance. /// Murat What I normally do is create the pure C++ class, using custom types and Qt Types then I build a wrapper around it using C++/CLI using some utilities to convert custom types (QString to String^ for example) For example: Foo.h #include <QString> class Foo{ Foo():m_bar("Bar"){} Foo(const Foo& val):m_bar(val.m_bar){} const QString& getBar() const { return m_bar;} void setBar(const QString& val){m_bar=val;} QString m_bar; } Converters.h #include <vcclr.h> #include <msclr\marshal_cppstd.h> namespace ManagedVersions { QString String2QString(String^ a) { return QString::fromStdWString(msclr::interop::marshal_as<std::wstring>(a)); } String^ QString2String(const QString& a) { return gcnew String(a.toStdWString.c_str()) } } ManFoo.h #include "Converters.h" #include "Foo.h" #include <vcclr.h> using namespace System; namespace ManagedVersions { public ref class ManFoo { internal: Foo* Unmanaged; ManFoo(const Foo& a){Unmanaged=new Foo(a);} public: property String^ Bar{ String^ get(){return QString2String(Unmanaged->getBar());} void set(String^ a){Unmanaged->setBar(String2QString(a));} } ManFoo(){Unmanaged=new Foo();} ManFoo(const ManFoo% a){Unmanaged=new Foo(*(a.Unmanaged));} ManFoo(ManFoo^ a){Unmanaged=new Foo(*(a->Unmanaged));} !ManFoo() { if (Unmanaged){ delete Unmanaged; Unmanaged = nullptr; } } ~ManFoo() { this->!ManFoo(); GC::SuppressFinalize(this); } }; } (I omitted the include guards there) There are caveats however, for example when compiling with clr QClipboard doesn't work anymore (or maybe now it does ) Thanks VRonin, your example is much better comparing to the official documentation. Could you give me also some information about the managed side? For example, say we have a struct in Foo.h. What do we have to do to use it directly from .NET? Do we have to also use converter methods for it? (Like having a similar class in ManFoo.h and exchanging members with the native struct from Foo.h). Cheers, I.
https://forum.qt.io/topic/67034/creating-a-shared-library-for-both-managed-and-unmanaged-environment
CC-MAIN-2018-39
refinedweb
438
58.89
0 Hey guys, I am working on this encryption/decryption project and I have just finished writing the encryption part of the code. I complied it and ran it. The first part worked well. However once I chose to encrypt a file ( I didnt choose decrypt because it was not completed), the encrypted part did not output, instead it was an empty space as though there was nothing written to the second string. Can someone take a quick look at my encrypt function and see what is going on with my code, I know its probably just some easy problem, but I've been working on it for a bit and havent solved it yet. Thanks! #include <iostream> #include <string> #include <cctype> using namespace std; void encrypt(string, int); void decrypt(string); int main () { string code; int choice, key; bool wrong = true; do { wrong = true; cout << "Enter 1 to encrypt a message or 2 to decrypt a message?" << endl; cin >> choice; if (choice != 1 || choice !=2) wrong = false; } while(wrong); if (choice == 1) { cout << endl << "Please enter the code that you would like to encrypt." << endl; cin >> code; cout << endl << "Please enter a key 1-100 to encrypt your message." << endl; cin >> key; encrypt(code, key); } else { cout << endl << "Please enter the code that you would like to decrypt." << endl; cin >> code; cout << endl; decrypt(code); } getchar (); getchar (); return 0; } void encrypt (string encrypt_code, int encrypt_key) { string EncryptedChar; for (int i = 0; i <= encrypt_code.length(); i++) { if (encrypt_code[i] + encrypt_key > 126) EncryptedChar[i] = ((encrypt_code[i] + encrypt_key) - 127) + 32; else EncryptedChar[i] = (encrypt_code[i] + encrypt_key); } cout << "Your encrypted code is " << EncryptedChar << "using key " << encrypt_key << endl; }
https://www.daniweb.com/programming/software-development/threads/279157/trouble-with-filling-strings-then-outputting-them
CC-MAIN-2018-13
refinedweb
274
66.37
Now let’s go ahead and implement the handleSubmit and handleConfirmationSubmit methods and connect it up with our AWS Cognito setup. Replace our handleSubmit and handleConfirmationSubmit methods in src/containers/Signup.js with the following. handleSubmit = async event => { event.preventDefault(); this.setState({ isLoading: true }); try { const newUser = await Auth.signUp({ username: this.state.email, password: this.state.password }); this.setState({ newUser }); } catch (e) { alert(e.message); } this.setState({ isLoading: false }); } handleConfirmationSubmit = async event => { event.preventDefault(); this.setState({ isLoading: true }); try { await Auth.confirmSignUp(this.state.email, this.state.confirmationCode); await Auth.signIn(this.state.email, this.state.password); this.props.userHasAuthenticated(true); this.props.history.push("/"); } catch (e) { alert(e.message); this.setState({ isLoading: false }); } } Also, include the Amplify Auth in our header. import { Auth } from "aws-amplify"; The flow here is pretty simple: In handleSubmitwe make a call to signup a user. This creates a new user object. Save that user object to the state as newUser. In handleConfirmationSubmituse the confirmation code to confirm the user. With the user now confirmed, Cognito now knows that we have a new user that can login to our app. Use the email and password to authenticate exactly the same way we did in the login page. Update the App’s state using the userHasAuthenticatedmethod. Finally, redirect to the homepage. Now if you were to switch over to your browser and try signing up for a new account it should redirect you to the homepage after sign up successfully completes. A quick note on the signup flow here. If the user refreshes their page at the confirm step, they won’t be able to get back and confirm that account. It forces them to create a new account instead. We are keeping things intentionally simple but here are a couple of hints on how to fix it. Check for the UsernameExistsExceptionin the handleSubmitmethod’s catchblock. Use the Auth.resendSignUp()method to resend the code if the user has not been previously confirmed. Here is a link to the Amplify API docs. Confirm the code just as we did before. Give this a try and post in the comments if you have any questions. Now while developing you might run into cases where you need to manually confirm an unauthenticated user. You can do that with the AWS CLI using the following command. aws cognito-idp admin-confirm-sign-up \ --region YOUR_COGNITO_REGION \ --user-pool-id YOUR_COGNITO_USER_POOL_ID \ --username YOUR_USER_EMAIL Just be sure to use your Cognito User Pool Id and the email you used to create the account. Next up, we are going to create our first note. If you liked this post, please subscribe to our newsletter, give us a star on GitHub, and check out our sponsors. For help and discussionComments on this chapter For reference, here is the code so farFrontend Source :signup-with-aws-cognito
https://branchv21--serverless-stack.netlify.app/chapters/signup-with-aws-cognito.html
CC-MAIN-2022-33
refinedweb
474
51.75
We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies. + 29 comments "You are given an unordered array consisting of consecutive integers [1, 2, 3, ..., n] without any duplicates." 1 3 5 2 4 6 8 huh? + 62 comments My solution int minimumSwaps(vector<int> arr) { int i,c=0,n=arr.size(); for(i=0;i<n;i++) { if(arr[i]==(i+1)) continue; swap(arr[i],arr[arr[i]-1]); c++; i--; } return c; } + 25 comments Here's a python3 solution that does not assume consecutive values but does assume that values aren't repeated. None of the test cases time out because it looks up indexes to swap using a hash table instead of the list.index method. def minimumSwaps(arr): ref_arr = sorted(arr) index_dict = {v: i for i,v in enumerate(arr)} swaps = 0 for i,v in enumerate(arr): correct_value = ref_arr[i] if v != correct_value: to_swap_ix = index_dict[correct_value] arr[to_swap_ix],arr[i] = arr[i], arr[to_swap_ix] index_dict[v] = to_swap_ix index_dict[correct_value] = i swaps += 1 return swaps + 35 comments a simple sol static int minimumSwaps(int[] a) { int swap=0; for(int i=0;i<a.length;i++){ if(i+1!=a[i]){ int t=i; while(a[t]!=i+1){ t++; } int temp=a[t]; a[t]=a[i]; a[i]=temp; swap++; } } return swap; } + 3 comments If anyone is interested, this is the code I used for python (I was stuck on this for about a week so tried to explain my logic as clear as possible!). Give me some pointers if you have them, relatively new to coding. # Complete the minimumSwaps function below. def minimumSwaps(arr,n,swaps=0): #iterate over entire array for i in range(0,n): #it's good practice to use a boolean guided function in a long for loop, #while will evaluate and IF the statement in it is true it will continue #I used the consecutive, increasing values to swap by index while arr[i] != (i+1): #temp is the correct index of arr[i] temp = arr[i]-1 #swap this with whatever element is where arr[temp] is, this will #continue to swap until arr[i] == index+1 arr[i], arr[temp] = arr[temp], arr[i] #increase swaps swaps+=1 return swaps Sort 2193 Discussions, By: Please Login in order to post a comment
https://www.hackerrank.com/challenges/minimum-swaps-2/forum
CC-MAIN-2021-39
refinedweb
405
51.07
Is there any way I can tell which which default.css is used ? thx -g Hi, can't understand what you mean. What default.css you mean? You can include css for your application and set a path to it. Like this <mx:Style It's relative path to file. Hi Natasha, Thanks for the response.. Sorry if the queston was confusing.. When I build, the compiler uses a default css from the sdk. In the sdk, there are two default.css file one located in "sdk/projects/framework" and the other in "sdk/projects/haloclassic". I'm not sure which one is used, if any. Now that the forums are back online,,, I'll explain the reason for the question: I was creating a custom version of popUpButton. The code would build, but I had a runtime error due to the popUpIcon style class being null. Actually, none of the styles could be found. I placed a definition for the custom control class in both defaults.css files but the style was not picked up. I was modifying the class default.css file because when I referenced "haloclassic.PopUpButtonSkin" could not be found. I couldn't figure out the relative adressing for the "haloclassic" namespace. Since the changes to default.css did not have any affect, I couldn't figure out if the default.css file was used or there was another one built into a swf. I still haven't figured it out, but I moved the parts of the haloclassic style into my local directory, but this work around is not anything I can move into production with. It will make maintenence a nightmare. -g
https://forums.adobe.com/thread/463686
CC-MAIN-2017-51
refinedweb
278
78.35
D.gnu - [Bug 72] New: Wrong code generated (segmentation fault) when class - gdc-bugzilla gdcproject.org Jul 27 2013 Bug #: 72 Summary: Wrong code generated (segmentation fault) when class (in one file) inherits from class (in another file) with interface Classification: Unclassified Product: GDC Version: 4.7.x Platform: All OS/Version: All Status: NEW Severity: normal Priority: Normal Component: gdc AssignedTo: ibuclaw gdcproject.org ReportedBy: power pobox.sk Reduced example: ---------------- File screen3d.d: ---------------- module screen3d; public interface ScreenI { public void initSDL(); public void clear(); } public class Screen3D: ScreenI { public: static int width = 640; static int height = 480; public void initSDL() { resized(width, height); // segfault here } public void resized(int width, int height) { this.width = width; this.height = height; } public void clear() { } } ---------------- File main.d: ---------------- module main; private import screen3d; public class Screen: Screen3D { public override void resized(int width, int height) { super.resized(width, height); } public override void clear() { } } private: Screen screen1; public int main(string[] args) { screen1 = new Screen; ScreenI screen2 = screen1; screen2.initSDL(); return 0; } ---------------- When the example is compiled as two sepparate files, it segfaults. When the example is merged into one file, it works. In disassembly the difference between working and segfaulting version is following: In working version, the method initSDL in the interface of the class Screen is a reference to a thunk function which subtracts 8 (in 32-bit code) from first parameter and then calls the initSDL method in class Screen3D. In segfaulting version, the method initSDL in the interface of the class Screen is a reference to the initSDL method in class Screen3D. I tested it on GDC crosscompiler for ARM linux (running on x64 linux) - gcc version 4.7.3 with gdc commit e63f8a7a5657684c0f2c3d2fd1a9c33eec0208c0 (last commit in gdc-4.7 branch before merging D 2.063). I also tried GCC-4.8-MinGW-GDC-.7z and gcc-4.6.1-tdm-1-gdc-9841510e8ba6-20120109.7z (both from) - I didn't manage to create an executable, but the assembly/disassembly shows the same wrong code. I tried the latest DMD (2.063.2) and it generates correct code. -- Configure bugmail: ------- You are receiving this mail because: ------- You are watching all bug changes. Jul 27 2013
http://www.digitalmars.com/d/archives/D/gnu/Bug_72_New_Wrong_code_generated_segmentation_fault_when_class_5641.html
CC-MAIN-2014-35
refinedweb
365
57.87
[NT] Microsoft Visual C++ 8.0 Standard Library Time Functions Invalid Assertion DoS (Problem 3000) - From: SecuriTeam <support@xxxxxxxxxxxxxx> - Date: 13 Feb 2007 12:19:38 +0200 The following security advisory is sent to the securiteam mailing list, and can be found at the SecuriTeam web site: - - promotion The SecuriTeam alerts list - Free, Accurate, Independent. Get your security news from a reliable source. - - - - - - - - - Microsoft Visual C++ 8.0 Standard Library Time Functions Invalid Assertion DoS (Problem 3000) ------------------------------------------------------------------------ SUMMARY A vulnerability in the way Microsoft's Visual C++ handles large time_t values, allows attackers to overflow the variable, which in turn will cause the value stored inside the time_t variable to be invalid/corrupt, anyone using this value will get an assertion which in turn causes a denial of service vulnerability in the complied program. DETAILS Introduction:() fstat() and may be others.); Both static and dynamic (MSVCR80.DLL) versions of C library are vulnerable. very simple trick. This is also true for Java and JavaScript timestamps. 3. Application where date_t is calculated as a result from user input + some offset (e.g. timezone conversions for date December, 29 2999 23:01 GMT-01:00). An example: e-mail messages, HTTP requests, etc. Example: /* D:\>cl localtime_s.c Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.42 for 80x86 localtime_s.c Microsoft (R) Incremental Linker Version 8.00.50727.42 /out:localtime_s.exe localtime_s.obj D:\>localtime_s.exe (Dr.Watson comes, expected result: "Invalid value") */ #include <time.h> #include <stdio.h> #include <error.h> int main(){ struct tm tm; time_t t = 0x3a3a3a3a3a3a3a3a; if(localtime_s(&tm, &t) != 0) { printf("Invalid value\n"); } else { printf("OK\n"); } return 0; } Workarounds: it doesn't covers the vector where time_t is calculated as a result of time arithmetics. Exploitation: Test application to set file date to 27.09.14896 3touch.c is available from <>. Application compiled with MSVC 8.0, e.g. MSDN sample fstat.c, crashes on attempt to fstat() this file. It may also be used to get interesting results with "dir" command (shows "Invalid argument") if FILETIME is changed to 0x7FFFFF00, but it seems to be different issue. Vendor: 23.08.2006 - Initial vendor notification through secure@xxxxxxxxxxxxx". ADDITIONAL INFORMATION The information has been provided by <mailto:3APA3A@xxxxxxxxxxxxxxxx> 3APA3] IP3 NetAccess Arbitrary File Disclosure - Next by Date: [NEWS] Aruba Networks Unauthorized Administrative and WLAN Access through Guest Account - Previous by thread: [NEWS] IP3 NetAccess Arbitrary File Disclosure - Next by thread: [NEWS] Aruba Networks Unauthorized Administrative and WLAN Access through Guest Account - Index(es): Relevant Pages - SecurityVulns.com: Microsoft Visual C++ 8.0 standard library time functions invalid assertion DoS (P ... invalid assertion DoS. ... Vendor: Microsoft ... Since Microsoft Visual Studio 5.0, ... type to 64 bit integer and time functions to their 64-bit variants. ... (Bugtraq) - [Full-disclosure] SecurityVulns.com: Microsoft Visual C++ 8.0 standard library time functions in ... invalid assertion DoS. ... Vendor: Microsoft ... Since Microsoft Visual Studio 5.0, ... type to 64 bit integer and time functions to their 64-bit variants. ... ) - RE: Vendor wants remote control of our Servers and Workstations ... Of course the age-old problem with security is that ... Vendor has significant access to your internal ... this vendor uses the same method to support a number ... customer and makes significant changes ... ... (Security-Basics) - Security researchers organization ... of security researchers, plain and simple. ... better than the vendor itself. ... industry, telecommunications industry and banking industry has ( ... These are all common ideals we can agree and act upon, ... (NT-Bugtraq)
http://www.derkeiler.com/Mailing-Lists/Securiteam/2007-02/msg00032.html
crawl-001
refinedweb
583
52.66
Asynchronous .NET "Fire and Forget" Pattern by Peter A. Bromberg, Ph.D. A little known technique that I read about quite some time ago on Mike Woodring's site just became important to me, and I though I'd share it. Often in your short happy life as a developer you will come upon requirements to perform a certain set of actions that must be completed within a certain allotted time in order to prevent something bad (such as a TFTP packet request Timeout, for example) from happening. I had such a requirement recently in building a TFTP server for VOIP devices. One of the requirements was to log every device request to the database. However, I have a number of complex operations going on and they must all be completed in under a second or I am "toast" - the device will think I died and that just causes a whole bunch of cascading problems that I can't afford to deal with. Enter the Asynchronous Fire and Forget pattern! Faster than a speeding bullet, it will enable you to kick off a process or a method, never having to wait for anything, and sail on your merry way through your other stuff like a breeze. Hey, I don't have 30 milliseconds to wait for my SQL Insert call to complete! Time is just that tight. I need to Fire it off and keep galloping on! The .NET Framework SDK docs carry a caution that mandates calling EndInvoke on delegates you've called BeginInvoke on, in order to avoid potential leaks. This means you can't just "fire-and-forget" a call to BeginInvoke without the risk of running into memory leak issues. If you need to "bone up" on delegates, I've got a piece I did sometime ago that could be helpful. Mike's sample provided an AsyncHelper class with one public method called, appropriately, "FireAndForget", that is intended to support the fire-and-forget pattern without the fear of leaks. The usage model is that instead of calling BeginInvoke against a delegate, you would instead call the AsyncHelper.FireAndForget, passing that delegate and its parameters as input. What I've put together here is a simple example using my previously written - up SysLog Sender class that sends out greatly simplified SysLog Messages. It's probably not the greatest example, but there are some things you can't expose about your work, so it will suffice as a surrogate for something else - such as a long - running database insert, for example, to illustrate the technique. Here's some sample code to look at and then I'll explain just below it: using System; using System.Reflection; using System.Threading; using Utils.SysLogSender; class App { delegate void SendSysLogMessageDelegate(string ipAddress, string body); static void Main() { int tid = AppDomain.GetCurrentThreadId(); Console.WriteLine("[{0}] Main called", tid); SendSysLogMessageDelegate sld = new SendSysLogMessageDelegate(SendLogMessage); AsyncHelper.FireAndForget(sld,"127.0.0.1", "This is a Syslog test message"); Console.WriteLine("[{0}] Press ENTER to exit", tid); Console.ReadLine(); } static void SendLogMessage(string ipAddress, string message ) { Sender.Send(ipAddress,message); Console.WriteLine(String.Format("Sent Syslog Message to {0} with {1}",ipAddress, message)); } } public class AsyncHelper { class TargetInfo { internal TargetInfo( Delegate d, object[] args ) { Target = d; Args = args; } internal readonly Delegate Target; internal readonly object[] Args; } private static WaitCallback dynamicInvokeShim = new WaitCallback(DynamicInvokeShim); public static void FireAndForget( Delegate d, params object[] args ) { ThreadPool.QueueUserWorkItem(dynamicInvokeShim, new TargetInfo(d, args)); } static void DynamicInvokeShim( object o ) { TargetInfo ti = (TargetInfo)o; ti.Target.DynamicInvoke(ti.Args); } } You'll notice the first thing you must do is declare a Delegate with a signature that exactly matches the method you need to call: SendSysLogMessageDelegate(string ipAddress, string body); Next, you need to create a method that serves as the target of the delegate: static void SendLogMessage(string ipAddress, string message ) { Sender.Send(ipAddress,message); } Finally, we just create an instance of the delegate, pointing to the target method, and call the FireAndForget method of the AsyncHelper class, passing in the delegate and the list of whatever parameters the target method needs. In this case, there are only two, a string IPAddress and a text message, but you can have as many as you want, because the FireAndForget method take a params object[] args parameter list: SendSysLogMessageDelegate sld = new SendSysLogMessageDelegate(SendLogMessage); AsyncHelper.FireAndForget(sld,"127.0.0.1", "This is a Syslog test message"); And that's the basics. No Threading issues, no memory leaks, and NO WAITING for XYZ method to return! You can download the SysLog Sender class along with the above example below. If you aren't familiar with SysLog, I suggest you snag a copy of the free KIWI Syslog Daemon. Now you will not only be faster than a speeding bullet, you'll be able ask for a raise in a single bound! Download the complete VS.NET 2003 solution below Articles Submit Article Message Board Software Downloads Videos Rant & Rave
http://www.eggheadcafe.com/articles/20050818.asp
crawl-002
refinedweb
826
51.78
I'm starting a new series of posts on coding tricks that are simple in principle but often take someone new to a technology too long to find on Stack Overflow. This serves two purposes. First, I can find them again, which always makes things easier when I haven't used something for awhile. Second, maybe other people on the web will randomly find them useful. I'm calling it ST3R, mostly because I'm a dork and I like cubing things. In today's entry, I'm going to share a quick regular expression that will capture all the tags on a single page. This is useful for parsing HTML, XML, or other markup languages. I should note, however, that actual text processing of HTML tags is best handled by an HTML parser, not a basic regex. In this case, however, we're going to play out a scenario where we're writing a python script that will remove all the tags from an HTML document. Let's say our HTML looks something like this: <h1>This is an awesome Website</h1> <p>But I hate all these tags. Wouldn't it be great if we could remove them <span class="bold">all at once</span>.</p> This is some pretty simple HTML that we're looking at, but let's look at how we'd write a python script to remove the tags: import re #import our regex module htmlFile = "THIS STRING CONTAINS THE HTML" # now, we subsitute all tags for a simple space htmlFile = re.sub('<.*?>', ' ', htmlFile) Here, we use the regular expression of <.*?>, which will capture everything that is between two brackets, no matter what. Of course, more advanced processing would take into consideration what's actually between them, but our .* will capture everything and the ? will make sure that the regex is not greedy (meaning it won't capture everything from the first < to the last > in the document). That's all for now!
https://natmeurer.com/simple-technical-tricks-to-remember-1-python-regex-to-remove-tags/
CC-MAIN-2019-26
refinedweb
329
71.24
no-unicode_literals The use of from __future__ import unicode_literals has been deemed an anti-pattern. The problems with it are: It makes it so one can’t jump into the middle of a file and know whether a bare literal string is a byte string or text string. The programmer has to first check the top of the file to see if the import is there. It removes the ability to define native strings (a string which should be a byte string on python2 and a text string on python3) via a string literal. It makes for more context switching. A programmer could be reading one file which has unicode_literals and know that bare string literals are text strings but then switch to another file (perhaps tracing program execution into a third party library) and have to switch their understanding of what bare string literals are.
https://docs.ansible.com/ansible/devel/dev_guide/testing/sanity/no-unicode-literals.html
CC-MAIN-2022-27
refinedweb
146
64.24
User talk:ShuaDaddy From Uncyclopedia, the content-free encyclopedia edit It works. Honest! It helps us if you use it also... Please do. When you make lots of small edits it's a bit of a pain... Thanks. MrN Fork you! 10:05, Jul 13 - That thing that nice chap said about the preview button? Please. ~ 10:31, 13 July 2008 (UTC) edit Wide open butthole This page has now been deleted twice. Uncyclopedia is a parody/satire site; a huge image of a woman holding her anus open is neither parody, satire, nor comedy. It's just disgusting. Please read the links in the welcome message above to understand what constitutes appropriate content for this site. Thank you. -- Sir Codeine K·H·P·B·M·N·C·U·Bu. · (Harangue) - so much for drunken inspiration edit user:Shua Is that you using two accounts or you just hijacked another account? ~ 12:12, 14 July 2008 (UTC) - that was my original account that I couldn't remember the password ShuaDaddy 7:54 PM edit Pee Review I agree that I probably was not the best person to review the article because I'm not a wireless person. I suggest that you resubmit it back to Pee Review with your specification (ie, that you want someone with wireless technical knowledge) in the text of the review so that you get what you want. However, even still, I recommend making it more obvious that you're joking about everything, as not only will it make the article more accessible, it'll make it funnier for those who do know that it's genuinely ridiculous. Cheers, --mrmonkey72 04:57, 27 July 2008 (UTC) edit PLS moving I noticed you asking stuff about the PLS. Feel free to move your article into the main namespace (just click on the move tab at the top). I'd do it for you, but you might as well in case you want to change the title. You can add the template if you want too. If you have any other questions, Dr. Skullthumper is the one to ask. EMC seems to have disappeared. -- 15Mickey20 (talk to Mickey) 10:24, 17 August 2008 (UTC) edit PLS Prize Hey, I still need that postal address to send your PLS prize to... please can you mail me at community@wikia.com as soon as possible? Thanks -- sannse (talk) 07:36, 21 August 2008 (UTC) - Still nothing... have you gone? Wait... you can't answer that if you have... -- sannse (talk) 20:16, 26 August 2008 (UTC) edit Poo Lit: The Judgening We're looking for judges for Poo Lit. Are you game? Are you?! Sir Modusoperandi Boinc! 00:06, September 2, 2009 (UTC) - Thanks for your prompt reply. Pick a spot here. Also, it's best to keep responses on the same talkpage as they started.Sir Modusoperandi Boinc! 00:34, September 2, 2009 (UTC) edit:17, October 5, 2009 (UTC)
http://uncyclopedia.wikia.com/wiki/User_talk:ShuaDaddy
CC-MAIN-2015-48
refinedweb
491
75.2
Appendix B. DocBook and XML - Table of Contents - B.1. DocBook Instances as XML - B.2. The DocBook DTD as XML. Although not yet officially adopted by the OASIS DocBook Technical Committee, an XML version of DocBook is available now and provided on the CD-ROM. B.1. DocBook Instances as XML Most DocBook documents can be made into well-formed XML documents very easily. With few exceptions, valid DocBook SGML instances are also well-formed XML instances. The following areas may need to be addressed. B.1.1. System Identifiers "-//Norman Walsh//DTD DocBk XML V1.4//EN" ""> <chapter><title>Chapter Title</title> <para> This <emphasis>paragraph</paragraph> is important. </para> </chapter> to your catalog files. Alternatively, you can remap system identifers with the SYSTEM catalog directive. If you are faced with documents that don't use public identifiers at all, this is probably your only option. B.1.2. Minimization If you have used SGML minimization features in your instances:<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook V3.1//EN"> <chapter id=(1)chap1><title>Chapter Title</title> <para> This <emphasis>paragraph(2)</> is important. </para> </chapter> they will not be well-formed XML instances. In particular, XMLXML "-//Norman Walsh//DTD DocBk XML V1.4//EN" ""> <chapter id="chap1"><title>Chapter Title</title> <para> This <emphasis>paragraph</emphasis> is important. </para> </chapter> B.1.3. Attribute Default Values Correct processing of this document may require access to the default attributes:<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook V3.1//EN"> <chapter><title>Chapter Title</title> <para> Write to us at: <address(1)> 90 Sherman Street Cambridge, MA 02140 </address> </para> </chapter> "-//Norman Walsh//DTD DocBk XML V1.4//EN" ""> <chapter><title>Chapter Title</title> <para> Write to us at: <address format="linespecific"> 90 Sherman Street Cambridge, MA 02140 </address> </para> </chapter> B.1.4. Character and SDATA Entities<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook V3.1//EN"> <chapter><title>Chapter Title</title> <para> This book was published by O'Reilly(1)™. </para> </chapter> - , DocBk XML DTD is distributed with an unofficial set. "-//Norman Walsh//DTD DocBk XML V1.4//EN" "" [ <!ENTITY trade "™"> <chapter><title>Chapter Title</title> <para> This book was published by O'Reilly™. </para> </chapter> B.1.5. Case-Sensitivity(1)<!DocType Book PUBLIC "-//OASIS//DTD DocBook V3.1//EN"> (2)<book><title>Book Title</title> <chapter><title>Chapter Title(3)</Title> <para> Paragraph test. </para> (4)<PARA> A second paragraph. </PARA> </chapter> </book>. - (1) - Keywords in XML are case-sensitive, and must be in uppercase. - (2) - The name declared in the document type declaration, like all other names, is case-sensitive. - (3) - Start and end tags must use the same case. - (4) - In XML, Para is not the same as PARA. Note that this is a validity error (against the DocBk XML DTD), but it is not an XML well-formedness error. The use of para and PARA as distinct names is as legitimate as using foo and bar, as long as they are properly nested. The result will be something like this:<?xml version='1.0'?> <!DOCTYPE book PUBLIC "-//Norman Walsh//DTD DocBk XML V1.4//EN" ""> <book><title>Book Title</title> <chapter><title>Chapter Title</title> <para> Paragraph test. </para> <para> A second paragraph. </para> </chapter> </book> B.1.6. No #CONREF Attributes<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook V3.1//EN"> <chapter><title>Chapter Title</title> <indexterm id="idx-bor"><primary>Something</primary></indexterm>(1) <para> Paragraph test. </para> <indexterm startref="idx-bor">(2) </chapter>. - (1)(2) - "-//Norman Walsh//DTD DocBk XML V1.4//EN" ""> <chapter><title>Chapter Title</title> <indexterm id="idx-bor"><primary>Something</primary></indexterm> <para> Paragraph test. </para> <indexterm startref="idx-bor"/> </chapter> B.1.7. Only Explicit CDATA-Marked Sections Are Allowed<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook V3.1//EN" [ <!ENTITY % draft "IGNORE"> <!ENTITY % sourcecode "CDATA"> ]> <chapter><title>Chapter Title</title> (1)<![ %draft; [ <para> Draft paragraph. </para> ]]> <para> The following code is totally out of context: <programlisting> <![ (2)%sourcecode; [ if (x < 3) { y = 3; } ]]> </programlisting> </chapter> - (1)(2) - Parameter entities are not allowed in the body of XML documents (they are allowed in the internal subset). - (1) - XML instances cannot contain IGNORE, INCLUDE, TEMP, or RCDATA marked sections. - (2) - CDATA marked sections must use the "CDATA" keyword literally because parameter entities are not allowed. The result will be something like this:<?xml version='1.0'?> <!DOCTYPE book PUBLIC "-//Norman Walsh//DTD DocBk XML V1.4//EN" ""> <chapter><title>Chapter Title</title> <para> The following code is totally out of context: <programlisting> <![CDATA[ if (x < 3) { y = 3; } ]]> </programlisting> </chapter> B.1.8.> XML instances cannot use CDATA or SUBDOC external entities. One option for integrating external CDATA content into a document is to employ a pre-processing pass that inserts the content inline, wrapped in a CDATA marked section. SUBDOC entities may be more problematic. If you do not require validation, it may be sufficient to simply put them inline. XML namespaces may offer another possible solution. The result will be something like this:<?xml version='1.0'?> <!DOCTYPE book PUBLIC "-//Norman Walsh//DTD DocBk XML V1.4//EN" ""> <chapter><title>Chapter Title</title> <para> The following code is totally out of context: <programlisting> <![CDATA[ int main () { .. } ]]> </programlisting> </chapter> B.1.9. No Data Attributes on Notations They're not allowed in XML, so don't add any. B.1.10. No Attribute Value Specifications onEntity Declarations They're not allowed in XML, so don't add any. B.2. The DocBook DTD as XMLBk XML DTD deals with them: The small number of places in which DocBook uses name groups have been expanded. There's one downside: DocBook uses %admon.class; in a name group to define the content model, and attribute lists for elements in the admonitions class. In DocBk XML DTD, this convenience cannot be expressed. If additional admonitions are added, the element and attribute list declarations will have to be copied for them. - No CDATA or RCDATA declared content Graphic and InlineGraphic have been made EMPTY. The content model for SynopFragmentRef, the only RCDATA element in DocBook, has been changed to (arg | group)+. - No exclusions or inclusions on element declarations In DocBook, exclusions are used to exclude the following: Ubiquitous elements (indexterm and BeginPage) from a number of contexts in which they should not occur (such as metadata, for example). Formal objects from Highlights, Examples, Figures and LegalNotices. Formal objects and InformalTables from tables. Block elements and Footnotes from Footnotes Admonitions, EntryTbls, and Acronyms from themselves. Removing these exclusions from DocBk XML DTD means that it is now valid, in the XML sense, to do some things that don't make a lot of sense (like put a Footnote in a Footnote). Be careful. Inclusions in DocBook are used to add the ubiquitious elements (indexterm and BeginPage) unconditionally to a large number of contexts. In order to make these elements available in DocBk XML DTD, they have been added to most of the parameter entities that include #PCDATA. If new locations are discovered where these terms are desired, DocBk XML DTD will be updated. - Elements with mixed content must have #PCDATA first. The content models of many elements have been updated to make them a repeatable OR group beginning with #PCDATA. - Many declared attribute types (NAME, NUMBER, NUTOKEN, and so on) are not allowed They have all been replaced by NMTOKEN or CDATA. - No #CONREF attributes allowed. The #CONREF attributes on indexterm, GlossSee, and GlossSeeAlso were changed to #IMPLIED. The content model of indexterm was modified so that it can be empty. - Attribute default values must be quoted. Quotes were added wherever necessary. > > Back to: DocBook: The Definitive Guide © 2001, O'Reilly & Associates, Inc.
http://www.oreilly.com/openbook/docbook/book/appb.html
CC-MAIN-2016-50
refinedweb
1,280
52.05
This is the mail archive of the libstdc++@gcc.gnu.org mailing list for the libstdc++ project. 17_intro/header_csetjmp.cc is failing with: [...]/17_intro/header_csetjmp.cc:32:6: #error "setjmp_must_be_a_macro" According to section 17.4.1.2 clause 5 of ISO 14882:1998 "Names which are defined as macros in C shall be defined as macros in the C++ Standard Library, even if C grants license for implementation as functions." According to section 7.13 clause 3 of ISO 9899:1999: "It is unspecified whether setjmp is a macro or an identifier declared with external linkage." Thus <csetjmp> [i.e. ./std/csetjmp or the file it directly includes (Aside, is it: ./c/bits/std_csetjmp.h or ./c_std/bits/std_csetjmp.h? ;-)] should provide a macro for setjmp if it is not found after including <setjmp.h>. This code should go in one of those files (I personally think it should go right after the ``#include <setjmp.h>''): #ifndef setjmp #define setjmp(env) setjmp (env) #endif I will do a patch, if someone tells me how to know which file it should go in. ;-) Regards, Loren
http://gcc.gnu.org/ml/libstdc++/2001-03/msg00243.html
crawl-001
refinedweb
184
66.54
12 June 2012 10:01 [Source: ICIS news] SINGAPORE (ICIS)--Sinopec and PetroChina are expected to refine a total of 29.0m-29.5m tonnes of crude in June, with total daily throughput down by 0.2% month on month to around 967,000 tonnes, sources from the two companies said on Tuesday. The two are the biggest refiners in ?xml:namespace> Sinopec lowered its crude throughput target for June to 17.9m-18.0m tonnes, with its daily throughput down by 1.4% from May to approximately 597,000 tonnes partially due to weak demand for gasoline and diesel, sources from the company said. PetroChina is expected to process 11.0m-11.1m tonnes of crude this month, with daily throughput up by 1.9% from May to around 370,000 tonnes, according to sources from the company. The increase was a result of higher refinery operating rates set for the month as the company completed maintenance shutdowns at several big refineries in late May. The combined throughput is expected to rise in July when there are fewer turnarounds, market sources said. However, the rise will be limited as soft demand for oil products will weigh on refinery operating rates,
http://www.icis.com/Articles/2012/06/12/9568400/sinopec-petrochina-cut-daily-crude-throughput-by-0.2-in.html
CC-MAIN-2015-14
refinedweb
201
74.08
In today’s Programming Praxis exercise, our goal is to translate a csv file to an HTML table. Let’s get started, shall we? We will be using the Text.CSV library to read in the csv file. import Text.CSV import Text.Printf Converting the rows to a table consists of doing pretty much the same thing three times: the content is transformed in some way and surrounded by two html tags. Surprisingly, Haskell was not able to correctly figure out the type of the wrap function, complaining about an ambiguity. Presumably this is caused by a combination of printf, which is pretty polymorphic in and of itself and using the wrap function to process a [[String]], [String] and [Char], repsectively. Oh well, having to manually specify the type is not the end of the world. toTable :: [[String]] -> String toTable = wrap "table" unlines . wrap "tr" concat $ wrap "td" id id where wrap :: String -> ([b] -> String) -> (a -> b) -> [a] -> String wrap tag combine f xs = printf "<%s>%s</%s>" tag (combine $ map f xs) tag All that’s left to do is to read in the csv file and call the toTable function if it was succesfully parsed. main :: IO () main = putStrLn . either show toTable =<< parseCSVFromFile "test.csv" Tags: bonsai, code, csv, Haskell, html, kata, praxis, programming, table
https://bonsaicode.wordpress.com/2013/01/15/programming-praxis-translate-csv-to-html/
CC-MAIN-2016-50
refinedweb
218
73.27
Have you ever had to refactor some code – or implement a feature – and due to all the edge cases, you end up dealing with a bunch of nested IF/CASE statements? This can create a lot more mental overhead than necessary, in terms of making sense of the logic. Also, it can make testing a bit more intensive, since you have to create scenarios that hit all of these logic branches. And when you refactor these nested conditionals, you can sometimes break stuff without realizing it, and that is never fun. Today we’re going to use Elixir to create a simple validation based on a user’s age. We will be looking at multi-clause functions with pattern matching and guards in Elixir to accomplish this. One of the most important uses of pattern matching in Elixir is matching the arguments of a function. By pattern matching the arguments of a function, Elixir allows us to overload function calls and use multiple definitions of the same function, based upon the arguments it was called with. Let’s Install Elixir. Trust Me You’re Gonna Love It! Just type “iex” into your terminal and an interactive Elixir shell should spin up. Think of this as irb in Ruby. This is where you can play around with the Elixir language a bit. After you hit return you should see something like this. > iex Erlang/OTP 22 [erts-10.4.4] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [hipe] [dtrace] Interactive Elixir (1.9.1) - press Ctrl+C to exit (type h() ENTER for help) iex(1)> Now let’s make a variable. Let’s try and assign the integer “1” to the variable “x”. iex(1)> x = 1 #=> 1 That seemed to work, but you’d probably be surprised to learn that the equal sign (=) isn’t used for assignment in Elixir. It’s used for matching. To be more specific, it’s used for pattern matching. If we were to swap those values around, it would still return “1”. iex(2)> 1 = x #=> 1 Normally, this would throw an error, but since we’re not assigning the value 1 to x, it’s OK. Forget all about assignment. In Elixir, we match using the equal sign (=). This is pattern matching in its most basic form. There are plenty of articles out there on the basics of pattern matching in Elixir and I highly recommend checking some of them out. Some of you might be asking yourself, “OK, but how or why do I use this?” And that’s a fair question. One way it’s pretty commonly used is with data deconstruction. So for example, let’s go back to iex and make a user. iex(1)> user_1 = %{username: "JoeSchmoe90", dob: %{month: 02, day: 17, year: 1980}} #=> %{dob: %{day: 17, month: 2, year: 1987}, username: "JoeSchmoe90"} Say we need to pull out the year from this map. We could do this by digging into our map. iex(2)> user_1[:dob] #=> %{day: 17, month: 3, year: 1980} We need to go another level deeper; and while we’re at it, lets match this value to a variable. iex(2)> user_1[:dob][:year] #=> 1980 That’s one way to do it, but let’s do this another way – a more Elixir-like way. iex(3)> %{dob: %{year: year_born}} = user_1 #=> %{dob: %{day: 17, month: 3, year: 1980}, username: "JoeSchmoe90"} iex(4)> year_born #=> 1980 Cool! We have this value. But it’s pretty useless without a use case. So, say you had to do some validations on a user, as we often do. # say we had some users with some nested information user_1 = %{username: "JoeSchmoe90", dob: %{month: 03, day: 17, year: 1980}} user_2 = %{username: "JoeSchmoe817", dob: nil} user_3 = %{username: "JoeSchmoe199", dob: %{month: 06, day: 17, year: "1990"}} # Next we need to create a validation that only authorizes users # over the age of 18. # Simple enough we just do some math with the year born. def authorized_user?(user) do year_born = user[:dob][:year] if (current_year() - year_born) >= 18 do true else false end end This works, and it’s pretty easy to follow; but what if we have a user that never provided a date of birth? user_2 = %{username: "JoeSchmoe90", dob: nil} This would break the arithmetic inside of our if statement since we wouldn’t be able to subtract “nil” from the current year. You might think: I’ll just throw another ‘if’ statement in there. def authorized_user?(user) do year_born = user[:dob][:year] if year_born == nil do false else if (current_year() - year_born) >= 18 do true else False end end end This also works, but it’s getting a little noisy. It’s OK for now… but say that for whatever reason our user has a date of birth, but somehow the year was converted to a string. user_3 = %{username: "JoeSchmoe199", dob: %{month: 06, day: 17, year: "1990"}} This would also break our code since we can’t subtract the string “1990” from the current year. So you need to go into your code and add another ‘if’ statement to deal with this; or maybe more than one. Who knows? … You can see how this can get ridiculous pretty quickly. def authorized_user?(user) do year_born = user[:dob][:year] if is_integer(year_born) && year_born != nil do if (current_year() - year_born) >= 18 do true else false end else year_born = year_born |> String.to_integer() if is_integer(year_born) do (current_year() - year_born) >= 18 else {:error, "invalid dob"} end end end How do we use some of the tools built into Elixir to solve this problem in a more readable way? I wrote this and I’m having a hard time keeping track of everything, and I don’t like that. Instead, what I’ll do is refactor this using some pattern matching, and multi-clause functions. def authorized_user?(%{dob: nil} = _user), do: false def authorized_user?(%{dob: %{year: nil}} = _user), do: false def authorized_user?(%{dob: %{year: year_born}} = user) when is_integer(year_born) do (current_year() - year_born) >= 18 end def authorized_user?(%{dob: %{year: year_born}} = user) when is_binary(year_born) do {:error, "invalid dob"} end Believe it or not, the code above solves our problem! Let’s break it down. # This is what you can do with MultiClause Functions # You can have multiple functions with the same name that behave differently # based on the parameters provided. # This Function Is Triggered If dob is nil, and returns false def authorized_user?(%{dob: nil} = _user), do: false # This Function Is Triggered When The Year Inside our dob map is nil, and returns false. def authorized_user?(%{dob: %{year: nil}} = _user), do: false # This Function Is Triggered When A Year Is Present And It Happens To Be An Integer # We Use Pattern Matching To Be Able To Pull Out The Value We Need Inside Our Function Header def authorized_user?(%{dob: %{year: year_born}} = user) when is_integer(year_born) do (current_year() - year_born) >= 18 end # This Function Is Triggered When Year Is A String And Raises An Error def authorized_user?(%{dob: %{year: year_born}} = user) when is_binary(year_born) do {:error, "invalid dob"} end Now we can take a user, and when we pass it into authorized_user() – and depending on the user attributes – certain functions will run and others won’t. This is a pretty common pattern in Elixir and Phoenix. We cut our lines of code in half. I think it’s easier to read and reason about. Especially when you understand the basics of pattern matching and multi-clause functions.
https://sweetcode.io/pattern-based-design-elixir/
CC-MAIN-2020-50
refinedweb
1,238
79.9
NAME stpcpy - copy a string returning a pointer to its end SYNOPSIS #include <string.h> char *stpcpy(char *dest, const char *src); Feature Test Macro Requirements for glibc (see feature_test_macros(7)): stpcpy(): Since glibc 2.10: _XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L Before glibc 2.10: _GNU_SOURCE DESCRIPTION The stpcpy() function copies the string pointed to by src (including the terminating null byte ('\0')). CONFORMING TO This function was added to POSIX.1-2008. Before that, it was not part of the C or POSIX.1 standards, nor customary on UNIX systems, but was not a GNU invention either. Perhaps it came from MS-DOS.\n", buffer); } BUGS This function may overrun the buffer dest. SEE ALSO bcopy(3), memccpy(3), memcpy(3), memmove(3), stpncpy(3), strcpy(3), string(3), wcpcpy(3) COLOPHON This page is part of release 3.35 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at.
http://manpages.ubuntu.com/manpages/precise/man3/stpcpy.3.html
CC-MAIN-2014-42
refinedweb
160
76.52
I am undertaking the "Django Templates" section of the django girls tutorial and I cannot get my local server to display posts from the database. 1) The QuerySet isn't loading at all in the HTML file. I followed the steps to import the Post model into views.py and add the QuerySet in the posts variable (the previous part of the tutorial). When I tried putting {{ posts }} in the HTML file (post_list.html), nothing appears in the QuerySet that loads on the page. This is all on my local machine for now but I want it to work here before I push to pythonanywhere. When I query the database on my venv it returns the data I was expecting (dates, titles, etc.) however when I try and pull from database all I get is the web title appear on the page. Not sure what is going wrong, everyone seems to have issues forgetting that the database isn't committing but I haven't reached that point yet! :) I have included the code so far (it matches the tutorial as I copy pasted to error check) and I am stumped. Like I say no data is displayed (posts) and only the title "Web App" appears at the top of the page. Help! :D post_list.html <html> <head> <title>Web app</title> </head> <body> <div> <h1><a href="/">Web app</a></h1> </div> {% for post in posts %} <div> <p>published: {{ post.published_date }}</p> <h1><a href="/">{{ post.title }}</a></h1> <p>{{ post.text|linebreaksbr }}</p> </div> {% endfor %} </body> </html> view.py from django.shortcuts import render from django.utils import timezone from .models import Post def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/post_list.html', {'posts': posts})
https://www.pythonanywhere.com/forums/topic/12827/
CC-MAIN-2018-43
refinedweb
294
76.32
Memory Usage Constantly RisingPosted Thursday, 21 June, 2012 - 16:58 by daleluck Description I was in the middle of my other project and noticed the large amount of memory that my program had taken up. Since it was just a test, I decided I'd start again and just port over the pathfinding library whilst redesigning exactly how the system works - but then I noticed that the memory allocation of the program starts at 17000k and constantly rises as the program runs, even with just the below piece of code. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using OpenTK; using OpenTK.Input; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; namespace Program { class Program { // Game Window Details public static GameWindow MainGame; public static int WindowWidth = 800, WindowHeight = 600; public static double WindowFPS = 30.0; static void Main(string[] args) { // sets up the window for 2D, disallowing manually resizing it MainGame = new GameWindow(WindowWidth, WindowHeight, GraphicsMode.Default, "Test Window"); MainGame.WindowBorder = WindowBorder.Fixed; GL.MatrixMode(MatrixMode.Projection); GL.LoadIdentity(); GL.Ortho(0, WindowWidth, WindowHeight, 0, 0, 5); GL.MatrixMode(MatrixMode.Modelview); // sets up the different functions MainGame.RenderFrame += OnRenderFrame; // runs the window at 60.0fps MainGame.Run(WindowFPS); } static void OnRenderFrame(object sender, FrameEventArgs e) { GL.ClearColor(Color.Black); GL.Clear(ClearBufferMask.ColorBufferBit); MainGame.SwapBuffers(); } } } All it does is clear the background to be black, but the memory it takes up is constantly rising - there's nothing else to the program, just setting up the window and then making the background black. I really want to know why this is happening and how can sort it out. #1 Be sure to also test a release build with no debugger attached. I don't have the time to test it out myself atm. But I would be interested in the results. Also I think that when the memory reaches 1mb the garbage collector might clean up the 'leaks' But as I said, I haven't tested it yet :-) #2 Tested it in the release build, same problem arises. Also, what do you mean by it cleaning up once a megabyte of memory was reached? As far as I know, the amount of memory stands for how many kilobytes the program is using, and with this program starting off at 16000k memory usage I left it for a bit and checked back and it had risen to 25000k with no signs of slowing down or removing memory. I also tested it with the 'quick start' sample and found the exact same issue, so I'm fairly sure it's not something I've written doing something wrong. I never noticed this before because I never opened my program for prolonged amounts of time, but since I'm making a game where the expectation is the user WILL have it open for so long it's kind of an issue I need sorting out quickly. #3 What I meant was that maybe the program is generating garbage. And if I remember correcly the garabage collector only starts collecting once 1mb of memory is allocated ( I could be wrong here ). So if its garabage it's not really a leak, just lazy cleanup by GC. But this might still be problem depending on how much garbage is generated each frame, ideally it shoudn't generate any. #4 I'm not sure how I'd go about lowering the amount of garbage that it makes. It happens in the example project too, so I'm sure I've not done anything wrong. I'll carry on with writing the program and get around to the memory cleanup once a solution has arisen, or hopefully, as you've suggested might happen, the program will just sort itself out at some point. #5 Cant confirm. This code (net) takes 35MB memory but it didnt go up. #6 Well that's odd, that code with nothing else attached uses up just over 15000k when it's executed and then steadily rises every few seconds (odd that it isn't doing it every couple of frames) with mine. I'm not sure what to do about this now if it's just a problem that I'm having. #8 I cannot reproduce this on Windows, Linux or Mac OS X using the native or the SDL2 backend. This may be a driver issue. If you can still reproduce this using OpenTK 1.1 beta4, please file a bug report at Make sure to include the following information:
http://www.opentk.com/node/3037
CC-MAIN-2015-27
refinedweb
754
62.78
Design By Contract or DBC defines that methods should have defined input and output verifications. Therefore, you can be sure you are always working with a usable set of data in all methods and everything is behaving as expected. If not, exceptions or errors should be returned and handled from the methods. To read more on DBC read the wikipedia page here. In our example here, we are working with input parameters that may possibly be null. As a result a NullReferenceException would be thrown from this method because we never verify that we have an instance. During the end of the method, we don’t ensure that we are returning a valid decimal to the consumer of this method and may introduce methods elsewhere. 1: public class CashRegister 2: { 3: public decimal TotalOrder(IEnumerable<Product> products, Customer customer) 4: { 5: decimal orderTotal = products.Sum(product => product.Price); 6: 7: customer.Balance += orderTotal; 8: 9: return orderTotal; 10: } 11: } The changes we can make here to introduce DBC checks is pretty easy. First we will assert that we don’t have a null customer, check that we have at least one product to total. Before we return the order total we will ensure that we have a valid amount for the order total. If any of these checks fail in this example we should throw targeted exceptions that detail exactly what happened and fail gracefully rather than throw an obscure NullReferenceException. It seems as if there is some DBC framework methods and exceptions in the Microsoft.Contracts namespace that was introduced with .net framework 3.5. I personally haven’t played with these yet, but they may be worth looking at. This is the only thing I could find on msdn about the namespace. 1: public class CashRegister 2: { 3: public decimal TotalOrder(IEnumerable<Product> products, Customer customer) 4: { 5: if (customer == null) 6: throw new ArgumentNullException("customer", "Customer cannot be null"); 7: if (products.Count() == 0) 8: throw new ArgumentException("Must have at least one product to total", "products"); 9: 10: decimal orderTotal = products.Sum(product => product.Price); 11: 12: customer.Balance += orderTotal; 13: 14: if (orderTotal == 0) 15: throw new ArgumentOutOfRangeException("orderTotal", "Order Total should not be zero"); 16: 17: return orderTotal; 18: } 19: } It does add more code to the method for validation checks and you can go overboard with DBC, but I think in most scenarios it is a worthwhile endeavor to catch sticky situations. It really stinks to chase after a NullReferenceException without detailed information. This is part of the 31 Days of Refactoring series. For a full list of Refactorings please see the original introductory post. Post Footer automatically generated by Add Post Footer Plugin for wordpress.
http://lostechies.com/seanchambers/2009/08/25/refactoring-day-25-introduce-design-by-contract-checks/
CC-MAIN-2013-48
refinedweb
453
54.63
Setting up & First React App Series: React 101 for dummies Hey people! 👋 Guess who's back with another blog? Me! Your favorite blogger of all time 😁 In this blog, we will be getting comfortable with the making of React apps. Let's get started! ReactJs Environment Setup To build react apps left and right, there are a few things that you need to do first. Firstly, You need to install NPM and Nodejs. You can download Nodejs from here. Secondly, you need to install create-react-app If you've previously installed create-react-appglobally via npm install -g create-react-app, I recommend you uninstall the package using npm uninstall -g create-react-appor yarn global remove create-react-appto ensure that npx always uses the latest version. The setup and creating the app go hand in hand so, moving on to the next section! Create your first React App To create your react application, Follow the steps below: Create a directory that will hold your React app and open it in your preferred IDE (I use VS Code - download from here, but that's just my preference. you can use any IDE you like.) Open your terminal and navigate to the directory you created for the React App, and run the following commands. npx create-react-app app-name Here, essentially what you're doing is downloading all the dependencies which will help run your react app. Here comes the fun part! When the above command is run successfully, you will notice that a folder has been created by your app-name, that folder will contain everything related to your app. - Now all you have to do is navigate into that directory using cd app-name& enter the following command to run the app. npm start This will automatically start a new browser window with your app running at localhost:3000, if that did not happen you can directly type localhost:3000 in your browser. Congrats, you're done with the setup of your react app! Modify your App It's time to get creative!✨ So far we have created a React app running perfectly, but how to make changes in the app? In your project directory, you will find another folder called src, and open App.js file which will have the code for whatever is running on localhost:3000 Clear out everything inside the <div className="App"> </div> & now what you see is a blank canvas. Go nuts and enjoy yourself. The boring form of this should look something like this: I just added an h1 tag inside the empty div tag (basic HTML syntax) import './App.css'; function App() { return ( <div className="App"> <h1> Hello World </h1> </div> ); } export default App; If you feel that you might be a little lost, do check out my previous blog: Getting Started with ReactJS Also, Congratulations! You just created your first React App! Woohoo🙌 I will explain more about components and basic React concepts in the coming blogs, so stay tuned🙂 ~ That's it for this blog, I hope you followed along because more blogs like this will be coming your way very soon! (Feedback Appreciated) Till then, You got this✨ -V
https://varshitha.hashnode.dev/setting-up-and-first-react-app
CC-MAIN-2021-39
refinedweb
534
61.67
- I dunno. I've heard a story from a classmate about a consultant brought in by her coop company. The dude basically did the same thing, worked for 6 months and said everything was coming along great. Then on the day of the deadline, it was discovered that all he had was a namespace and a function header. He cried during the meeting and was fired. Admin All women developers I've met are lousy developers. Some shouldn't even be called developers, why? Because they can't even write a Hello World app. I'm being serious here, there was a "colleague" who couldn't even write 1 line of code, whenever she received a programming task, she simply delegated the task to his boyfriend (lead developer). There were 2 other women who used that same technique, and there were 2 other women who wrote mediocre and buggy code. I'm not saying my code was perfect... but at least (back then) I at least knew how to use multi-threading & concurrency, basic OO principles, and properly use & read framework APIs. Admin This is so funny. Even though there were so many comments from people saying they have similar stories from incompetent male programmers, people still comment about how her gender is related to her incompetence: Did you morons know that the first programmer ever was a woman? Our profession might not even exist if it wasn't for Ada Lovelace. Or Grace Hopper, who wrote the first compiler. Just because there are some incompetent female programmers, doesn't mean all of us are. (relevant:) The problem is that some of these incompetent women get hired just because of their gender, and create a bad reputation for all of us. Admin Blame where due. I'd say they got hired more due to the hiring manager's gender. I have worked with some real stars that were women, and some that were ho-hum. I think that this site proves it's not just women that get hired inappropriately, but as a minority, they are under a magnifying glass. Must be tough - props to the ladies! Admin I've worked with lousy programmers from all creeds. I've worked with female programmers who aren't too bad at it. Such females are exceptionally rare. Female programmers of any skill level at all are incredibly rare. I don't blame this one. Have you ever worked with enterprise Java? You will spend more time reading than anything else. It takes years before you can actually do anything. Admin I know this is years after the original comment, but I just need to note in passing it's definitely NOT far-fetched. When I was in college, one of our class projects required us to work in teams of 3 or 4. Two of us had signficant experience programming (I had programmed professionally two years before going to college) and we agreed to do the project design. The other two wanted more experience programming, so it looked like a good combination. We fed design specs to the other two who kept giving us positive feedback on how well it was going. Finally, 2 days before the semester project is due, they tell us not a line of code had been written. They didn't know where to begin and were too embarrassed to tell us. At least it had a happy ending. I got alone with the other student and said "I'll program, you document." Despite it being finals week, we managed to grind the project out in a day. Best thing: when we turned in our project, we were allowed to anonymously write down the percent that we thought the others in the group contributed to the project. Win! Admin This reminds me another one: If idiots can fly, then I'm working in an airport. Admin the woman who has contributed the most to software development is Barbara Liskov after whom is named the "Liskov Subsitution Principle", which means that when using the "inheritance" pattern, you should be able to freely substitute the derived class with the base class at the point of calling, and not have to know what the underlying class actually is. This was quoted in 1987 and had no specific programming language in mind as far as I am aware. With regards to this particular WTF, the sad situation of a programmer is often being left alone for long periods to "get on with it". Pair-programming would never have let this happen. When you have a pair programming, you push each other to work, and don't waste time at work doing other stuff so much, like browsing TheDailyWTF.com. The WTF though is that Paula could leave with this work experience on her CV/resume and the company could not give a bad reference. She could say, truthfully, that she spent so many months in this company working on such and such a project. Of course had she been clever enough she would have either found some open-source that did what she wanted, or found a website somewhere to get the code (give me the codez..) possibly in return for a few nice "reputation points". Oh well, I have work to do, can't spend too long on here... Admin And every year, we make a pilgrimage back to this clbuttic, the paragon of TDWTF. Admin Admin And 2014 is here, thanks to today's t-shirt giveaway. Nice job on the artwork, Mark. Admin Oh hey, now that Discourse is gone we can comment on these old articles again. Addendum 2016-03-25 19:59: Paula was pretty buggy on Discourse anyway. Admin Is this the best classic? FILE_NOT_FOUND (for the record, "Special Delivery" is the GOAT) Admin It's possible that "brillant" isn't misspelled - it might be French. I mean, she obviously needs all the benefit of the doubt we can give her, here. Admin Not worth the time/money. She has probably spent the money/lawyers might cost more, in the end, than they paid her. Most likely explanation - nobody like to admit that they were stupid Admin Smart people who think they can program are even worse than stupid people. Stupid people at least only make stupid mistakes. Admin I once worked with a "programmer" who was asked create a database and forms in access, as a bug tracking system to track his work on other projects. Predictably, the access database he created was so buggy it was unusable. I've never seen anything so buggy. Admin The real WTF is the number of people who doubt this could be true. I've been in this industry for 40 years now. I've been coding in Java for about 20 years. I have a friend who was hired by a government agency as a Java programmer. He had no Java programming experience whatsoever. He was an HTML guy who read a book. He even told them that. They hired him anyway then complained about his lack of skill. Admin Thats why a daily status update, code review and JIRA helps in tackling with dodgy contractors. Admin Do not abandon logic and reason; one should not multiply externalities unnecessarily. Look for common factors. What individual worked at all those places? What policies did those places have that attracted that individual? And so forth.
https://thedailywtf.com/articles/comments/The_Brillant_Paula_Bean/5
CC-MAIN-2019-18
refinedweb
1,236
73.37
Transpose of a directed graph G is another directed graph on the same set of vertices with all of the edges reversed compared to the orientation of the corresponding edges in G. That is, if G contains an edge (u, v) then the converse/transpose/reverse of G contains an edge (v, u) and vice versa. Given a graph (represented as adjacency list), we need to find another graph which is the transpose of the given graph. Example: Input : figure (i) is the input graph. Output : figure (ii) is the transpose graph of the given graph. We traverse the adjacency list and as we find a vertex v in the adjacency list of vertex u which indicates an edge from u to v in main graph, we just add an edge from v to u in the transpose graph i.e. add u in the adjacency list of vertex v of the new graph. Thus traversing lists of all vertices of main graph we can get the transpose graph. Thus the total time complexity of the algorithm is O(V+E) where V is number of vertices of graph and E is the number of edges of the graph. Note : It is simple to get the transpose of a graph which is stored in adjacency matrix format, you just need to get the transpose of that matrix. C++ Python3 # Python3 program to find transpose of a graph. # function to add an edge from vertex # source to vertex dest def addEdge(adj, src, dest): adj[src].append(dest) # function to pradjacency list # of a graph def displayGraph(adj, v): for i in range(v): print(i, “–> “, end = “”) for j in range(len(adj[i])): print(adj[i][j], end = ” “) print() # function to get Transpose of a graph # taking adjacency list of given graph # and that of Transpose graph def transposeGraph(adj, transpose, v): # traverse the adjacency list of given # graph and for each edge (u, v) add # an edge (v, u) in the transpose graph’s # adjacency list for i in range(v): for j in range(len(adj[i])): addEdge(transpose, adj[i][j], i) # Driver Code if __name__ == ‘__main__’: v = 5 adj = [[] for i in range(v)] addEdge(adj, 0, 1) addEdge(adj, 0, 4) addEdge(adj, 0, 3) addEdge(adj, 2, 0) addEdge(adj, 3, 2) addEdge(adj, 4, 1) addEdge(adj, 4, 3) # Finding transpose of graph represented # by adjacency list adj[] transpose = [[]for i in range(v)] transposeGraph(adj, transpose, v) # displaying adjacency list of # transpose graph i.e. b displayGraph(transpose, v) # This code is contributed by PranchalK 0--> 2 1--> 0 4 2--> 3 3--> 0 4 4--> 0
https://tutorialspoint.dev/data-structure/graph-data-structure/transpose-graph
CC-MAIN-2020-16
refinedweb
445
58.96
Hey guys, So I have another problem. I need to check out a file from PVCS from an ASP.NET webpage. In order to do so I spawn a process that calls a batch file which sets some environment variables and then calls the pvcs command get.exe to get the file. This all works great when I run it on my local machine, but as soon as I deploy to the server all hell breaks lose. The website impersonates the main user, this happens in the web.config (still not sure if relevant). After trial and error, I narrowed down the problem to communication with shared drives. PVCS drive is mapped in the server. So I made a small batch script that only does a cd to a directory on this shared drive and it failed. Code is simply "cd Z:/work/". Google gave some answers and more questions still. Apparently impersonation and shared drives simply do not work. But I'm not certain if that pertains to spawned process using C# Process class. Though, given that the webpage works perfectly in my machine without impersonation, this might have something to do with it. C# spawned processes have limited permissions, but I don't think this is the problem since my code is failing in doing a simple cd Z:\work\. So I created a console app which does the check out (same code as the webpage) and it worked in the web server without a problem. The problem only occurs when I spawned the process from the webpage in the webserver. I made some dummy code to test. I even tried to call the console app from the website, but that still doesn't work. public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnCheckout_Click(object sender, EventArgs e) { Command cmd = new Command(@"cmd", @"/c testpath.bat"); cmd.execute(); lblError.Text = cmd.stderr; lblOutput.Text = cmd.stdout; } } public class Command { // Private members private Process process; private int timeout; // Public members public string stderr { get; private set; } public string stdout { get; private set; } public string exception { get; private set; } public bool done { get; private set; } public int exitLevel { get; private set; } /// <summary> /// Construct a Command object that will be executed in a Windows environment. /// </summary> /// <param name="args">the command to execute in command prompt</param> /// <param name="timeout">This is optional and consists of the time in milliseconds to wait for the command to finish. Default is 10 seconds.</param> public Command(string exec, string args, string workingDir="", int timeout = 5000) { this.timeout = timeout; this.exception = ""; process = new Process(); if (!string.IsNullOrEmpty(workingDir)) process.StartInfo.WorkingDirectory = workingDir; process.StartInfo.FileName = exec; process.StartInfo.Arguments = args; process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.RedirectStandardOutput = true; process.OutputDataReceived += process_OutputDataReceived; } void process_OutputDataReceived(object sender, DataReceivedEventArgs e) { if (!string.IsNullOrEmpty(e.Data)) { stdout = e.Data; } } public void execute() { try { process.Start(); process.BeginOutputReadLine(); // Note that the following three lines in any stderr = process.StandardError.ReadToEnd(); // other order will deadlock. process.WaitForExit(timeout); } catch (Exception e) { exception = e.Message; Debug.WriteLine(e.Message + "\n" + e.StackTrace); } Thread.Sleep(1000); } } Does anybody have any clue what my problem is? Thread Closed This thread is kinda stale and has been closed but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.
http://channel9.msdn.com/Forums/Coffeehouse/ASPNET-and-Network-Drives-Help
CC-MAIN-2015-06
refinedweb
575
59.7
Tomorrow, June 30th, is the release date for my book titled “Game Programming with Silverlight”. Writing this book was a great experience as it was the first book I have ever written. It was extremely time consuming mostly because it was a learning experience but I am glad I did it. Also, I apologize for the lack of Silverlight tips these days! Finishing the book was my top priority but I am looking forward to getting back to adding Silverlight tips on a regular basis. The book itself covers a lot of what I discuss here in this tips blog but with more detail. Here is a quick outline of what I covered in the book: Chapter 1: Silverlight 101. I start the book off by giving a thorough introduction into Silverlight, XAML and Silverlight controls. Chapter 2: Getting Started. This chapter covers using Visual Studio 2008 and 2010 for creating Silverlight projects. Chapter 3: What’s new with Silverlight 3. I cover each and every new feature to Silverlight 3 that could pertain to game development. Chapter 4: Silverlight Tips and Tricks. Mostly tips I covered here in my blog. Chapter 5: Creating the World. Covers the map editor I created that allows you to create maps for your games. Also, I discuss resources where you can obtain game art from. Chapter 6: Object Manager. I discuss how to use a web service to load objects from. Also, I cover the different types of objects you might have in a multi-player adventure type game. Chapter 7: Animation. This chapter discusses the variety of ways to perform animation in Silverlight. Chapter 8: The Client UI. I discuss the ways you can lay out your client UI in your game. Chapter 9: Network Support: I discuss how to make your game multi-player using socket programming. Chapter 10: Extras: In this final chapter I discuss a variety of topics such as how scrolling maps smoothly, player movement, chat boxes and reflections. Let me know if you have any suggestions or ideas on what you would want to see in a future book (Game Programming with Silverlight 4 for example). Thanks! --Mike Animation Easing allows for you to apply built in animation functions to your Silverlight controls. The result is a variety of animation effects that make your controls move in a more realistic way. For example, you can add springiness to your controls, set how many times you want it to bounce when it hits a destination point, etc. The functions that you can set include: Each of these has can have an EasingMode set to one of the following options: In addition, you can set the Duration, From and To values for the animation. The best way to see what each of these do is to simply to try them out via this demo. Try modifying any properties that are specifically unique to the animation. The animation functions listed above are applied directly to a storyboard that is then used to target and animate a given control. The XAML I use for each ball is as follows: <UserControl x:Class="BouncingBall.Ball" xmlns="" xmlns: <Canvas> <Canvas.Resources> <Storyboard x: <DoubleAnimation x:Name="BallDA" Completed="DoubleAnimation_Completed" From="0" To="1000" Duration="0:0:05" Storyboard. <DoubleAnimation.EasingFunction> <BounceEase x:</BounceEase> </DoubleAnimation.EasingFunction> </DoubleAnimation> </Storyboard> </Canvas.Resources> <Image x:</Image> </Canvas> </UserControl> Thanks, --Mike From within VS you can specify which Internet browser you want launched when running your Silverlight application. Your default system browser is not affected by this setting. To make this change right click on your startup web page and choose Browse with… from the context menu. This will bring up the following dialog. From within this dialog select the browser you want to use and choose “Set as Default”. Close the dialog when you are done. With the release of Silverlight 3 Beta 1 GPU (Graphics Processing Unit) acceleration (or hardware acceleration) is now available. The GPU is a processor attached to your graphics card that is generally used for calculating floating point operations. In addition, it contains a number of graphics primitives that when used will save you a lot of CPU time. By default this option is disabled and to use it you must enable it both on your Silverlight control/plug-in as well as any of the controls you want to leverage it. To enable it on your Silverlight control open your web page that hosts the Silverlight control. For HTML modify the Silverlight control to include the following param: <param name="EnableGPUAcceleration" value="true" /> <param name="EnableGPUAcceleration" value="true" /> For ASPX add the following attribute: <asp:Silverlight <asp:Silverlight Now, to apply it to a control you will need to add CacheMode="BitmapCache” to the control. The following example shows you how to add it to an Image control: <Image CacheMode="BitmapCache" Source="MyImage.png"></Image> <Image CacheMode="BitmapCache" Source="MyImage.png"></Image> Currently BitmapCache is the only option. What this does is it causes visual elements (and all their children) to be cached as bitmaps after they have already been rendered. Once cached, your application can bypass the expensive rendering phase for the cached elements and just display them. If you want to test out what is being cached in your application add the following attribute to your Silverlight control: <asp:Silverlight <asp:Silverlight Uncached objects will appear tinted where as cached objects will not be tinted. This feature is supported on: This feature should be used when the following are occurring to your control: Of the course of the last year I have been collecting links to some really good Silverlight tutorial blogs that I thought I would share with you. These are active blogs, frequently updated, that are specifically oriented to teaching Silverlight development. That is, they are all about showing you how things are done and giving you the source code you need to do it yourself. If I have missed any good links post a comment and I will add it! Silverlight tutorial sites in alphabetical order: Also, here is a great Silverlight Blog summary page: Thank you, --Mike When calculating the positions of objects such as Images make certain to use integer values not floating point values. For example, take a look at this code that centers a map around a given position: private void CenterMap(double windowWidth, double windowHeight) { if (null != _parentCanvas) { int leftPos = (int) ((windowWidth / 2) - _currentX); int topPos = (int) ((windowHeight / 2) - _currentY); _parentCanvas.SetValue(Canvas.LeftProperty, (double) leftPos); _parentCanvas.SetValue(Canvas.TopProperty, (double)topPos); } } Notice I converted the map layout position left and top to be integers. The following screen shot shows an example where double values were used instead of integers. The result is the images are slightly blurred and lines (or seams) appear between the image tiles. Compare the screenshot above that used doubles with the shot below that used integers. In the screen shot below the images are crisp and the terrain tiles have no seams or lines. Thank you, --Mike Snow Subscribe in a reader By default Silverlight will not download an image more than once if is contained within the image cache. That is, as long as the URI remains the same it will reference the image from the cache. So what if the image changed on the server even though it has the same URI? Your application can force an update by setting the property IgnoreImageCache to true. Example: Image img = new Image(); Uri uri = new Uri("", UriKind.Absolute); BitmapImage bi = new System.Windows.Media.Imaging.BitmapImage(uri); bi.CreateOptions = BitmapCreateOptions.IgnoreImageCache; img.Source = bi; LayoutRoot.Children.Add(img); Unless you have had your head under a rock you probably have heard Silverlight 3 Beta 1 has been released! If you haven’t already, please install it from This release comes packed with some of the greatest features to date. If you are a game developer, you will be happy to hear the following features below are now included in Silverlight 3. I will be writing detailed blogs on a number of these to help you apply them to your application. Image Opened In Silverlight 2 it was difficult to accurately determine when a image was completely opened. This case was often needed to determine the actual dimensions of the image. The problem occurred because the DownloadProgress is fired at 100% before the image is fully decoded. The solve this, a new event called ImageOpened is available. Now you can be guaranteed to get the right size for the image. Example: private void LoadImage(string fileName) Image img = new Image(); Uri uri = new Uri(fileName, UriKind.Relative); img.Source = new System.Windows.Media.Imaging.BitmapImage(uri); img.ImageOpened += new EventHandler<RoutedEventArgs>(Image_ImageOpened); void Image_ImageOpened(object sender, RoutedEventArgs e) Image img = (Image)sender; BitmapImage bi = (BitmapImage)img.Source; double width = bi.PixelWidth; double height = bi.PixelWidth != _radius) XAP Compression Optimization were made to drastically reduce the size of the XAP file. You can expect the XAP file size to now be on par (if not better) than Windows zipping. Games often come packed with a lot of content so obviously the smaller your XAP the faster your customers will be able to download your game. Perspective 3D Perspective 3D transforms can now be applied to Silverlight controls via the PlaneProjection property. This allows you to rotate a 2D control in a 3D plane. Example code that shows how to do this: <Image Source="Man.png"> <Image.Projection> <PlaneProjection RotationX="45"></PlaneProjection> </Image.Projection> </Image> Pixel Shaders Pixel shaders allow you to apply effects to controls such as images. There are two built in effects available by default: Drop Shadow and Blur. In addition, you can write and apply your own custom effects. The following images show the result of applying pixel shader effects to them. Example code to accomplish this through a built in shader: <Image Source="dwarf.jpg"> <Image.Effect> <BlurEffect></BlurEffect> </Image.Effect> Binding You can now bind controls to properties of each other. For example, the Text of a TextBlock can bind to the Text of a TextBox. Or, a TextBox Text can bind to the Value of Slider. Example: <StackPanel> <TextBox x:</TextBox> <TextBlock Text="{Binding Text, ElementName=UserText}"></TextBlock> </StackPanel> Whatever someone types in the TextBox is automatically reflected in the TextBlock. Bitmap API Bitmap APIs are now available through a class called WriteableBitmap. This method takes as parameters the surface width and height and the pixel format. Example code: WriteableBitmap wb = new WriteableBitmap(0, 0, PixelFormats.Bgr32); wb.Render(img, new ScaleTransform()); wb.Lock(); // walk through WriteableBitmap[] wb.Invalidate(); wb.Unlock(); Hardware Acceleration Silverlight now makes use of the GPU (Graphics Processing Unit) for rendering which frees up CPU time for other tasks. The GPU typically sits on a video card. It is a dedicated graphics processing device that is used for a variety of tasks such as calculating floating point operations. Animated Text Performance Improvements A property called TextRenderingMode now allows you specify RenderForAnimation. This turns off optimizations that could directly affect text animation such as scaling, rotating, etc. The result is a smother, more peformant animation of text. Example on how to set this property: RenderOptions.SetTextRenderingMode(MyTextbox, TextRenderingMode.RenderForAnimation); Network Monitoring API There are now API’s that allow you to monitor the status of the network. To see if a network is available you can call: bool isConnected = NetworkInterface.GetIsNetworkAvailable(); You can also hook up an event that will fire when the network status changes: NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged); To access these methods you will need to reference the namespace System.Net.NetworkInformation; SaveFileDialog Finally we are able to save files in Silverlight! Calling this method will invoke a dialog that will allow you to specify a file to save to. The method returns a pointer to a Stream that you can than write to. Example code: SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "map files (*.xml)|*.xml|All files (*.*)|*.*"; sfd.ShowDialog(); System.IO.Stream stream = sfd.OpenFile(); // Save your data here stream.Flush(); stream.Close(); Make certain to flush and close the stream or the file will not be created. CaretBrush The CaretBrush is useful because you can now change the appearance of the caret. This was a problem if, for example, you wanted to have a background color of a textbox set to back. The cursor was also black so it would not appear. Example on how to set it: <TextBox Foreground="White" Background="Black" Width="200" Text="Hello"> <TextBox.CaretBrush> <SolidColorBrush Color="White"></SolidColorBrush> </TextBox.CaretBrush> </TextBox> Resulting Screenshot (notice the white caret): Local Connection This feature allows two separate Silverlight applications to communicate with each other on the client side without the need to roundtrip to the server. Implementing this is fairly straight forward. Start by creating two separate Silverlight applications. To one, add this code that will listen for a message: LocalMessageReceiver receiver = new LocalMessageReceiver("R2D2"); receiver.MessageReceived += new EventHandler<MessageReceivedEventArgs>(receiver_MessageReceived); receiver.Listen(); You will need to reference System.Windows.Messaging to make these calls. The constructor for LocalMessageReceiver takes any unique identifier. To the other application add this code that will send a message to the first Silverlight application: LocalMessageSender sender = new LocalMessageSender("R2D2"); sender.SendCompleted += new EventHandler<SendCompletedEventArgs>(sender_SendCompleted); sender.SendAsync("Hello World!"); Navigation Navigation is now supported in Silverlight. This allows you to do things like hook up navigation in your Silverlight application to the Back and Forward buttons of your browser. A new template called “Silverlight Navigation Application” is available that demonstrates how to do this. Essentially to accomplish this you will need to put your main page in a <navigation:Frame>. You add history by this call: this.Frame.Navigate(new Uri(currentPage, UriKind.Relative)); Then, when the back and forward buttons of your browse are clicked this frame object will intercept them and display the correct page. System Colors You can now get access to a users settings for their System Colors. These are available through System.Windows.SystemColors.*. Example: System.Windows.SystemColors.ActiveBorderColor. This will allow ou present a contrast that matches a user's settings. Other Thanks, --Mike Snow I recently had the opportunity to try out the controls from ComponentArt.com. I was very impressed with their ease of use, professional design and overall quality. Also, their staff are very prompt to responding to questions which made my developer experience a lot easier. Overall, they are very friendly and easy to work with. ComponentArt currently has a Beta 2 release available here; I highly recommend you check it out! The Silverlight controls they currently support include: Let’s take a look at the Toolbar, Menu, Data Grid and Tree View controls. Toolbar The following screenshots shows you what the toolbar looks like in each of the available themes. These themes can be applied to all controls. For the toolbar, you can enable/disable items, change orientation from horizontal to vertical, and more. Also, you can have a seperate icon represented for enabled, disabled and hover. Black Ice Arctic White Office 2003 Office 2007 Windows 7. Example code needed to create a toolbar: <ComponentArt:ToolBar <ComponentArt:ToolBarItem</ComponentArt:ToolBarItem> <ComponentArt:ToolBarItem</ComponentArt:ToolBarItem> <ComponentArt:ToolBarItem</ComponentArt:ToolBarItem> <ComponentArt:ToolBarItem</ComponentArt:ToolBarItem> <ComponentArt:ToolBarItem</ComponentArt:ToolBarItem> <ComponentArt:ToolBarItem</ComponentArt:ToolBarItem> </ComponentArt:ToolBar> The following screenshot shows an example menu in action. With menus you can change how they expand and collapse. You can make it so they instantly expand or you can send an interval for the rate of acceleration or deceleration. You can also set whether they expand when hovered or expand when clicked. There are a lot more settings that make the menu extremely customizable to your needs. Example code needed to create a menu: <ComponentArt:Menu <ComponentArt:MenuItem <ComponentArt:MenuItem x: <ComponentArt:MenuItem x: <ComponentArt:MenuItem x: <ComponentArt:MenuItem </ComponentArt:MenuItem> <ComponentArt:MenuItem <ComponentArt:MenuItem x: <ComponentArt:MenuItem x: <ComponentArt:MenuItem x: <ComponentArt:MenuItem <ComponentArt:MenuItem <ComponentArt:MenuItem <ComponentArt:MenuItem </ComponentArt:Menu> Data Grid The data grid is probably one of the more impressive controls. Columns can be resized and re-ordered. Check out the screen shot here: You can also group rows by area: TreeView The following screen shot shows the tree view in action. The tree view supports icons, drag/drop, node editing, tree view lines styles (none, solid, dotted), tree view line colors, multiple selection, enabling and disabling nodes and more. Given a tree view control: <ComponentArt:TreeView x:</ComponentArt:TreeView> The following snippet of code shows you how easy it is to add nodes to the tree: public void CreateRootNode() TreeViewNode rootNode = new TreeViewNode(); rootNode.Header = "Mailbox"; TreeViewObjects.Items.Add(rootNode); Any data you want to store with a node in the tree can be set in the TreeViewNode.Tag property. Based on Silverlight 3, this book walks you through how to create a multi-player online RPG in Silverlight. Included is a Map Editor written in Silverlight that allows you to create maps for your game. Map Editor Features include: Here is a screenshot of the Map Editor (in early development): Let me know if you have any suggestions or comments about what you are hoping to see out of the book. Thank you, --Mike I recently stumbled across a cool tool by EnvyGames that allows you to generate sprites from 3D Models and their animation files. This tool, called SpriteWorks, is ideal for creating high quality sprite animations and one that I’ll be adding to my arsenal of game development tools for Silverlight. Since Silverlight does not yet support 3D models, sprite animation is really the only way to go. On a side note, EnvyGames is also working on a Silverlight Game Engine. For a complete list of features visit this link:. A beta is due out in a number of weeks. Once you have installed SpriteWorks make certain to have the following installed or the tool will not work: SpriteWorks currently supports importing the following 3D file formats: This tool is still undergoing improvements and fixes and I would recommend using it with Torque models for the best result. I will now give a quick overview on how the tool works. Start by launching SpriteWorks, Click the Browse button and choose your 3D model. In the left pane a preview of the model will appear. If your model doesn’t appear at first click the Camera tab and adjust the Camera Angles and Position until the model is centered in the preview window. Next click the Model tab and open up your Animation Sequence file. You can click the Play button to preview the animation. Finally, when you are ready click the Output tab. Enter the Output File Name, check the “Animate this model” checkbox and click the “Create Sprite Sheet” button. The tool will start taking a snapshot of each animation frame. The tool will go up to 52% and sit there for a minute or two before completing. Be patient here, the tool has not hung! The result is a PNG file that has each sequence of the animation in it: Once you have an image loaded how do you go back and get the original file name for the source file? This can be accomplished through the Uri property of the images Source. However, you must first typecast the images Source to be a BitmapImage. The Uri has a property called OriginalString that returns the full relative path to the image file. Example: public string GetImageSourceFile(Image img) { BitmapImage bi = (BitmapImage) img.Source; Uri uri = bi.UriSource; return uri.OriginalString If you ever run into this error when running your application you might be a bit perplexed by its encrypted meaning. Looking at the exceptions details you will see something like which really doesn’t help you very much:: The Silverlight Team is working to make improvements in error reporting. For now, to better understand what is causing these errors you should take a careful look at your XAML to see if something declared is missing or wrong. For example, say you have an event handler in your XAML that is not anywhere to be found in your code behind. Often I find myself removing an event handler I no longer want in my code behind but forgetting to remove it in my XAML as well. Now you know (if you didn’t already). When it comes to drawing shapes such as rectangles you are probably fully aware you can draw shapes specifying the color and thickness of the lines. This is done via the properties StrokeThickness and Stroke. For example, take a look at the rectangle drawn here: This rectangle is drawn with a line color of red set via the Stroke property. It’s thickness is set to “1” using the StrokeThickness property as seen here: <Rectangle Width="128" Height="128" StrokeThickness="1" Stroke="Red"></Rectangle> Did you also know you can change the shapes lines to be dotted/dashed while greatly configuring how they are drawn? This is done via the following two properties: Let’s take a brief look at each. StrokeDashArray The StrokeDashArray let’s you set the length of each dash and the distance between each dash. You can specify an array of these values where the first value is the length and the second value is the distance. It pair value in the array is applied and then repeated once the array you specified runs out. In this example, we are drawing a dash of length 2 with a distance of 5 between each dash: StrokeDashArray="1,5" The next example has two values that repeat non-stop where we have a length of 1, distance of 5 followed by length of 10, distance of 2. StrokeDashArray="1,5,10,2" StrokeDashCap StrokeDashCap affects how or in what shape the dots are drawn and it can be set to one of the following (each example is zoomed in to show detail): Thank you, --Mike Snow Subscribe in a reader In Tip of the Day #93 I showed you how to read XML via XmlReader. However, a better and simpler approach (IMHO) would be to use LINQ. Let’s start with the same XML file we used in Tip #93. <?xml version="1.0" encoding="utf-8" ?> <ImageTree> <Area name="grass"> <Image name="Normal Grass">grass1.png</Image> <Image name="Dry Grass">grass2.png</Image> <Image name="Mixed Grass">grass3.png</Image> <Image name="Long Grass">grass4.png</Image> </Area> <Area name="tile"> <Image name="Brick">brick.png</Image> <Image name="White Stone">stone.png</Image> <Image name="Cracked Stone">crackedstone.png</Image> <Image name="Black Brick">brick2.png</Image> </ImageTree> To use LINQ you will need to add a reference to System.Xml.Linq. To do this, right click on your References folder in your Silverlight application in the Solution Explorer and choose “Add Reference”. You will find this component on the .NET tab. In your source file add a using statement to reference System.Xml.Linq. The function below will create a tree view out of the XML file that is shown above. A few important notes on this code: private void CreateTree() TreeViewItem areaItem = null; TreeView tv = new TreeView(); TreeViewItem rootItem = new TreeViewItem(); rootItem.Header = "Images"; tv.Items.Add(rootItem); XDocument document = XDocument.Load("MapImages.xml"); foreach (XElement element in document.Descendants("Area")) areaItem = new TreeViewItem(); areaItem.Header = element.FirstAttribute.Value; rootItem.Items.Add(areaItem); foreach (XElement imageElement in element.Descendants("Image")) { TreeViewItem imageItem = new TreeViewItem(); imageItem.Tag = imageElement.Value; imageItem.Header = imageElement.FirstAttribute.Value; areaItem.Items.Add(imageItem); } MainCanvas.Children.Add(tv); As you can see from the code above it’s a lot simpler and straight forward than using XmlReader. Thank you, --Mike Snow Subscribe in a reader
http://silverlight.net/blogs/msnow/default.aspx
crawl-002
refinedweb
3,958
56.45
Written and Developed by Carlos Casares Oracle Spain Creating applications that interact with data in a synchronous way in Visual Builder is quite easy. But sometimes your application needs to be notified asynchronously or needs to receive so-called unsolicited message. These are messages that are not part of a response of a previous request, might be received at anytime, and need to be handled accordingly. How would you handle these asynchronous events? You have several approaches to get notified from an external event: Using a polling mechanism by means of regular calls initiated from the app/browser every X seconds (or milliseconds or minutes…). This approach is heavy for both the client (app running in your browser) and the server. Another (a bit unknown) approach is Server-Sent Events or subscribing to MQTT topics through the Paho Javascipt library. The one we’re going to focus on is Websockets. (For more information about polling vs. websockets vs. sse, see here). As per Wikipedia: The WebSocket protocol enables interaction between a web browser (or other client application) and a web server with lower overhead than half-duplex alternatives such as HTTP polling, facilitating real-time data transfer from and to the server. In brief, you can establish a bi-directional communication channel between your application and a websocket server (which most likely will be different than the web server itself). Such communication is initiated by the web application (and thus, from the browser) and once established, you will have a channel to send (browser-to-server) and receive (server-to-browser) messages. Websockets runs on top of the HTTP protocol and supports plain and SSL/TLS communication. When used with VB, you’ll need to connect to the server using Websockets Secure (or WSS) as your browser will not allow to use plain HTTP/WS in a HTTPS served application. Websocket is available as default object in HTML that can be easily used in your Javascript code such as: var aWebSocket = new WebSocket(url [, protocols]); Once created, you just need to set a number of callbacks to attend the unsolicited events you’re going to receive. And the object provides a send() method to send messages from the app/browser to the server. You don’t need to link or include any external library to be able to use Websockets in your application. It is that easy! Maybe the most challenging part of Websocket programming is the communications error handling. Take into account that once you open a websocket channel, it will remain opened as long as your internet connection is stable. A network glitch or outage, will simply close the connection and your code is responsible to re-establish it again. From a Server point of view, you can’t do anything when the client lost its connection. Remember, the client (app) is the one who initiates it, not the server. There are many ways to implement a Websocket server, in many different languages (Java, Javascript/nodejs, C#, Python, etc). But, apart from the Websocket object available by default, there are also different client libraries that provide extra features and ease the tasks involved in Websocket programming. One of the most famous and my personal favorite is socket.io, that can be used for both client and websocket server implementation. Actually, if you plan to use socket.io as your client library, you must connect to a socket.io-based server (socket.io library also supports other transports whenever Websocket is not supported by your browser). Socket.io handles communication outages very well. You, as the app programmer, won’t really need to worry about them (apart from handling an offline situation, of course). While Oracle Visual Builder does not support a declarative “Websocket object” that can be easily dragged and dropped into your apps, it is very easy to extend your applications writing your JS code or importing third party libraries and extend Visual Builder application with a Websocket channel (using, in my example, the socket.io library). You just need to follow these simple steps: 1) Import/link the socket.io client library in your app 2) Create the socket.io object and establish the connection with your server 3) Send messages whenever you want or 4) Receive (unsolicited) messages and trigger a VB Custom Event (which will actually handle the message, and interact with VB objects) You can add socket.io to your VB app by downloading the socket.io client library and import it in your VB app or by loading it at runtime from a CDN using require.js. You can do so in the JS section of your appplication, flow or page, depending if you want the websocket to be available at app, flow or page level respectively: define([''], function(io) { (the CDN link used may vary; just do a Google search for socket.io client library cdn and get the latest version) Declare the socket variable outside of your prototype functions so that it doesn’t get initialized every time and also you can have multiple JS functions for different purposes that will make use of the Websocket communication: var socket; You can handle the incoming messages within your JS code, as part of the callback function. However, you will most likely want to run Action Chains as part of such handling. If so, you will need to get your app EventHelper object that will allow you to fire custom events. Declare it along with the socket variable: var socket, eventHelper; and get it in your PageModule (or FlowModule or AppModule) constructor. Such constructor is always part of your default JS code: var PageModule = function PageModule () {}; enhance it as follows: var PageModule = function PageModule(context) { if (context) { eventHelper = context.getEventHelper(); } }; Note: PageModule() (or FlowModule() or AppModule()) seems to be invoked several times during initialization, and the context object is not always valid. Thus, check if it really comes in before getting an error when trying to get the EventHelper from an undefined variable. Then, you need to write a prototype function that will handle all the Websockets communication (connection, disconnection and message reception). If you want to also send messages from your VB app (not part of this example), you can write a separate prototype function that will invoke the send()or emit() methods as follows: socket.send() socket.emit() You can use namespaces when sending (and receiving) messages with the socket.io library. Check the official documentation on that. This is the complete code for the prototype function in my example: PageModule.prototype.startWebsocket = function(start, hostname, port) { if (start == true) { /** Websocket/socket.io stuff **/ console.log("***********: " + hostname + ":" + port); socket = io("wss://" + hostname + ":" + port, { autoConnect: false, transports: ['websocket'] }); var messageHandler = function(message) { console.log("******* [WEBSOCKET]: " + "Message received: " + JSON.stringify(message)); if (eventHelper) { eventHelper.fireCustomEvent("newMessage", { message: { timestamp: Date().toString(), data: message.data } } ); } }; }); } }); socket.on('message', messageHandler); socket.connect(); /** Websocket/socket.io stuff **/ } else { if (socket) { socket.disconnect(); } } } It receives three input parameters: If (start == true) the code tries to establish the connection and define some callbacks that will be invoked under certain events (connect, disconnect, and message in the example): socket = io("wss://" + hostname + ":" + port, { autoConnect: false, transports: ['websocket'] }); Note how we’re using “wss” as the protocol (equivalent to HTTPS for websockets) as your browser will not allow you to establish a plain connection in an SSL served application. Also, we’re forcing socket.io to use websocket protocol and not to auto connect. Remember the io object is defined during the requirejs declaration: define([''], function(io) { We define the messageHandler function that will be later linked to the message callback definition. In this function we simply fire a VB custom event named newMessage: var messageHandler = function(message) { console.log("******* [WEBSOCKET]: " + "Message received: " + JSON.stringify(message)); if (eventHelper) { eventHelper.fireCustomEvent("newMessage", { message: { timestamp: Date().toString(), data: message.data } } ); } }; As part of the socket.io sample server implementation, we’re sending the following message structure: { data: "any text string" } And thus, we’re accessing its content through message.data in the above code. Of course, you can send literally whatever you want (binary, plain text, JSON, etc). Remember you can set your own payload to your custom events, but remember its definition when processing it in the ActionChain. In the example, we’re sending the following JSON object: { message: { timestamp: Date().toString(), data: message.data } } We now set the callbacks for the connect and disconnect events, where we will fire two different custom events to update the status in the application: }); } }); Finally, we set the message callback handler and (try to) establish the connection: socket.on('message', messageHandler); socket.connect(); Note we’re not defining any method or handler for reconnections. The magic of socket.io will handle all that for us! The last piece of code is to disconnect the existing connection (if any) should the start input variable is false: if (socket) { socket.disconnect(); } And that’s all for the JS part! Now it’s time to configure the VB application: 1) Create the variables and UI 2) Define custom events 3) Create the Action Chains that will be triggered by my custom events We start from an empty VB project where we create a new Web App named wssclientsample, and will use the default template (“None”) and do everything in the pre-created main flow and main-start page. Also, all variables, code, etc, will be at main-start page level. First, we’re going to create the following variables: The page UI is: Components data binding (in order): The Switch component triggers the following Action Chain through the value event, to connect or disconnect the websocket channel: The Call Module Function invokes the JS startWebsocket() method with the following mappings: Within the startWebsocket() JS method, you are triggering some custom events based on some events that happen as part of the websocket implementation: Note how the fireCustomEvent() method sends the same payload type as defined in the Custom Event: eventHelper.fireCustomEvent("changeWebsocketStatus", { connected: true }); eventHelper.fireCustomEvent("newMessage", { message: { timestamp: Date().toString(), data: message.data } } ); The Custom Events are triggered from the JS code that controls the websocket connection and message reception. We need to implement the Action Chains that will be triggered by those Custom Events: The Action Chain code is very simple, we just assign a variable on each: setStatus: data: …and with this, we’re done with all VB stuff! Now, you will be wondering which Websocket server your VB app is going to connect to. As part of this sample, I have written a very simple socket.io-based Websocket server that can be found here: If you plan to run it locally, you’ll have to deal with the SSL certificates. Remember that you need to host your websocket with SSL or the browser will reject the connection. I use a valid certificate and load it here in the server code: const optionsSSL = { cert: fs.readFileSync(SSLPATH + "/certificate.fullchain.crt").toString(), key: fs.readFileSync(SSLPATH + "/certificate.key").toString() }; However, you will need to have your own, either a valid one or a self-signed. If the second, you will need to upload it to your VB instance. See here for more info. Remember to run a npm install to download and install all the npm packages needed. Once you run your server, remember your IP address/hostname and the port used and type them in accordingly in your VB app: When ready, you just need POSTMAN, cURL or any other REST client to send the POST request to the server which will forward it as a websocket message to your VB app:
https://blogs.oracle.com/vbcs/working-with-asynchronous-event-and-websocket-in-visual-builder
CC-MAIN-2020-34
refinedweb
1,939
53.71
Managed thread objects have an ApartmentState property that can be set to STA or MTA. But setting this property on the main thread doesn't work reliably because the CLR might set the apartment state to MTA (by calling CoInitializeEx(NULL, COINIT_MULTITHREADED)) before your first line of code executes. And once a thread's apartment state has been set, it can't be changed (without calling CoUninitialize first). Therefore, to reliably set the main thread's apartment state, you must place the STAThreadAttribute or MTAThreadAttribute on your entry point. (MTA is the CLR's default, but using MTAThreadAttribute can be necessary in VB.NET since the compiler emits STAThreadAttribute on Main by default for backwards compatibility with VB6.) This is important to understand even if you don't use Interop directly. For example, using Windows Forms requires that your entry point is marked with STAThreadAttribute, and the code emitted when creating a new Visual C++ Windows Forms Application project in VS.NET 7.1 doesn't handle this requirement correctly. Using these attributes is easy in any language except Managed C++. You'd probably expect the following code to print "0x1": #include <objbase.h> #include <stdio.h> #using <mscorlib.dll> using namespace System; [STAThread] int main() { printf("0x%x\n", CoInitialize(NULL)); return 0; } That's because the STAThreadAttribute should force the CLR to initialize the thread to STA, causing the explicit call to CoInitialize to return S_FALSE. But if you run it, you'll see that it prints either "0x0" (S_OK, indicating that the apartment state was not previously set) or "0x80010106" (RPC_E_CHANGED_MODE, indicating that the apartment state was already set to MTA). This means that the attribute didn't work. The reason for this can be discovered by opening the assembly in ILDASM. The main function isn't the assembly's true entry point. The C++ compiler emits an entry point called _mainCRTStartup that initializes the C runtime library before calling your main method. Furthermore, the v7.0 and v7.1 compilers do not propagate attributes on your main method to the true entry point. This should be addressed in a future version of the product, but in the meantime you can do the following: #include <objbase.h> #include <stdio.h> #using <mscorlib.dll> using namespace System; extern "C" int mainCRTStartup(); // Called by mainCRTStartup int main() {} // The true entry point int myMain() // Initialize the CRT mainCRTStartup(); You also need to use the linker option /ENTRY:myMain to make myMain your entry point. In Visual Studio .NET, this is the Entry Point setting under Configuration Properties -> Linker -> Advanced in the project's Property dialog. This new code prints "0x1" every time. This example used mainCRTStartup with main, but you could also use wMainCRTStartup with wmain. Or for a Windows application (/SUBSYSTEM:WINDOWS), you can use WinMainCRTStartup with WinMain, or wWinMainCRTStartup with wWinMain.
http://blogs.msdn.com/b/adam_nathan/archive/2003/07/18/56727.aspx
CC-MAIN-2015-48
refinedweb
473
57.06
/* $OpenBSD: buf_subs.c,v 1.21 2005/11/09 19:59:06 otto Exp $ */ /* $NetBSD: buf_subs.c,v 1.5 1995/03/21 09:07:08[] = "@(#)buf_subs.c 8.2 (Berkeley) 4/18/94"; #else static const char rcsid[] = "$OpenBSD: buf_subs.c,v 1.21 2005/11/09 19:59:06 otto Exp $"; #endif #endif /* not lint */ #include <sys/types.h> #include <sys/time.h> #include <sys/stat.h> #include <sys/param.h> #include <stdio.h> #include <errno.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include "pax.h" #include "extern.h" /* * routines which implement archive and file buffering */ #define MINFBSZ 512 /* default block size for hole detect */ #define MAXFLT 10 /* default media read error limit */ /* * Need to change bufmem to dynamic allocation when the upper * limit on blocking size is removed (though that will violate pax spec) * MAXBLK define and tests will also need to be updated. */ static char bufmem[MAXBLK+BLKMULT]; /* i/o buffer + pushback id space */ static char *buf; /* normal start of i/o buffer */ static char *bufend; /* end or last char in i/o buffer */ static char *bufpt; /* read/write point in i/o buffer */ int blksz = MAXBLK; /* block input/output size in bytes */ int wrblksz; /* user spec output size in bytes */ int maxflt = MAXFLT; /* MAX consecutive media errors */ int rdblksz; /* first read blksize (tapes only) */ off_t wrlimit; /* # of bytes written per archive vol */ off_t wrcnt; /* # of bytes written on current vol */ off_t rdcnt; /* # of bytes read on current vol */ /* * wr_start() * set up the buffering system to operate in a write mode * Return: * 0 if ok, -1 if the user specified write block size violates pax spec */ int wr_start(void) { buf = &(bufmem[BLKMULT]); /* * Check to make sure the write block size meets pax specs. If the user * does not specify a blocksize, we use the format default blocksize. * We must be picky on writes, so we do not allow the user to create an * archive that might be hard to read elsewhere. If all ok, we then * open the first archive volume */ if (!wrblksz) wrblksz = frmt->bsz; if (wrblksz > MAXBLK) { paxwarn(1, "Write block size of %d too large, maximium is: %d", wrblksz, MAXBLK); return(-1); } if (wrblksz % BLKMULT) { paxwarn(1, "Write block size of %d is not a %d byte multiple", wrblksz, BLKMULT); return(-1); } if (wrblksz > MAXBLK_POSIX) { paxwarn(0, "Write block size of %d larger than POSIX max %d, archive may not be portable", wrblksz, MAXBLK_POSIX); return(-1); } /* * we only allow wrblksz to be used with all archive operations */ blksz = rdblksz = wrblksz; if ((ar_open(arcname) < 0) && (ar_next() < 0)) return(-1); wrcnt = 0; bufend = buf + wrblksz; bufpt = buf; return(0); } /* * rd_start() * set up buffering system to read an archive * Return: * 0 if ok, -1 otherwise */ int rd_start(void) { /* * leave space for the header pushback (see get_arc()). If we are * going to append and user specified a write block size, check it * right away */ buf = &(bufmem[BLKMULT]); if ((act == APPND) && wrblksz) { if (wrblksz > MAXBLK) { paxwarn(1,"Write block size %d too large, maximium is: %d", wrblksz, MAXBLK); return(-1); } if (wrblksz % BLKMULT) { paxwarn(1, "Write block size %d is not a %d byte multiple", wrblksz, BLKMULT); return(-1); } } /* * open the archive */ if ((ar_open(arcname) < 0) && (ar_next() < 0)) return(-1); bufend = buf + rdblksz; bufpt = bufend; rdcnt = 0; return(0); } /* * cp_start() * set up buffer system for copying within the file system */ void cp_start(void) { buf = &(bufmem[BLKMULT]); rdblksz = blksz = MAXBLK; } /* * appnd_start() * Set up the buffering system to append new members to an archive that * was just read. The last block(s) of an archive may contain a format * specific trailer. To append a new member, this trailer has to be * removed from the archive. The first byte of the trailer is replaced by * the start of the header of the first file added to the archive. The * format specific end read function tells us how many bytes to move * backwards in the archive to be positioned BEFORE the trailer. Two * different position have to be adjusted, the O.S. file offset (e.g. the * position of the tape head) and the write point within the data we have * stored in the read (soon to become write) buffer. We may have to move * back several records (the number depends on the size of the archive * record and the size of the format trailer) to read up the record where * the first byte of the trailer is recorded. Trailers may span (and * overlap) record boundaries. * We first calculate which record has the first byte of the trailer. We * move the OS file offset back to the start of this record and read it * up. We set the buffer write pointer to be at this byte (the byte where * the trailer starts). We then move the OS file pointer back to the * start of this record so a flush of this buffer will replace the record * in the archive. * A major problem is rewriting this last record. For archives stored * on disk files, this is trivial. However, many devices are really picky * about the conditions under which they will allow a write to occur. * Often devices restrict the conditions where writes can be made, * so it may not be feasible to append archives stored on all types of * devices. * Return: * 0 for success, -1 for failure */ int appnd_start(off_t skcnt) { int res; off_t cnt; if (exit_val != 0) { paxwarn(0, "Cannot append to an archive that may have flaws."); return(-1); } /* * if the user did not specify a write blocksize, inherit the size used * in the last archive volume read. (If a is set we still use rdblksz * until next volume, cannot shift sizes within a single volume). */ if (!wrblksz) wrblksz = blksz = rdblksz; else blksz = rdblksz; /* * make sure that this volume allows appends */ if (ar_app_ok() < 0) return(-1); /* * Calculate bytes to move back and move in front of record where we * need to start writing from. Remember we have to add in any padding * that might be in the buffer after the trailer in the last block. We * travel skcnt + padding ROUNDED UP to blksize. */ skcnt += bufend - bufpt; if ((cnt = (skcnt/blksz) * blksz) < skcnt) cnt += blksz; if (ar_rev((off_t)cnt) < 0) goto out; /* * We may have gone too far if there is valid data in the block we are * now in front of, read up the block and position the pointer after * the valid data. */ if ((cnt -= skcnt) > 0) { /* * watch out for stupid tape drives. ar_rev() will set rdblksz * to be real physical blocksize so we must loop until we get * the old rdblksz (now in blksz). If ar_rev() fouls up the * determination of the physical block size, we will fail. */ bufpt = buf; bufend = buf + blksz; while (bufpt < bufend) { if ((res = ar_read(bufpt, rdblksz)) <= 0) goto out; bufpt += res; } if (ar_rev((off_t)(bufpt - buf)) < 0) goto out; bufpt = buf + cnt; bufend = buf + blksz; } else { /* * buffer is empty */ bufend = buf + blksz; bufpt = buf; } rdblksz = blksz; rdcnt -= skcnt; wrcnt = 0; /* * At this point we are ready to write. If the device requires special * handling to write at a point were previously recorded data resides, * that is handled in ar_set_wr(). From now on we operate under normal * ARCHIVE mode (write) conditions */ if (ar_set_wr() < 0) return(-1); act = ARCHIVE; return(0); out: paxwarn(1, "Unable to rewrite archive trailer, cannot append."); return(-1); } /* * rd_sync() * A read error occurred on this archive volume. Resync the buffer and * try to reset the device (if possible) so we can continue to read. Keep * trying to do this until we get a valid read, or we reach the limit on * consecutive read faults (at which point we give up). The user can * adjust the read error limit through a command line option. * Returns: * 0 on success, and -1 on failure */ int rd_sync(void) { int errcnt = 0; int res; /* * if the user says bail out on first fault, we are out of here... */ if (maxflt == 0) return(-1); if (act == APPND) { paxwarn(1, "Unable to append when there are archive read errors."); return(-1); } /* * poke at device and try to get past media error */ if (ar_rdsync() < 0) { if (ar_next() < 0) return(-1); else rdcnt = 0; } for (;;) { if ((res = ar_read(buf, blksz)) > 0) { /* * All right! got some data, fill that buffer */ bufpt = buf; bufend = buf + res; rdcnt += res; return(0); } /* * Oh well, yet another failed read... * if error limit reached, ditch. o.w. poke device to move past * bad media and try again. if media is badly damaged, we ask * the poor (and upset user at this point) for the next archive * volume. remember the goal on reads is to get the most we * can extract out of the archive. */ if ((maxflt > 0) && (++errcnt > maxflt)) paxwarn(0,"Archive read error limit (%d) reached",maxflt); else if (ar_rdsync() == 0) continue; if (ar_next() < 0) break; rdcnt = 0; errcnt = 0; } return(-1); } /* * pback() * push the data used during the archive id phase back into the I/O * buffer. This is required as we cannot be sure that the header does NOT * overlap a block boundary (as in the case we are trying to recover a * flawed archived). This was not designed to be used for any other * purpose. (What software engineering, HA!) * WARNING: do not even THINK of pback greater than BLKMULT, unless the * pback space is increased. */ void pback(char *pt, int cnt) { bufpt -= cnt; memcpy(bufpt, pt, cnt); return; } /* * rd_skip() * skip forward in the archive during a archive read. Used to get quickly * past file data and padding for files the user did NOT select. * Return: * 0 if ok, -1 failure, and 1 when EOF on the archive volume was detected. */ int rd_skip(off_t skcnt) { off_t res; off_t cnt; off_t skipped = 0; /* * consume what data we have in the buffer. If we have to move forward * whole records, we call the low level skip function to see if we can * move within the archive without doing the expensive reads on data we * do not want. */ if (skcnt == 0) return(0); res = MIN((bufend - bufpt), skcnt); bufpt += res; skcnt -= res; /* * if skcnt is now 0, then no additional i/o is needed */ if (skcnt == 0) return(0); /* * We have to read more, calculate complete and partial record reads * based on rdblksz. we skip over "cnt" complete records */ res = skcnt%rdblksz; cnt = (skcnt/rdblksz) * rdblksz; /* * if the skip fails, we will have to resync. ar_fow will tell us * how much it can skip over. We will have to read the rest. */ if (ar_fow(cnt, &skipped) < 0) return(-1); res += cnt - skipped; rdcnt += skipped; /* * what is left we have to read (which may be the whole thing if * ar_fow() told us the device can only read to skip records); */ while (res > 0L) { cnt = bufend - bufpt; /* * if the read fails, we will have to resync */ if ((cnt <= 0) && ((cnt = buf_fill()) < 0)) return(-1); if (cnt == 0) return(1); cnt = MIN(cnt, res); bufpt += cnt; res -= cnt; } return(0); } /* * wr_fin() * flush out any data (and pad if required) the last block. We always pad * with zero (even though we do not have to). Padding with 0 makes it a * lot easier to recover if the archive is damaged. zero padding SHOULD * BE a requirement.... */ void wr_fin(void) { if (bufpt > buf) { memset(bufpt, 0, bufend - bufpt); bufpt = bufend; (void)buf_flush(blksz); } } /* * wr_rdbuf() * fill the write buffer from data passed to it in a buffer (usually used * by format specific write routines to pass a file header). On failure we * punt. We do not allow the user to continue to write flawed archives. * We assume these headers are not very large (the memory copy we use is * a bit expensive). * Return: * 0 if buffer was filled ok, -1 o.w. (buffer flush failure) */ int wr_rdbuf(char *out, int outcnt) { int cnt; /* * while there is data to copy copy into the write buffer. when the * write buffer fills, flush it to the archive and continue */ while (outcnt > 0) { cnt = bufend - bufpt; if ((cnt <= 0) && ((cnt = buf_flush(blksz)) < 0)) return(-1); /* * only move what we have space for */ cnt = MIN(cnt, outcnt); memcpy(bufpt, out, cnt); bufpt += cnt; out += cnt; outcnt -= cnt; } return(0); } /* * rd_wrbuf() * copy from the read buffer into a supplied buffer a specified number of * bytes. If the read buffer is empty fill it and continue to copy. * usually used to obtain a file header for processing by a format * specific read routine. * Return * number of bytes copied to the buffer, 0 indicates EOF on archive volume, * -1 is a read error */ int rd_wrbuf(char *in, int cpcnt) { int res; int cnt; int incnt = cpcnt; /* * loop until we fill the buffer with the requested number of bytes */ while (incnt > 0) { cnt = bufend - bufpt; if ((cnt <= 0) && ((cnt = buf_fill()) <= 0)) { /* * read error, return what we got (or the error if * no data was copied). The caller must know that an * error occurred and has the best knowledge what to * do with it */ if ((res = cpcnt - incnt) > 0) return(res); return(cnt); } /* * calculate how much data to copy based on whats left and * state of buffer */ cnt = MIN(cnt, incnt); memcpy(in, bufpt, cnt); bufpt += cnt; incnt -= cnt; in += cnt; } return(cpcnt); } /* * wr_skip() * skip forward during a write. In other words add padding to the file. * we add zero filled padding as it makes flawed archives much easier to * recover from. the caller tells us how many bytes of padding to add * This routine was not designed to add HUGE amount of padding, just small * amounts (a few 512 byte blocks at most) * Return: * 0 if ok, -1 if there was a buf_flush failure */ int wr_skip(off_t skcnt) { int cnt; /* * loop while there is more padding to add */ while (skcnt > 0L) { cnt = bufend - bufpt; if ((cnt <= 0) && ((cnt = buf_flush(blksz)) < 0)) return(-1); cnt = MIN(cnt, skcnt); memset(bufpt, 0, cnt); bufpt += cnt; skcnt -= cnt; } return(0); } /* * wr_rdfile() * fill write buffer with the contents of a file. We are passed an open * file descriptor to the file an the archive structure that describes the * file we are storing. The variable "left" is modified to contain the * number of bytes of the file we were NOT able to write to the archive. * it is important that we always write EXACTLY the number of bytes that * the format specific write routine told us to. The file can also get * bigger, so reading to the end of file would create an improper archive, * we just detect this case and warn the user. We never create a bad * archive if we can avoid it. Of course trying to archive files that are * active is asking for trouble. It we fail, we pass back how much we * could NOT copy and let the caller deal with it. * Return: * 0 ok, -1 if archive write failure. a short read of the file returns a * 0, but "left" is set to be greater than zero. */ int wr_rdfile(ARCHD *arcn, int ifd, off_t *left) { int cnt; int res = 0; off_t size = arcn->sb.st_size; struct stat sb; /* * while there are more bytes to write */ while (size > 0L) { cnt = bufend - bufpt; if ((cnt <= 0) && ((cnt = buf_flush(blksz)) < 0)) { *left = size; return(-1); } cnt = MIN(cnt, size); if ((res = read(ifd, bufpt, cnt)) <= 0) break; size -= res; bufpt += res; } /* * better check the file did not change during this operation * or the file read failed. */ if (res < 0) syswarn(1, errno, "Read fault on %s", arcn->org_name); else if (size != 0L) paxwarn(1, "File changed size during read %s", arcn->org_name); else if (fstat(ifd, &sb) < 0) syswarn(1, errno, "Failed stat on %s", arcn->org_name); else if (arcn->sb.st_mtime != sb.st_mtime) paxwarn(1, "File %s was modified during copy to archive", arcn->org_name); *left = size; return(0); } /* * rd_wrfile() * extract the contents of a file from the archive. If we are unable to * extract the entire file (due to failure to write the file) we return * the numbers of bytes we did NOT process. This way the caller knows how * many bytes to skip past to find the next archive header. If the failure * was due to an archive read, we will catch that when we try to skip. If * the format supplies a file data crc value, we calculate the actual crc * so that it can be compared to the value stored in the header * NOTE: * We call a special function to write the file. This function attempts to * restore file holes (blocks of zeros) into the file. When files are * sparse this saves space, and is a LOT faster. For non sparse files * the performance hit is small. As of this writing, no archive supports * information on where the file holes are. * Return: * 0 ok, -1 if archive read failure. if we cannot write the entire file, * we return a 0 but "left" is set to be the amount unwritten */ int rd_wrfile(ARCHD *arcn, int ofd, off_t *left) { int cnt = 0; off_t size = arcn->sb.st_size; int res = 0; char *fnm = arcn->name; int isem = 1; int rem; int sz = MINFBSZ; struct stat sb; u_int32_t crc = 0; /* * pass the blocksize of the file being written to the write routine, * if the size is zero, use the default MINFBSZ */ if (ofd < 0) sz = PAXPATHLEN + 1; /* GNU tar long link/file */ else if (fstat(ofd, &sb) == 0) { if (sb.st_blksize > 0) sz = (int)sb.st_blksize; } else syswarn(0,errno,"Unable to obtain block size for file %s",fnm); rem = sz; *left = 0L; /* * Copy the archive to the file the number of bytes specified. We have * to assume that we want to recover file holes as none of the archive * formats can record the location of file holes. */ while (size > 0L) { cnt = bufend - bufpt; /* * if we get a read error, we do not want to skip, as we may * miss a header, so we do not set left, but if we get a write * error, we do want to skip over the unprocessed data. */ if ((cnt <= 0) && ((cnt = buf_fill()) <= 0)) break; cnt = MIN(cnt, size); if ((res = file_write(ofd,bufpt,cnt,&rem,&isem,sz,fnm)) <= 0) { *left = size; break; } if (docrc) { /* * update the actual crc value */ cnt = res; while (--cnt >= 0) crc += *bufpt++ & 0xff; } else bufpt += res; size -= res; } /* * (isem && (arcn->sb.st_size > 0L)) file_flush(ofd, fnm, isem); /* * if we failed from archive read, we do not want to skip */ if ((size > 0L) && (*left == 0L)) return(-1); /* * some formats record a crc on file data. If so, then we compare the * calculated crc to the crc stored in the archive */ if (docrc && (size == 0L) && (arcn->crc != crc)) paxwarn(1,"Actual crc does not match expected crc %s",arcn->name); return(0); } /* * cp_file() * copy the contents of one file to another. used during -rw phase of pax * just as in rd_wrfile() we use a special write function to write the * destination file so we can properly copy files with holes. */ void cp_file(ARCHD *arcn, int fd1, int fd2) { int cnt; off_t cpcnt = 0L; int res = 0; char *fnm = arcn->name; int no_hole = 0; int isem = 1; int rem; int sz = MINFBSZ; struct stat sb; /* * check for holes in the source file. If none, we will use regular * write instead of file write. */ if (((off_t)(arcn->sb.st_blocks * BLKMULT)) >= arcn->sb.st_size) ++no_hole; /* * pass the blocksize of the file being written to the write routine, * if the size is zero, use the default MINFBSZ */ if (fstat(fd2, &sb) == 0) { if (sb.st_blksize > 0) sz = sb.st_blksize; } else syswarn(0,errno,"Unable to obtain block size for file %s",fnm); rem = sz; /* * read the source file and copy to destination file until EOF */ for (;;) { if ((cnt = read(fd1, buf, blksz)) <= 0) break; if (no_hole) res = write(fd2, buf, cnt); else res = file_write(fd2, buf, cnt, &rem, &isem, sz, fnm); if (res != cnt) break; cpcnt += cnt; } /* * check to make sure the copy is valid. */ if (res < 0) syswarn(1, errno, "Failed write during copy of %s to %s", arcn->org_name, arcn->name); else if (cpcnt != arcn->sb.st_size) paxwarn(1, "File %s changed size during copy to %s", arcn->org_name, arcn->name); else if (fstat(fd1, &sb) < 0) syswarn(1, errno, "Failed stat of %s", arcn->org_name); else if (arcn->sb.st_mtime != sb.st_mtime) paxwarn(1, "File %s was modified during copy to %s", arcn->org_name, arcn->name); /* * (!no_hole && isem && (arcn->sb.st_size > 0L)) file_flush(fd2, fnm, isem); return; } /* * buf_fill() * fill the read buffer with the next record (or what we can get) from * the archive volume. * Return: * Number of bytes of data in the read buffer, -1 for read error, and * 0 when finished (user specified termination in ar_next()). */ int buf_fill(void) { int cnt; static int fini = 0; if (fini) return(0); for (;;) { /* * try to fill the buffer. on error the next archive volume is * opened and we try again. */ if ((cnt = ar_read(buf, blksz)) > 0) { bufpt = buf; bufend = buf + cnt; rdcnt += cnt; return(cnt); } /* * errors require resync, EOF goes to next archive */ if (cnt < 0) break; if (ar_next() < 0) { fini = 1; return(0); } rdcnt = 0; } exit_val = 1; return(-1); } /* * buf_flush() * force the write buffer to the archive. We are passed the number of * bytes in the buffer at the point of the flush. When we change archives * the record size might change. (either larger or smaller). * Return: * 0 if all is ok, -1 when a write error occurs. */ int buf_flush(int bufcnt) { int cnt; int push = 0; int totcnt = 0; /* * if we have reached the user specified byte count for each archive * volume, prompt for the next volume. (The non-standard -R flag). * NOTE: If the wrlimit is smaller than wrcnt, we will always write * at least one record. We always round limit UP to next blocksize. */ if ((wrlimit > 0) && (wrcnt > wrlimit)) { paxwarn(0, "User specified archive volume byte limit reached."); if (ar_next() < 0) { wrcnt = 0; exit_val = 1; return(-1); } wrcnt = 0; /* * The new archive volume might have changed the size of the * write blocksize. if so we figure out if we need to write * (one or more times), or if there is now free space left in * the buffer (it is no longer full). bufcnt has the number of * bytes in the buffer, (the blocksize, at the point we were * CALLED). Push has the amount of "extra" data in the buffer * if the block size has shrunk from a volume change. */ bufend = buf + blksz; if (blksz > bufcnt) return(0); if (blksz < bufcnt) push = bufcnt - blksz; } /* * We have enough data to write at least one archive block */ for (;;) { /* * write a block and check if it all went out ok */ cnt = ar_write(buf, blksz); if (cnt == blksz) { /* * the write went ok */ wrcnt += cnt; totcnt += cnt; if (push > 0) { /* we have extra data to push to the front. * check for more than 1 block of push, and if * so we loop back to write again */ memcpy(buf, bufend, push); bufpt = buf + push; if (push >= blksz) { push -= blksz; continue; } } else bufpt = buf; return(totcnt); } else if (cnt > 0) { /* * Oh drat we got a partial write! * if format doesnt care about alignment let it go, * we warned the user in ar_write().... but this means * the last record on this volume violates pax spec.... */ totcnt += cnt; wrcnt += cnt; bufpt = buf + cnt; cnt = bufcnt - cnt; memcpy(buf, bufpt, cnt); bufpt = buf + cnt; if (!frmt->blkalgn || ((cnt % frmt->blkalgn) == 0)) return(totcnt); break; } /* * All done, go to next archive */ wrcnt = 0; if (ar_next() < 0) break; /* * The new archive volume might also have changed the block * size. if so, figure out if we have too much or too little * data for using the new block size */ bufend = buf + blksz; if (blksz > bufcnt) return(0); if (blksz < bufcnt) push = bufcnt - blksz; } /* * write failed, stop pax. we must not create a bad archive! */ exit_val = 1; return(-1); }
http://opensource.apple.com//source/file_cmds/file_cmds-220.7/pax/buf_subs.c
CC-MAIN-2016-40
refinedweb
3,925
66.17
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function that prints all occurrences of pat[] in txt[]. You may assume that n > m. Examples: Input : txt[] = "geeks for geeks" pat[] = "geeks" Output : Pattern found at index 0 Pattern found at index 10 Input : txt[] = "aaaa" pat[] = "aa" Output : Pattern found at index 0 Pattern found at index 1 attern found at index 2 The idea is to use find() in C++. // CPP program to print all occurrences of a pattern // in a text #include <bits/stdc++.h> using namespace std; void printOccurrences(string txt, string pat) { int found = txt.find(pat); while (found != string::npos) { cout << "Pattern found at index " << found << endl; found = txt.find(pat, found + 1); } } int main() { string txt = "aaaa", pat = "aa"; printOccurrences(txt, pat); return 0; } Output: Pattern found at index 0 Pattern found at index 1 Pattern found at index.
http://linksoftvn.com/pattern-searching-using-c-library/
CC-MAIN-2019-43
refinedweb
153
74.39
Muse SDK and Tools Release Notes Table of Contents - 1 Muse SDK and Tools Release Notes - 2 October 2, 2017: Muse Direct Beta – Windows - 3 October 2, 2017: LibMuse 6.0.2 API 9 Android, iOS, Windows and Unity example application - 4 April 25, 2017: LibMuse 6.0.1 API 8 Android, iOS, Windows and Unity example application - 5 December 8, 2016: LibMuse 6.0.0 API 7 Android, iOS and Unity example application - 6 November 23, 2016: LibMuse 6.0.0 API 7 Windows - 7 June 27, 2016: LibMuse 5.13.0 API 4 Android and IOS - 8 May 13, 2016: LibMuse 5.8.0 API 4 Android and IOS - 9 April 12, 2016: LibMuse 5.4.0 API 3 Android and IOS - 10 June 22, 2015: LibMuse-iOS 1.2.1 - 11 May 29, 2015: LibMuse for Android 1.3.0 and LibMuse for iOS 1.2.0 - 12 May 7, 2015: LibMuse for Android 1.2.1 - 13 April 30, 2015: LibMuse for iOS 1.1.0 and LibMuse for Android 1.2.0 - 14 April 29, 2015: LibMuse for iOS 1.0.1 - 15 April 28, 2015: LibMuse for iOS 1.0.0 - 16 March 18, 2015: LibMuse for Android 1.0.4 - 17 March 2, 2015: LibMuse for Android 1.0.2 - 18 February 6, 2015: SDK Tools v3.4.1 & LibMuse for Android 1.0.1 - 19 February 3, 2015: SDK Tools v3.4.0 - 20 January 30, 2015: SDK Tools v3.2.3 - 21 December 23, 2014: SDK Tools v3.2.2 - 22 December 17, 2014: SDK Tools v3.2.0 - 23 Nov 17, 2014: SDK Tools v3.0.2 - 24 November 14, 2014: SDK Tools v3.0.1 - 25 August 12, 2014: SDK Tools v2.4.2 - 26 July 31, 2014: SDK Tools v2.4.0 - 27 July 4, 2014: SDK Tools v2.2.0 - 28 June 24, 2014: SDK Tools v2.0.0 - 29 April 10, 2014: SDK Tools v1.0 October 2, 2017: Muse Direct Beta – Windows Key features: - Connect to multiple headbands via Bluetooth - Stream live data to one or many computers simultaneously - One-click recording - Receives and streams raw data from the Muse headband including EEG, accelerometer, gyroscope, battery, and DRL/REF - Comes with built-in algorithms: band powers, headband status indicator, data quality indicator, blink event, jaw clench event, and “is user wearing headband” indicator - Easy-to-use GUI Known issues: - Replaying the data as OSC messages using Muse Player with the -s output option does not work with files saved from Muse Direct. - Muse Direct may terminate unexpectedly if Bluetooth is turned off from the settings application while streaming data from the headband. October 2, 2017: LibMuse 6.0.2 API 9 Android, iOS, Windows and Unity example application Features introduced in this release: General - Allow an in progress connection to be cancelled if Muse.disconnect() is called while attempting to connect to the headband. - Introduces the ComputingDeviceConfigurationFactory class which can be used to get a ComputingDeviceConfiguration object containing information about the host machine. - The flush() function of MuseFileWriter now returns a boolean value indicating if the flush operation succeeded in writing to the file or not. - Adds the isPaired() function to the Muse class. This can be used to determine if the Muse headband is paired with the system or not. This is most useful on Windows where this distinction is made for Bluetooth Low Energy devices . Android - Updates the example application project to use API level 25 (7.1) Issues addressed in this release: General - Fixed MuseConfiguration to return proper values from getPreset() Windows - Fixed an issue where some data packets could get reversed in order due to an ordering issue with EventLoop. - Fixed a crash that could occur when trying to write to a network drive that disconnects during the write operation. - Prevent a crash that could arise if one or more of the Bluetooth characteristics was not correctly initialized. - Fixed an issue where the headband would immediately disconnect the second time it was asked to connect. - Fixed an issue where if 2 actions were added for the same execution time in an EventLoop, the second action could be processed before the first. Now the first action added will be the first action processed at the specified execution time. - Correctly stop listening if MuseManager::stop_listening() is called while the Bluetooth radio is off. Documentation - Added units to the documentation of EEG and DRL/REF data packets. - Clarified usage and differences between ReaderMuse and MuseFileReader. - Fixed broken link in MuseConnectionListener. API changes in this release: - The flush() function of MuseFileWriter now returns a boolean value indicating if the flush operation succeeded in writing to the file or not. April 25, 2017: LibMuse 6.0.1 API 8 Android, iOS, Windows and Unity example application Features introduced in this release: - The application name, application version and LibMuse version are now automatically added as an annotation at the start of all .muse files created with MuseFileWriter. This can be used to identify source and version of LibMuse that produced the file. Issues addressed in this release: General - MuseArtifactPacket now includes a timestamp like MuseDataPacket. - The ARTIFACT message type has been added to the MessageType enumeration to identify a MuseArtifactPacket in a .muse file. Use MuseFileWriter::add_artifact_packet() to save an artifact packet in the file and MuseFileWriter::get_artifact_packet() to retrieve it. - A warning has been added to provide more context to the failed assertion that is thrown if a Muse object is destroyed while in the connected state. Muse objects should only be destroyed while in the disconnected state but this assertion could appear if start_listening is called while the application maintains a reference to a connected Muse object. If you maintain a local reference to a Muse object, make sure it is in the disconnected state before setting it to null. Android - Exceptions raised during the connection process no longer crash the application. Now if an error is encountered, the error will be logged and the headband will return to the disconnected state. Windows - Fixed a crash that could arise if you tried to connect to a Muse while Bluetooth was off. Now the connection request is deferred until Bluetooth is turned on or a disconnect is requested. - If the pairing operation fails when connecting to a Muse 2016, LibMuse will now disconnect immediately rather than waiting for the connection attempt to time out. - run_asynchronously can be called on multiple Muse objects to simultaneously connect to more than 1 Muse headband. - The RSSI value of a Muse is correctly returned if it is known. - MuseManagerWindows::getInstance() has been deprecated. Use MuseManagerWindows::get_instance() instead. Documentation - Formatting fixes for the Android documentation. - Updated readme file with links to the Bug Reports forum and License terms. Breaking API changes in this release: - The constructor of MuseArtifactPacket has changed to take 4 parameters instead of 3, with the timestamp as the fourth parameter. This will only impact you if you are constructing your own instances of MuseArtifactPackets. December 8, 2016: LibMuse 6.0.0 API 7 Android, iOS and Unity example application Features introduced in this release: - New API to allow LibMuse to throw exceptions for debugging purposes rather than trying to catch everything. See Muse::enable_exception for more details. - enableDataTransmission has been(). Android - Fixed MuseFileAndroid to return false if the write operation failed. - Fixed a potential crash that could occur from attempting to read data from a Muse 2016 headband before the connection was established. Documentation - Fixed the Accelerometer documentation to clarify the X, Y and Z axes. - Fixed MuseLog documentation to indicate that calling MuseLog.f will cause the application to crash with SIGABRT. Breaking API changes in this release: - Locations of header files for iOS have changed to remove gen-objc. Instead all iOS header files are now located under Muse/api/. If you have included individual headers from the Muse framework, you will need to update to the new path. No changes are required if you are including “Muse/Muse.h” - applications. November 23, 2016: LibMuse 6.0.0 API 7 Windows Known Issues: - Unpaired Muse 2016 headbands that were previously detected but are currently off may be returned when querying MuseManager for the list of Muse headbands. Unpaired Muse 2016 headbands that are off will be removed from the list automatically when the remove_from_list_after timeout expires (30 seconds by default). - Trying to connect to a Muse 2014 headband that is paired with the computer but is currently off results in a Platform::COMException being thrown. LibMuse will catch this exception and disconnect gracefully, but Visual Studio may become unresponsive if running the application with the debugger attached. This can be avoided by removing Platform::COMException from the “Break when thrown” list in “Exception Settings”. This issue does not happen when running without the debugger attached. - The example applications can only connect to one headband at a time. If you try to connect to a second headband while one is currently connected or connecting, an exception will be thrown. Breaking API changes in this release: - The interaxon::Convert class has been moved to the interaxon::bridge namespace and is now interaxon::bridge::Convert. - application. Features introduced in this release: - LibMuse for Windows is a C++ library that is compatible with the Windows 10 Universal Windows Platform. It supports both Muse 2014 and Muse 2016 headbands. - New API to allow LibMuse to throw exceptions for debugging purposes rather than trying to catch everything. See Muse::enable_exception for more details. - 2 sample applications are included in the examples folder. GettingData illustrates how to connect to the Muse headband. ReaderWriter illustrates how to handle file I/O. In both cases, see MainPage.xaml.cpp for the code. - HTML documentation that describes the C++ API is available from README.html. - Header files for compiling against the LibMuse library are available in the include folder. Include “muse.h” to include all LibMuse headers. - Libraries are available for both Win32 (x86) and x64 development. ARM development is not supported at this time due to lack of ARM support in Google’s protobuf libraries. - There is support for reading and writing .muse files through the MuseFileReader/MuseFileWriter classes. Note however that UWP applications have restrictions on file access based on their capabilities (). - enable_data_transmission is(). Windows - Trying to reconnect to a Muse 2014 headband could result in a Platform::COMException which could cause Visual Studio to hang when running with the debugger attached. This is now fixed. - Fixed an exception that could occur if MuseManager::start_listening() was called immediately after a call to MuseManager::stop_listening(). - Fixed an issue where run_asynchronously() would fail to start when running in Release mode. - Muse 2014 headbands are now removed from the list of muses in MuseManager when the headband is removed in the Bluetooth settings. You will receive a muse_list_changed callback when this occurs. - Fixed the refresh button in the example applications to properly refresh the list of Muse headbands. The first item in the list is now shown in the Combobox. Documentation - Adds EventLoopFactory to the class list. - Fixed the Accelerometer documentation to clarify the X, Y and Z axes. June 27, 2016: LibMuse 5.13.0 API 4 Android and IOS This is a minor release for both Android and iOS that provides new functionality and bug fixes. There are no API breaking changes in this release, but there is a behavioural change in Accelerometer and Gyro data. For the time being we do not support the x86 architecture on Android. Features introduced in this release: - New IS_GOOD data packet type which indicates if the last 1 second of raw EEG data is good or contained too much interference and should not be used. - Introduces ReaderPlaybackListener which provides notifications when a ReaderMuse finishes playback of a file or playback was interrupted. Issues addressed in this release: General - Corrected the timestamp for all EEG derived packets (ALPHA_ABSOLUTE, ALPHA_RELATIVE, ALPHA_SCORE, BETA_ABSOLUTE, …). Previous versions were returning -1 for the timestamp. This has been corrected to be the time the packet was generated by LibMuse. - ACCELEROMETER axis values were inconsistent between Muse 2014 and Muse 2016 headbands. Axes for both headbands have now been mapped to X, Y, Z in a Right Hand Coordinate System as shown in the new documentation. FORWARD_BACKWARD, UP_DOWN and LEFT_RIGHT have been deprecated and the sign of UP_DOWN and LEFT_RIGHT has changed as a result of the new axis mapping. - ACCELEROMETER values are now displayed in G for both Muse 2014 and Muse 2016 headbands. Previous releases had Muse 2014 values displayed in mG. - The GYRO axis values now map to the same axes as the ACCELEROMETER values where GYRO indicates rotation about that axis. - ACCELEROMETER and GYRO values for Muse 2016 headbands running firmware versions 1.2.9 and 1.2.13 have been corrected. LibMuse was returning +/-4G for the accelerometer and +/-1000 degrees per second when the ranges for these firmware versions was actually +/-2G and +/-245 degrees per second. Android - Fixed a crash that occurred if you tried to connect to a headband while the Bluetooth on the device was turned off. - Fixed a crash that could result while attempting to reconnect to a headband after the device had been locked and unlocked. iOS - Fixed a crash that resulted from calling disconnect when the headband was already disconnected. The second call to disconnect is now ignored. May 13, 2016: LibMuse 5.8.0 API 4 Android and IOS Breaking API changes in this release: - Presets 24, 25, AC and AE have been removed. Research presets AB and AD will only emit EEG, ACCELEROMETER and BATTERY data packets. Features introduced in this release: -. Issues addressed in this release: General -. Android - Fixed the issue causing UI lag when attempting to connect to a Muse 2014 (MU-01) headband that was powered off. - Clarified the example application with additional comments. iOS - The example application was including the EAAccessory and CoreBluetooth frameworks unnecessarily. These have been removed as they were not referenced. You can build an iOS application using just Muse.framework Documentation -. April 12, 2016: LibMuse 5.4.0 API 3 Android and IOS Algorithm changes: To better align with established research the computed powers of the EEG bands have changed. In particular: - New values are computed in microvolts as opposed to raw ADC units. - Spectrum is estimated on windows of 1.0 seconds as opposed to 1.16 seconds. To reconcile the difference between the values from the previous release with the values in this release, add 0.4323 to the value from the previous release. Breaking API changes in this release: - The method of discovering headbands has changed. MuseManager.refreshPairedMuses and MuseManager.getPairedMuses have been removed. To discover Muse headbands, set a MuseListener using MuseManager.setMuseListener and then call MuseManager.startScanning. When a Muse is discovered, you will receive a MuseListener.museListChanged() callback. See the example code for more details. - Muse.getMuseConfiguration() and Muse.getMuseVersion() may return null values. A null value is returned if you have not yet connected to that particular Muse and the configuration and version is unknown. After connecting to the headband, configuration and version data will be non-null even if you later disconnect. - SenderInformation has been removed. As a consequence, the getSource function in MuseArtifactPacket, MuseConnectionPacket and MuseDataPacket has also been removed. A Muse object is now passed as an input parameter in the following functions and can be used to get the information that SenderInformation used to provide. - MuseConnectionListener::receiveMuseConnectionPacket - MuseDataListener::receiveMuseDataPacket - MuseDataListener::receiveMuseArtifactPacket - Static constants in LibMuseVersion have been replaced with a static ApiVersion instance. In addition, the semantic meaning of the digits in API version have changed. Major version now refers to the release of the SDK. API breaking changes are now tracked with an API field rather than the major version. The version string and monotonic version have changed as a result. The monotonic version is still greater than all previous monotonic versions. Use the ApiVersion instance to retrieve the major, minor and patch version numbers as well as the string version of the API. - MELLOW and CONCENTRATION date packet types have been removed. There is no replacement for these data types. - HORSESHOE data packet types have been renamed to HSI_PRECISION. - The TP9, FP1, FP2, TP10 EEG enumeration values have been renamed to EEG1, EEG2, EEG3, EEG4 respectively. - DROPPED_EEG and DROPPED_ACCELEROMETER packet types are now deprecated. NaN values are used in the EEG data to represent dropped values. - The open, write and close functions in MuseFile now return boolean values to indicate the success or failure of the corresponding operation. Android specific breaking API changes in this release: - Classes in the com.interaxon package have been moved to the com.choosemuse package. Please update your imports accordingly. iOS specific breaking API changes in this release: - EAAccessory(IXNAccessoryMuse) has been removed. Register a IXNMuseListener with IXNMuseManager to receive a callback when a Muse is connected. This also removes the need to include the linker flag -ObjC. - The following instance functions have been removed with no replacement: - IXNAnnotationData::initWithAnnotationData - IXNComputingDeviceConfiguration::initWithComputingDeviceConfiguration - IXNDspData::initWithDspData - IXNMuseArtifcatPacket::initWithMuseArtifactPacket - IXNMuseConfiguration::initWithMuseConfiguration - IXNMuseConnectionPacket::initWithMuseConnectionPacket - IXNMuseDataPacket::initWithMuseDataPacket - IXNMuseVersion::initWithMuseVersion - The following functions now return an interface rather than a protocol. References to id will need to be replaced with references to class_name*. - IXNMuseFileFactory::museFileWriterWithPathString - IXNMuseFileFactory::museFileReaderWithPathString - IXNMuseFileReader::getFileReader - IXNMuseFileWriter::getFileWriter Features introduced in this release: - Adds support for Muse 2016 hardware - MuseDataPackets provide functions to access the raw double value of data. This provides much better memory performance over the values() function. Check the packet type before calling the getValue function as calling the wrong getValue function for the packet type results in an exception. - Logs from LibMuse can be added to your own application logging system through LogManager and LogListener. - MuseErrorListener can be used to receive error notifications from LibMuse such as timeouts. - Additional MusePresets had been added to support the second generation hardware and research needs. - Gyro information is now provided through MuseDataPacketType. - MuseFileReader and MuseFileWriter now supports the reading and writing of all MuseDataPacket types. - You can explicitly set the timestamp for messages written with MuseFileWriter. See MuseFileWriter::setTimestampMode. Issues addressed in this release: General - Unknown presets are defaulted to PRESET_10. - Notch frequencies other than 0, 50 or 60 are now defaulted to NOTCH_NONE rather than NOTCH_60HZ. - The battery level read by MuseFileReader is returned as a percentage rather than an absolute value that requires division by 100. - The ranges for the accelerometer and gyro data packets have changed for Mu-02 model headbands. The new ranges are [-4,4) and [-1000, 1000) respectively. There is a corresponding firmware update. Firmware can be updated through the Muse mobile application. Using this version of LibMuse with older firmware will cause the values to be much larger than expected. Android - Libmuse does not crash when trying to connect to a Muse 2014 headband that is off. - Fixed crash that resulted from trying to get the name of a device that had no name. An empty string is returned in this case. - MuseManager provides a museListChanged() callback for each muse detected after startListening() is called. Previously, some callbacks were not performed if startListening() was called multiple times. - Calling Muse.setNumConnectTries() on a MU-01 headband no longer throws an exception. Instead it does nothing. - Improves connectivity for android devices and fixes issue where once a device reached an error state it would not reconnect. - Updated the example application to use Android Studio and SDK level 23. iOS - MuseFileReader returns an empty byte array when trying to read a file that does not exist and is consistent with the documentation. June 22, 2015: LibMuse-iOS 1.2.1 - Fixed a bug that caused apps to get stuck in an infinite reconnect loop when a device went out of and back into range two or more times. - Fixed an issue where the notch frequency was not being properly set for European regions. - Fixed a couple of rare edge cases (one on a zero-length read from the OS, and the other on being notified of a Muse accessory being removed without first being added.) - Improved documentation in the example app. May 29, 2015: LibMuse for Android 1.3.0 and LibMuse for iOS 1.2.0 - Changes in both iOS and Android: - macAddress parameter was removed from addConfiguration method in Muse File Writer, because it’s already a part of MuseConfiguration data struct (breaking change). - MuseFileWriterFactory was renamed to MuseFileFactory and 2 methods were added to it: for MuseFileReader creation and MuseFile creation (breaking change). - Added MuseFileReader, which will allow to read and playback muse files. There is a simple example on how to use in both Android and iOS example app. Look for playMuseFile method. - MuseFile interface was changed. - LibMuse for iOS: - ibmuse for iOS is distributed as a static library (libMuse.a file + Headers) and not as dynamic framework. This will allow you to support ios devices >= 7.0 and it should resolve code signing warning. See example App build settings for details on how to use libMuse.a in your project - minimum deployment target on iOS is 7.0 now - LibMuse for Android: - Fixed MuseFileWriter behaviour: now if file exists FileWriter will append new data at the end, before it erased the old data May 7, 2015: LibMuse for Android 1.2.1 - Added libmuse.so for x86 architecture (it was not included in 1.2.0) - Properly populated batteryPercentRemaining in MuseConfiguration class - Changed type for batteryPercentRemaining from int to double - Improved documentation for getMuseConfiguration() and getMuseVersion() methods April 30, 2015: LibMuse for iOS 1.1.0 and LibMuse for Android 1.2.0 - LibMuse for iOS: - support x86 architecture (allows to compile application with libmuse for iphonesimulator) - LibMuse for Android: - added FileWriter API - added Mellow and Concentrations packets - removed rename API from Muse class April 29, 2015: LibMuse for iOS 1.0.1 - Set IPHONEOS_DEPLOYMENT_TARGET to 8.0, as App store rejects applications with dynamic frameworks < 8.0 April 28, 2015: LibMuse for iOS 1.0.0 First release! Features include: - Raw data: EEG, accelerometer, DRL/REF, Battery - DSP data: jaw clench, eye blink, relative and absolute band powers, session score, mellow (experimental), concentration (experimental). - Muse Bluetooth connection handling - Works out of the box in Xcode March 18, 2015: LibMuse for Android 1.0.4 - Fixed minor issue in recovery mechanism in case of data error - Improved error logging in case of data error - Libmuse now notifies headband about host platform on every connect (this improves user experience if same headband is used on multiple devices with different apps) March 2, 2015: LibMuse for Android 1.0.2 - Fixed segfault which could happen onDestroy(). - Reduced disconnection detection to 2.5 sec (was > 10 sec). - Methods connect(), execute() and runAsynchronously() do not throw exceptions anymore. Exceptions are properly handled inside the SDK. - Improved documentation - Improved error handling. February 6, 2015: SDK Tools v3.4.1 & LibMuse for Android 1.0.1 - MuseSDK separated into SDK Tools (MuseIO, MusePlayer, MuseLab) and LibMuse - Changes to LibMuse for Android 1.0.1: - Better error handling - Documentation improvements (added information about threading and exceptions) - Link C++ lib statically - Added new API to MuseManager class to allow to scan for Muse headbands which have custom names - Split libmuse and MuseSDK installers - Provided linux-x64 installer February 3, 2015: SDK Tools v3.4.0 LibMuse for Android 1.0.0 - Our first release of a native library for Android! - See our documentation for getting started with Android Studio. January 30, 2015: SDK Tools v3.2.3 - MuseIO 3.6.5 - Linux – Bug fix to fix 100% CPU usage. - Muse Elements – Fix to better detect “headband on”. December 23, 2014: SDK Tools v3.2.2 - Installer - Fixed installer problem on OSX Yosemite () - Muse-player 1.8.4 - Fixed a hang at end of input when using OSC input (the file would complete processing, but at the end muse-player would sit there forever) - Fixed an occasional hang on Windows with Muse file input - Fixed control-C showing an exception - Fixed bug in MATLAB output for /muse/elements - Fixed crash with Unicode in MATLAB(HDF5) files - Only print output when stdout is a terminal, useful when running Muse-Player in the background - Muse-IO 3.6.4 - Fixed bug on Windows where 50hz/60hz EMI filter command-line option did not work December 17, 2014: SDK Tools v3.2.0 - MusePlayer 1.8.0 - The MATLAB output format has been converted to Matlab File Format 7.3, which is form of HDF5. If you simply load the MATLAB output in MATLAB itself, you will not see or experience any difference from the previous MATLAB files we generated. However, this new format will allow your non-MATLAB programs(Python, C++, Java, etc) to easily parse the MATLAB file. In Python for example, you can simply import h5py and read the file, for example: import h5py # Load a file that has been saved as MATLAB from muse-player f = h5py.File('museplayer-matlab-output.mat','r') # “f” basically becomes a tree data structure at this point. # To show all the possible keys in the data structure: f.keys() f['IXDATA'].keys() # Example of how to get all the raw EEG data f['IXDATA']['raw']['eeg']['data'].value - Added the ability to do regular expression (regex) filtering when using the -i option. Examples: # Get the theta values for all 4 channels: muse-player -i '/muse/elements/.\*theta.\*' - Added –version argument - Better error message if port is in use - Bug fixes - Known issues: In MusePlayer for Linux, MATLAB output is not working for this release. - MuseLab 1.6.3 - Bug fix: Fixed horseshoe not working - Bug fix: Muse-IO timestamps cause all messages to be annotations. Currently timestamps will be ignored when saving. - MuseIO 3.6.3 - Bug fixes Nov 17, 2014: SDK Tools v3.0.2 - MuseIO 3.6.2 - Added back –dsp option for backward compatibility. - MuseLab 1.6.2 - Fixed version number. - MusePlayer 1.6.0 - No changes November 14, 2014: SDK Tools v3.0.1 - Installer - One click install! Removed all extra installation steps for muse-player. - MusePlayer 1.6.0 - Changes made to allow for all-in-one installer. - MuseIO 3.6.1 - Added new algorithm for EEG band power session score. This metric compares your current alpha/beta/etc against your historical average for that band. - Added experimental algorithms “concentration” and “mellow”. See documentation here. - dsp option is enabled by default now, use –no-dsp if you want to disable it. –dsp option is not present anymore (note: it was added back in the next release) - The paths are now considered a stable API. Anything new that is in progress will be put into the /muse/experimental section first before it becomes part of the supported API. - MuseLab 1.6.2 (on release, this was incorrectly marked as 1.7.0) - Bug fix: Can’t change EEG signal trace color - Bug fix: Horseshoe indicator not working - Misc - Revamp of documentation on the wiki. August 12, 2014: SDK Tools v2.4.2 - Muse-Player 1.4.2 - Fixed crash on Windows July 31, 2014: SDK Tools v2.4.0 - Muse-Player 1.4.0 - Ability to play back huge files (8+ hours) – files are loaded incrementally now instead of completely loaded into memory at the start. - Ability to record for long period of time (8+ hours) – files are incrementally saved instead of being written all at once at the end of the recording. - Fixed bugs when piping output from display through “less”. July 4, 2014: SDK Tools v2.2.0 - Added support for Linux - Installer - Brand new installer that makes the install process a bit easier. - All platforms: automatically install Java if it is not already installed. - All platforms: automatically set the path to include Muse install directory. - Windows: Automatically install required Microsoft library without having to click through more dialog boxes. - New icons and graphics. - MuseIO 3.4.0 - Renamed /muse/dsp/bandpowers to /muse/dsp/elements - Changed all double outputs to floats. This only occurred in the dsp paths. - In the channel layout, LCH and RCH have been renamed MUSE_LEFT_AUX and MUSE_RIGHT_AUX. These values have been added to the Muse protobuf file format. - Bug fix: - Layout channel names T9 and T10 were incorrectly labelled, they should be TP9 and TP10. - MusePlayer 1.2.0 - Added ability to output CSV - Automatically do “as-fast-as-possible” when writing files. - Added ability to filter data. - Added ability to auto-skip gaps in data - Added handling of DSP data from MuseIO - Bug fixes: - Fixed crash when using the –osc-timestamp with MuseIO - MuseLab 1.6.1 - Bug fix: When recording from six channel Muse, only 4 channels were recorded. Fixed. - Known Issues: - Muse-Player by default can only receive and transmit UDP messages, so you must change MuseIO and MuseLab accordingly. On MuseIO, this would mean doing: - “muse-io –osc osc.udp://localhost:5000″ June 24, 2014: SDK Tools v2.0.0 - MuseIO 3.2.0 - The first version of Muse Elements – our basic DSP package for developers: - Blink event - Jaw Clench event - Relative band powers for each channel: alpha, beta, gamma, theta, delta, and low frequencies - FFT for each channel - Proper fit indicator for each channel - Data quality indicator for each channel - Aligned MuseIO OSC messages and Muse file format v2. - TCP support - MuseLab 1.6.0 - Headset indicator to indicate proper fit - Battery level indicator - Added support for TCP connections - Recorded sessions now record to Muse file format version 2. - Stationary line graph improvements: - Allow user to mark ranges on the stationary line graph - Display title - Display legend - Ability to hide grid lines - Ability to choose number of grid lines - Exponential magnify area of line graph - Adjust position of magnification - Override master time - Minor improvements - Individual changes to time in a visualizer are now loaded from config file - OSC incoming messages now have a right/left scrollbar - Position and strength are now saved for static line graph - MusePlayer 1.0.0 - Supported inputs: - OSC network stream - OSC-replay file format - Muse file format v1 - Muse file format v2 - Supported outputs: - OSC network stream - OSC-replay file format - Muse file format v2 - MATLAB - Print to screen - Options: - As fast as possible - OSC tools - “oscdump” and “oscsend” have been integrated into the installer for convenience April 10, 2014: SDK Tools v1.0Our first release, containing the following: Supported platforms: Windows, MacOS - MuseIO 3.0.0 - MuseLab 1.4.0
http://developer.choosemuse.com/release-notes
CC-MAIN-2018-09
refinedweb
5,062
57.47
Joy, frustration, excitement, madness, aha's, headaches, ... codito ergo sum! Here’s some good news for everybody that has been waiting for it: I’ve just uploaded the brand new Son of SmartPart to the GotDotNet site! First of all, what is the Son of SmartPart? This version of the SmartPart will allow you to run ASP.NET 2.0 Web User Controls and ASP.NET 2.0 Web Parts in SharePoint sites. Since WSS SP2 you can run your SharePoint sites on the .NET Framework version 2.0, and from now on you can use the power of the new platform to extend SharePoint. What is working and what is not?Not all features that I would like to be in v1.0 are available yet, so what is already working and what’s not? The Son of SmartPart (SOSP) comes in two flavours: one to run ASP.NET 2.0 User Controls (SOSP-UC) and one to run ASP.NET 2.0 Web Parts (SOSP-WP). For the SOSP-UC version, all the features from the previous version of the SmartPart are working, so you can expose custom properties, toolparts, create connectable web parts and so on. The SOSP-WP version only has the basic functionality to run ASP.NET 2.0 web parts. Advanced stuff like connections are not yet supported. Support for these advanced features will follow. How do you install it?If you download the release from the GotDotNet site, you will find an Installation Guide. I’ve also created a small screencast to guide you to this process. There is no automated installation yet because the current version of the deployment tools (STSADM and WPPackager) do not support .NET 2.0 assemblies (yet?). What's next?This is not the last release of the Son Of SmartPart! I'd love to hear your feedback so we can make the coming releases even better. For now: go get the latest version on and unleash the power of ASP.NET 2.0 on your SharePoint sites! This is great stuff Jan. I intent on downloading and playing around with it later this afternoon. Bob Mixon Good news! Can't wait to try this out. And btw, thank you for a GREAT training week in Denmark. It was my pleasure Thomas! Good work. Now you've opened the gates, you might want to add the following to your installation instructions: 1) add WebResource.axd as a non-managed path. To get started, open Windows SharePoint Services Central Admin. In the "Virtual Server Configuration" section click the "Configure virtual server settings" link. In the virtual server list, click the server that you want to configure. (Most people only have "Default Web Site" here.) Now you are on the "Virtual Server Settings" page. In the section called "Virtual Server Management", click on "Define managed paths". Add "WebResource.axd" as non managed path. 2) Add the 2.0 webcontrols as safe controls. Pretty basic: <SafeControl Assembly="System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Namespace="System.Web.UI.WebControls" TypeName="*" Safe="True" /> <SafeControl Assembly="System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" Namespace="System.Web.UI.HtmlControls" TypeName="*" Safe="True" /> 3) please point the users to the fact that they must derive the user controls from SonOfSmartPart.IAdvancedUserControl and that they must add 2 member functions (see the samples, at least, that is how I got it to work) remark: for some reason I have not gotten a 2.0 treeview at work with a HoverNodeStyle. Just remove it, and it will work. Hans and Jan, Are the notes from Hans truely a requirement? Thanks for clarifying. Also, please ammend the note from Hans to indicate that the "safe controls" section is located in the web.config file (some may not know that). Any chance either of you could post a sample VS2005 .Net 2.0 sample? I'm having trouble getting mine to work. I have added the safecontrol section as Hans described, but am getting a Sharepoint error "The "SonOfSmartPartUC" Web Part appears to be causing a problem." P.S. Your sample web control works fine. And, for your sample code to compile, do I need sharepoint installed on my development station? I'm getting a build error "vs2005 the type or namespace name sharepoint does not exist in hte namespace" And, What are the different versions (WP/UC) targeted to? When should I use one or the other? Okay, now a few notes re VS2005 and ASP.NET 2.0 from my work: 1) If you're developing on XP, any references to sharepoint will fail. Not a problem, you just cannot build. 2) To deploy a UC, just copy the aspx and .aspx.cs to the usercontrols dir. I'm not sure how this would work if you wanted to deploy a precompiled uc/dll. 3) I've confirmed Hans' remark regarding HoverNodeStyle. The treeview control can exist, just remove the HoverNodeStyle markup in the ascx file. Also, make sure to follow Hans'/Jans instructions on WebResource.axd /Bob I installed Son of SmartPart v1.0 by reading the installation guide and I watched the video (very nice by the way). Sharepoint is throwing "The format of the file 'SonOfSmartPart' is invalid." error. It sounds like it does not like the DLL. I have SPS installed. Will The Son of Smartpart run under an SPS installation in a WSS site? Hi, I have a small problem with danish national charactors æøå when I load usercontrols.ascx through the smartpart interface. Only when I write æ (æ) for æ in the usercontrol does the character display as æ. If I simply write æ the character is not displayed in the rendered page. Anyone with an idea? Morten I was wondering if it would be possible to store ascx files in a web resource using the WebResourceAttribute and using Page.ClientScript.GetWebResourceUrl() to get the url to pass to Page.LoadControl()? I know the code behind would need to be compiled down to an assembly first. Only thing I see not working is you need to specify the mime type for the resource. I have just managed to get the UC controls up and running on Sharepoint 2007 with great success! However if I try and use any of the Sharepoint 12 features I get a mismatch. When will you be releasing a version of the dll that uses 2007? I receive: An unexpected error has occurred When trying to load my user control? I am using SonofsmartPart on Sharepoint services 2.0 with sp2...please please help me! Where can I download Son of SmartPart? GotDotNet site is down. Looks like the project has moved from gotdotnet to codeplex (). There seems to be little activity from the author though. Best information <a href="honda-did.info/hokie-honda.html ">hokie honda</a> <a href="honda-did.info/2005-honda-cbr600rr.html ">2005 honda cbr600rr</a> <a href="honda-did.info/h22-in-a-89-honda-civic.html ">h22 in a 89 honda civic</a> <a href="honda-did.info/1994-honda-accord-ex-ball-joints.html ">1994 honda accord ex ball joints</a> [URL=honda-did.info/honda-crv-tow-capacity.html]honda crv tow capacity[/URL] [URL=honda-did.info/cargo-rack-for-honda-250ex-atv.html]cargo rack for honda 250ex atv[/URL] good You might want to see if you are running an HTTP module that checks session variables. It will fire on the WebResources.axd file but there will no session for a file of that type and an exception gets thrown but you will never know it because the module swallows it while in runtime for some reason. Only pages with the <% Page %> directive will have session. Check the context and get out of the module will fix it. System.Web.UI.Page page = Context.CurrentHandler as System.Web.UI.Page; if (page == null) { return; } Worked for me!
http://weblogs.asp.net/jan/archive/2005/11/20/431000.aspx
crawl-002
refinedweb
1,332
69.48
Unnamed namespace. More... Unnamed namespace. Convert a Length::Quantity to the equivalent value in another unit. Definition at line 202 of file length.cc. References ns3::Length::Quantity::Unit(), and ns3::Length::Quantity::Value(). Referenced by ns3::Length::Length(), ns3::Length::As(), and ns3::Length::operator=(). Convert a value in one unit to the equivalent value in another unit. fromUnitto toUnit Helper to generate hash values from pairs of Length::Units Definition at line 133 of file length.cc. References FootToMeter(), MeterToFoot(), and NS_FATAL_ERROR. Convert a value in feet to the equivalent value in meters. Definition at line 73 of file length.cc. Referenced by Convert(), and USToMeter(). Convert a value in meters to the equivalent value in feet. Definition at line 85 of file length.cc. Referenced by Convert(), and MeterToUS(). Convert a value from meters to a US Customary unit (inches, feet, yards etc.) Value is converted to feet then scaled to the desired US Customary unit Definition at line 119 of file length.cc. References MeterToFoot(). Convert a value from a US Customary unit (inches, feet, yards etc.) to meters. Value is scaled to feet then converted to meters Definition at line 102 of file length.cc. References FootToMeter().
https://www.nsnam.org/doxygen/namespaceanonymous__namespace_02length_8cc_03.html
CC-MAIN-2021-43
refinedweb
202
52.15
#include <cx/PortAccess.h> char const * const *cxInputPortNames() subroutine cxinputportnames( n, namelist, lengths ) integer n character*(*) namelist(n) integer lengths(n) The storage used to hold this information is allocated and owned by the module control wrapper. Subsequent calls to this routine will overwrite the current contents. Therefore, the module programmer should never attempt to deallocated this storage. The Fortran subroutine cxInputPortNames accepts an array of character variables and fills them with the names of the module's input ports. At most n entries in the array are filled, even if there are more ports. Each port name is null-padded to fill the entry of namelist. The corresponding entry in the lengths array is assigned the true length of the port name, which may exceed the length of the character variable, in which case the caller should try again to get the full port name. The namelist array must have length at least cxInputPortCount, and each variable should be declared long enough to hold the longest port name (plus one for the null termination). Port names that do not fit in a character variable are truncated. The truncated name will not be recognized by other API routines, so on receiving such a name it is best to call cxInputPortNames with a larger character variable array. The namelist and lengths storage must be allocated by the user. To determine independently the number of input ports, use cxInputPortCount.
http://www.nag.co.uk/visual/IE/iecbb/DOC/html/unix-ref/man3/cxinputportnames.htm
crawl-003
refinedweb
237
51.89
Re: BASIC authentication Issues with IE - Part II - Solved but WHY? From: Wade A. Hilmo [MS] (wadeh_at_microsoft.com) Date: 03/27/04 - ] Date: Sat, 27 Mar 2004 08:40:35 -0800 Hi Hector, I've been following this thread for some time. From what I've seen, you have been given good information and advice so far. I would like to clarify a few points to try and help you narrow this down. First and foremost, inetinfo.exe is not integrated with IE in any way. It is the host process for the IIS web server core. It runs on the server side and services requests from all HTTP clients without distinction. In other words, it does not know the difference between a request from IE or from some other HTTP client. In fact, we have many users of IIS that have written their own custom HTTP clients that are not browsers in the traditional sense at all. Second, the way that IIS handles Basic authentiation is, well, basic. Per the HTTP spec, a client authenticates by sending an "Authorization" header in the request. If no authorization header is present, IIS authenticates the request as anonymous. If an authorization header is present and it specified Basic Authentication, and IIS is configured to accept Basic, then IIS authenticates the request as the user in the base64 encoded part of the authorization header. Some other authentication schemes are more complicated, but Basic is just this simple. Third, the credential cache that you keep mentioning has nothing to do with this issue. The credential cache is a performance optimization. It turns out that it can be very expensive (in terms of performance) to ask the operating system to produce a token from user credentials. For this reason, IIS can sometimes remember the token for a particular set of credentials so that, if those same credentials come in on another request, we can reuse the token instead of asking the operating system for a new one. This only affects where we get the token from, and has no affect whatsoever on whether we authenticate or not. Given these three things, I can say with very high confidence that you are looking at an issue with the client, and it has nothing to do with IIS. As such, this post is off topic on this newsgroup. I just look a look at the Microsoft newsgroups in hopes of pointing you to a better place, and unfortunately, it doesn't look like there is one central IE newsgroup. It looks like they are pretty well broken up by version. Lots of folks that read this newsgroup probably have an interest in the client as well, so hopefully somebody reading this can suggest an active newsgroup with a focus on IE. In any case, you are not guaranteed a response by Microsoft on a newsgroup anyway, so your best bet if you want this is to open a case with product support. That said, I can think of several scenarios where any client might not persist - or appear to not persist - credentials between basic authenticated requests. Note that I know nothing about the internals of IE. My only experience with IE is as a user, and seeing the HTTP that it puts on the wire. What follows is just my own personal speculation on this topic. For definive answers, you should be talk to someone who specializes on IE. First off, it's very important that the client not forward basic authenticate credentials indiscriminately. The reason for this is that basic authentication does not protect the password in any way. If you give me your basic authorization header, I can base64 decode it in no time and then I can become you. Because of this, I would expect that no client would preauthenticate ("preauthenticate" is the term used to say that the client forwards the credentials without first seeing a 401 from the server) without having very good reason to believe that the request is going to the same place as some previous request which successfully authenticated. I would speculate that the client would consider the target server, and possibly some part of the URL namespace to make this determination. Also, the client could, if is chooses, implement some logic to authenticate without prompting, based on the realm returned in the basic challenge from the server. In other words, if the server respnse with a 401 and www-authenticate header for basic, it will include a realm. The client could then search its own credential cache and see if it has credentials for that realm without asking the user. I have no idea if IE does this or not. Finally, I can see some timing scenarios where you might get unexpected authentication popups on the client. Specifically, if you make a request that results in a bunch of other requests (ie. if there are frames involved, if there are frames on the page, if there are 301 or 302 redirections, etc.) it's possible that the client makes some number of those requests before it gets back a 401 from any of them. In that case, there is no way that the client could preauthenticate all of the requests. And even if the following 401 responses all contain the same realm (and the client uses this information), it's possible that timing issues in a local credential cache on the client could cause it to prompt for credentials more times that you think it should. I would guess that someone very familiar with HTTP could probably explain the behavior that you are seeing by studying a sniffer trace of the traffic between the client and server. Note that log files may not be sufficient. A sniffer trace is going to show you the actual packets that are hitting the wire, complete with timing information, how the packets are broken up, and sequence numbers. Thank you, -Wade A. Hilmo, -Microsoft "hector" <nospam@nospam.com> wrote in message news:ebwazA8EEHA.1228@TK2MSFTNGP11.phx.gbl... > > "Ken Schaefer" <kenREMOVE@THISadOpenStatic.com> wrote in message > news:eW33$%235EEHA.3064@tk2msftngp13.phx.gbl... > > Hi, > > > > OK, now's where things get a bit interesting. I tried doing what I think > > you're doing: > > a) create a page on myserver.com (page1.asp) which requires Basic > > authentication. > > b) create some links on the page - one link points to page2.asp on the > same > > server. Page2.asp also requires Basic Authentication > > c) Goto page1.asp, enter username/password, get access to page1.asp > > d) Click on the link to page2.asp, but choose "Open in New Window". IE > > automatically sends credentials, and I'm giving access. > > e) Now, I close the second window, and return to my first window. I click > > the link to page2.asp again (but without choosing "open in new window"). > IE > > sends by credentails, and I'm logged in fine. > > In step c, how do you "Goto Page1.asp"? > > Do this by creating a simple Default Home Page with a link to this page1.asp > > If you type the url on the IE address bar, you will not see the problem. > > > Now, you seem certain that this is a bug. I would call Microsoft PSS > > (Product Support Services), and open a call to debug the issue. Certainly > > it's a not common problem (otherwise lots of people be having problems > with > > Basic Authentication), and it doesn't manifest itself on my copy of IE, > nor > > any other copy of IE that I've had before. If there is a bug in IE that > you > > are using, then you will not have to pay - it'll be fixed for free by > > Microsoft. > > Ken, this is has been a long time issue. I've been down this route before, > including calling them on the matter and/or related issue where you are not > losing credentials but it was cached and used again automatically in the > Explorer "Previewing" logic. Like I said, this has been an issue for a long > time and I am not the only one. And you know perfectly well, Microsoft is > will be mum on the subject closed related with security. I am just trying > to figure it out once and for all. I'm not a USER, well yeah of course I > am, I am a user of my own creation as well as hundreds of thousands of > user/customers. So we have to satisfy their reports too. But like I > said, for this particular "lost of authentication", I was one of the few > within our own product reporting it and know I find out "how" it happens. > > I am going to try one more thing and that is put the URL in the Favorites > likes instead. I can't do it know until I close Outlook and all Microsoft > software that has the IE logic integrated with the INETINFO.EXE credential > caching. PS: Do a search for this and you will see it how its all related, > and how there is difference with XP vs. others, how Microsoft solved the URL > shortcut automatic authentication security hole in XP but not others for > some "legacy reason." Yes, incoherent and all very inconsistent which is > what I am trying to get all straight once and for all. > > -- > Hector Santos, Santronics Software, Inc. > > > > > - ]
http://www.derkeiler.com/Newsgroups/microsoft.public.inetserver.iis.security/2004-03/0707.html
crawl-002
refinedweb
1,551
71.85
Are you sure? This action might not be possible to undo. Are you sure you want to continue? Capital Expenditure Decisions Presentation By : Sandip Gaudana Structure n n n n What is ‘Capital Expenditure’ Importance of Cap Ex Decisions Process Appraisal Methods Non Discounting n Discounting n What is Capital Expenditure ? n It is a Decision to invest Current Funds into Long Term Assets In Anticipation of Expected flow of benefits Over a series of years. Types of Cap Ex Decisions n Expansion of existing business Expansion of new business Replacement and modernisation n n Importance n n n n n Growth Risk Funding Irreversibility Complexity Process Project Generation Project Selection Project Evaluation Project Execution Methods of Appraisal Methods Non Discounted Pay Back Period Accounting Rate of Return Discounted Net Present Value Internal Rate of Return Profitability Index Non Discounted Methods n Pay Back Period n Accounting Rate of Return Pay Back Period n n n n Payback is the number of years required to recover the original cash outlay invested in a project. Example : Equal Cash Flow n Assume that a project requires an outlay of Rs 40,000 and yields annual cash inflow of Rs 10,000 for 7 years. The payback period for the project is: n Payback = 40,000 = 4 Years 10,000 Example : Unequal Cash Flow n A project requires a cash outlay of Rs 20,000, and generates cash inflows of Rs 8,000; Rs 7,000; Rs 4,000; and Rs 3,000 during the next 4 years. What is the project’s payback? n 3 Years + 12 * (1,000/3,000) Months n 3 Years, 4 Months Acceptance & Ranking n The project would be accepted if its payback period is less than the maximum or standard payback period set by management. n As a ranking method, it gives highest ranking to the project, which has the shortest payback period. Some Aspects n Certain virtues: n n n Simplicity Cost effective Short-term effects Cash flows after payback ignored Cash flow patterns Administrative difficulties n Serious limitations: n n n Accounting Rate of Return n The accounting rate of return is the ratio of the average after-tax profit divided by the average investment. The average investment would be equal to half of the original investment if it were depreciated constantly. Example (Project Cost Rs. 40,000) ARR = 3,200 * 100 20,000 ARR = 16 % Acceptance Rule n This method will accept all those projects whose ARR is higher than the minimum rate established. if it has highest ARR. n This method would rank a project as number one Discounted Methods n Net Present Value n Internal Rate of Return n Profitability Index Net Present Value n Net present value should be found out by subtracting present value of cash outflows from present value of cash inflows. n Steps Decide Appropriate rate for discounting n Calculate Present Value of Cash Inflow n NPV = PV of Cash inflows – PV of cash Outflow n Example n Project X costs Rs 2,500 now and is expected to generate year-end cash inflows of Rs 900, Rs 800, Rs 700, Rs 600 and Rs 500 in years 1 through 5. The opportunity cost of the capital may be assumed to be 10 per cent. Example Acceptance Rule n Accept the project when NPV is positive (NPV > 0) n Reject the projectwhen NPV is negative (NPV < 0) n May accept the project when NPV is zero (NPV = 0) n The NPV method can be used to select between mutually exclusive projects; the one with the higher NPV should be selected. Some Aspect n NPV is most acceptable investment rule for the following reasons: n n Time value Measure of true profitability n Limitations: n n Involved cash flow estimation Discount rate difficult to determine Internal Rate of Return n The internal rate of return (IRR) is the rate that equates the investment outlay with the present value of cash inflow received after one period. n Internal Rate of Return is the discount rate which makes NPV = 0. Calculation of IRR : Equal Cashflow n n An investment cost Rs 6,000 and provide annual cash inflow of Rs 2,000 for 5 years. Step : 1 Calculation of Factor Factor = Original Investment (6,000) = 3 Avg. Cash flow per year (2,000) n Referring to Annuity table for 5 years @ 18% ( Rs. 3.127) & @ 20 % ( Rs. 2.99) Example (Continued) IRR = A + [(C- O)/(C-D)] * (B-A) 18 + [ (6,254 – 6,000) / (6254-5980)] * (20-18) 18 + ( 254 / 274) * 2 18 + 1.854 IRR = 19.854 % Acceptance Rule n Accept the project when r > k. n Reject the project when r < k. n May accept the project when r = k. Some Aspects n IRR method has following merits: n n n Time value Profitability measure Acceptance rule Tedious & Difficult to understand Mutually exclusive projects n IRR method may suffer from: n n Profitability Index n Profitability index is the ratio of the present value of cash inflows, at the required rate of return, to the initial cash outflow of the investment. Example An investment cost Rs 6,000 and provide annual cash inflow of Rs 2,000 for 5 years, consider discounting rate of 18 % Profitabilty Index = PV of Cash Inflow PV of investment = 6,254 / 6,000 Profitability Index = 1.05 Acceptance Rule n The following are the PI acceptance rules: n Accept the project when PI is greater than one. PI > 1 n Reject the project when PI is less than one. PI < 1 n May accept the project when PI is equal to one. PI = 1 n The project with positive NPV will have PI greater than one. PI less than means that the project’s NPV is negative. Some Aspects n Recognises the time value of money. n A project with PI greater than one will have positive NPV and if accepted, it will increase shareholders’ wealth. n Like NPV method, PI criterion also requires calculation of cash flows and estimate of the discount rate. In practice, estimation of cash flows and discount rate pose problems. Which is more suitable ? Observations…by authors n Most commonly used method for evaluating investment of small size is Pay Back Period n For some of the projects, ARR is used as principal method and Pay Back is supplementary. n Discounted Techniques are gaining importance in Large investments having substantial outlay. Findings of a Survey n Survey by U Rao Cherukeri revealed the following n DCF methods have gained importance over a period of time ( Particularly the IRR) n ARR & PBP are widely used as supplementary evaluation methods. n WACC is commonly used as discount rate. Most often used in india is 15 % Ranking in US 1. 2. 3. 4. 5. Internal Rate of Return (IRR) Net Present Value (NPV) Accounting Rate of Return (ARR) Pay Back Period (PBP) Profitability Index (PI) ? Thank You !!!
https://www.scribd.com/presentation/9607306/5-Capital-Expenditure-Decisions-19-4-06
CC-MAIN-2018-13
refinedweb
1,156
56.89
for connected embedded systems wait4() Wait for one or more child process to change its state Synopsis: #include <sys/types.h> #include <sys/wait.h> pid_t wait4( pid_t pid, int * stat_loc, int options, struct rusage * resource_usage ); Arguments: - pid - The set of child processes that you want to get status information for: - less than -1 -- any child process whose process group ID is equal to the absolute value of pid. - -1 -- any child process - 0 -- any child process whose process group ID is equal to that of the calling process. - greater than 0 -- the single child process with this ID. -4() function suspends execution of the calling process until status information from one of its terminated child processes is available, or until the delivery of a signal whose action is either to terminate the process or execute a signal handler. If status information is available prior to the call to wait4(), not available for any process specified by pid, a value of zero is returned. On delivery of a signal waitpid() returns -1, and errno is set to EINTR. Errors: - ECHILD - The calling process has no existing unwaited-for child processes that meet the criteria set by pid. - EINTR - The function was interrupted by a signal. The value of the location pointed to by stat_loc is undefined. - EINVAL - The value of the options argument isn't valid. Classification: See also: exit(), fork(), pause(), wait(), wait3(), waitid(), waitpid()
http://www.qnx.com/developers/docs/6.3.2/neutrino/lib_ref/w/wait4.html
crawl-003
refinedweb
236
61.97
Discussion Board for collaboration related to QlikView App Development. Hi everyone, i have a combination chart with 2 Dimensions: 1. Product group 2. Month Additionally i have 2 Formulas: 1. Sum of product values (show as bars) 2. Sum of product marginal return (show as line) The bars are displayed correctly. One bar for each month in one bar-group for each product-group. Here is the problem: The values of the line (formula 2) are not horizontally aligned in the centers of the single bars but in the centers of the bar-groups. So the single line-values for every single month are all together displayed in one vertical line above the product-group. How can i get the chart to display the values of the line where they really relate to: the month - not the product-group? Thanks to all for your help This is possibly something to play with Presentation or Axis. Can the application be uploaded with sample data? Regards, tresesco I'd like to upload a .qvw and .xls file. How can i do this? Looks like the "insert media"-button only allows to upload pictures or something like this. instead of clicking Quick Reply, click on Reply, you would find three tabs there, go to second tab(Options); there you would find the option for attachment. Here you are and the sample application... There was a thread on something very similar yesterday. It looks like a QlikView bug to me. The two suggested workarounds were to use either a trellis chart or to concatenate the two dimensions into one. One extra complication with concatenating dimensions in your case is that the line would then be drawn between groups, not just within groups. That can be fixed with an appropriate background color expression though. Both workarounds attached. Thanks for your help. Both workarounds are possible and work like they expected. I'd prefer the solution with the concatenated dimensions. Could you please post the background expression which is needed, because i can't open the attached sample file (at the moment i'm testing qlikview for our company with the personal edition)? In which field of the property-window do i have to set the expression? Is there a way beyond to define dynamic bar groups within 1 dimension? Again thanks for your help!! Works well! Thank you!
https://community.qlik.com/t5/QlikView-App-Development/Horizontal-alignment-of-line-values-in-Combination-Chart/m-p/164970
CC-MAIN-2019-51
refinedweb
393
67.04
Problem with sets and Unicode strings Discussion in 'Python' started by Dennis Benzinger, Jun 27, 2006. Want to reply to this thread or ask your own question?It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum. - Similar Threads html, unicode and character setsjb, Mar 28, 2006, in forum: HTML - Replies: - 5 - Views: - 402 - Benjamin Niemann - Mar 29, 2006 Strings, Strings and Damned StringsBen, Jun 22, 2006, in forum: C Programming - Replies: - 14 - Views: - 797 - Malcolm - Jun 24, 2006 problem using sets strings and namespacesJBorges, Jul 29, 2005, in forum: C++ - Replies: - 5 - Views: - 329 - JBorges - Jul 29, 2005 compare unicode to non-unicode stringsAsterix, Aug 31, 2008, in forum: Python - Replies: - 5 - Views: - 737 - Matt Nordhoff - Aug 31, 2008 File names, character sets and UnicodeMichal Ludvig, Dec 12, 2008, in forum: Python - Replies: - 1 - Views: - 325 - Marc 'BlackJack' Rintsch - Dec 12, 2008
http://www.thecodingforums.com/threads/problem-with-sets-and-unicode-strings.359091/
CC-MAIN-2014-49
refinedweb
166
63.77
![if !(IE 9)]> <![endif]> The analyzer has detected a globally declared variable with a short name. Even if it won't cause any errors, it indicates a bad programming practice and makes the program text less comprehensible. An example: int i; The problem about short variable names is that there is a large risk you'll make a mistake and use a global variable instead of a local one inside a function's or class method's body. For instance, instead of: void MyFunc() { for (i = 0; i < N; i++) AnotherFunc(); .... } the following must be written: void MyFunc() { for (int i = 0; i < N; i++) AnotherFunc(); .... } In cases like this, the analyzer will suggest changing the variable name to a longer one. The smallest length to satisfy the analyzer is three characters. It also won't generate the warning for variables with the names PI, SI, CR, LF. The analyzer doesn't generate the warning for variables with short names if they represent structures. Although it's a bad programming practice as well, accidentally using a structure in an incorrect way is less likely. For example, if the programmer by mistake writes the following code: struct T { int a, b; } i; void MyFunc() { for (i = 0; i < N; i++) AnotherFunc(); .... } it simply won't compile. However, the analyzer does get angry about constants with short names. They cannot be changed, but nothing prevents one from using them in an incorrect check. For example: const float E = 2.71828; void Foo() { S *e = X[i]; if (E) { e->Foo(); } .... } The fixed code: const float E = 2.71828; void Foo() { S *e = X[i]; if (e) { e->Foo(); } .... } But an even better way is to use a longer name or wrap such constants in a special namespace: namespace Const { const float E = 2.718. ...
https://www.viva64.com/en/w/v707/
CC-MAIN-2020-50
refinedweb
302
73.07