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
React Native's built-in touch Gesture Responder system has given us all some performance problems on both iOS and Android platforms. Using the open-source solution react-native-gesture-handler is a great way to overcome this and add gestures in our React Native apps. Let us add this feature to the Instagram clone Feed screen. If you have been following this series so far, you'll know which screen I am talking about right now, and you'll have already installed the npm package required to use this library as well as other settings to make it work. You can skip the first section below called installing dependencies. If you are reading about this for the first time, do not worry. There is nothing new, and in the next section, I have added all the necessary steps to install react-native-gesture-handler and make it work with your React Native app. The gesture that I'm going to cover is a feature called "pinch to zoom." It requires two user fingers to use a pinch gesture to initiate a zoom effect. Installing dependencies To start, make sure you install the latest version of react-native-gesture-handler that supports React Native 60+ apps. If you are working with lower versions of React Naive, please give the official documentation a read to follow correct methods to set this library. Note: If you have installed and set up the react-navigation library as part of your app, you do not have to install and set up the Gesture Handler library again. yarn add react-native-gesture-handler For the current demo, since you are using the react-native CLI, only Android users have to add the following configuration inside ios/ directory from the terminal and run pod install. Everything is set up, so all you have to do is run the build command again, such as for iOS: react-native run-ios and for Android: react-native run-android. That's all for setup. Creating a PinchGestureHandler component A pinch gesture is a continuous gesture that is recognized with the help of PinchGestureHandler from react-native-gesture-handler. This handler tracks the distance between two fingers and uses that information to scale or zoom on the content. It gets activated when the fingers are placed on the screen and when their position changes. Since the Feed screen right now has many posts, each containing an image with some text, let's create a separate component file called PinchableBox.js inside the components/ directory. Import the following dependencies that are required to create this component. The Animated library is required to scale and transform the image from its given width and height. Another thing you have to notice is the State object that is also known as the handler state. import React from 'react' import { Animated, Dimensions } from 'react-native' import { PinchGestureHandler, State } from 'react-native-gesture-handler' Next, define a functional component called PinchableBox and export it. const PinchableBox = () => { // ... rest of the code } export default PinchableBox That's it for setting up the component. Adding image URI as a prop The source of the image is going to come from the Feed screen component. In this section, let us replace the Image component in the Feed screen with the PinchableBox component. The PinchableBox component is going to have an Animated.Image which is going to serve the purpose of displaying images in each post on Feed screen as well as perform scale animations. In PinchableBox.js file modify the component like the following snippet. The prop imageUri is what this component expects and it is used as the source URI of the image to display. const PinchableBox = ({ imageUri }) => { return ( <Animated.Image source={{ uri: imageUri }} style={{ width: screen.width, height: 300, transform: [{ scale: 1 }] }} ) } Setting the value of the scale to one is going to display the image as usual. Also, the width of the image component is calculated according to the screen of the device's width, using Dimensions from react-native. Add the following line in the same snippet above the functional component. const screen = Dimensions.get('window') Next, go the screens/Feed.js and import the PinchableBox component. // ... rest of the import statements import PinchableBox from '../components/PinchableBox' Next, replace the existing Image component in the render method with the following snippet: <PinchableBox imageUri={item.postPhoto.uri} /> It just needs one prop to be passed for now, and that is the image URI. Handling state event changes Animated uses declarative relationships between input and output values. For single values, you can use Animated.Value(). It is required since it's going to be a style property initially. Inside the PinchableBox component, set scale like below to modify it through Animations. scale = new Animated.Value(1) Next, in the style property of Animated.Image, change the value of scale to this.scale. transform: [{ scale: this.scale }] Now, wrap the Animated.Image with PinchGestureHandler. This wrapper component is going to have to props. > Let us define the onPinchEvent first, before the return statement. This event is going to be an Animated event. This way gestures can directly map to animated values. The animated value to be used here is scale. Passing useNativeDriver as boolean true allows the animations to happen on the native thread instead of JavaScript thread. This helps with performance. onPinchEvent = Animated.event( [ { nativeEvent: { scale: this.scale } } ], { useNativeDriver: true } ) Let us define the handler method onPinchStateChange that handles the state change when the gesture is over. Each gesture handler is assigned a state that changes when a new touch event occurs. There are different possible states for every handler, but for the current gesture handler, ACTIVE is used to check whether the event is still active or not. To access these states, the object is required to import from the library itself. The Animated.spring on scale property has toValue set to 1 which is the initial scale value. onPinchStateChange = event => { if (event.nativeEvent.oldState === State.ACTIVE) { Animated.spring(this.scale, { toValue: 1, useNativeDriver: true }).start() } } Here is the output of all code written so far. Here is the code for the complete PinchableBox component. import React from 'react' import { Animated, Dimensions } from 'react-native' import { PinchGestureHandler, State } from 'react-native-gesture-handler' const screen = Dimensions.get('window') const PinchableBox = ({ imageUri }) => { scale = new Animated.Value(1) onPinchEvent = Animated.event( [ { nativeEvent: { scale: this.scale } } ], { useNativeDriver: true } ) onPinchStateChange = event => { if (event.nativeEvent.oldState === State.ACTIVE) { Animated.spring(this.scale, { toValue: 1, useNativeDriver: true }).start() } } return ( > ) } export default PinchableBox Conclusion The Feed screen implemented is from one of the templates from Crowdbotics' react-native collection. We use UI Kitten for our latest template libraries. You can modify the screen further or add another component that takes care of counting likes or comments. Find more about how to create custom screens like this from our open source project here.
https://blog.crowdbotics.com/add-pinch-to-zoom-using-react-native-gesture-handler/
CC-MAIN-2021-17
refinedweb
1,148
57.77
CodePlexProject Hosting for Open Source Software In Short: Is there some way to use ClientBase<T> to append URITemplate bits to an already defined RESTful service client endpoint address? Let's assume there is some REST interface out there providing lots of useful(?) information about chocolate: ../chocolates/products ../chocolates/products/colors/white To create a client for the endpoints above, I write something like this service contract: [ServiceContract] public interface IChocolatteClient { [OperationContract, WebGet(UriTemplate="chocolatte/products")] XElement GetProducts(); [OperationContract, WebGet(UriTemplate="chocolatte/products/colors/{color}")] XElement GetProducts(string color=""); } What I really want though, From a code perspective, is to write the two URI's as one function with an optional argument: [ServiceContract] public interface IChocolatteClient { [OperationContract, WebGet(UriTemplate="chocolatte/products/colors/{color}")] XElement GetProducts(string color = ""); } I See the "color" argument as an optional argument, and would like to be able to simply use some simple logic in my implementation, such as: public class ChocolatteClientRest : ClientBase<IChocolatteClient>, IChocolatteClient { XElement GetProducts(string color = "") { var channel = CreateChannel(); return channel.GetProducts(color); } } This, however, does not work, because I need some magic from the UriTemplate that can let me indicate that one bit of the URI template (namedly the "colors/{color}") needs to be conditional. Is this doable in any way? Alternatively, is it possible to append the "colors/white" argument during runtime in some smart way? I am assuming that "deeper down", I can probably write an interceptor, or reimplement the channel object to support dynamic URI's, but that is a messy thing to do, and if I can get away with it by using ClientBase<T>, the solution will have a much higher degree of maintainability. In advance, thanks for reading! From Norway Please don't use ClientBase<T> to access REST services. One of the benefits of using REST over HTTP is you get to take full advantages of HTTP as a application protocol and get away from an RPC architecture. By using ClientBase<T> you are tunneling RPC over what is supposed to be RESTful. The new HttpClient is really quite easy to use and you can achieve very similar results quite simply, public class ChocolatteClientRest { HttpClient _HttpClient = new HttpClient(""); Dictionary<string,string> _Bookmarks = new Dictionary<string,string>() { {"products","chocolatte/products"}, {"productsbycolor","chocolatte/products/colors/{color}"} }; XElement GetProducts(string color = "") { string url; if (color == "") url = _Bookmarks["products"]; else url = _Bookmarks["productsbycolor"].Replace("{color}", color); var response = _HttpClient.Get(url); return XElement.Load(response.Content.ContentReadStream); } } Thank you for your response, Darrel. In my understanding, WCF was, and is designed in order to let the developers "forget" protocol. I need some more arguments as to why I should leave the comfort of WCF behind and work on a specific protocol (http in RESTful today, who knows what in the future?) . You say that the RPC architecture in this situation is bad - I'm not saying I disagree with you, could you give me a few reasons why? I find it to be beneficial for our project to have a common way (across teams) of configuring services in the solution that we are writing. We serve and consume services, both RESTFul and SOAP endpoints. By adopting WCF, everyone in my team knows, or can easilly look up details on how to set up endpoints, security, message lenghts, etc, regardless of transport. Isn't that the whole point of WCF? Using ClientBase<T>, I have the same structure in code, as does WCF in general. I admit, I would like to see a few more http options available to me, such as being able to control http-caching, custom headers, etc (i.e. in a HttpClientBase<T> implementation of a ServiceContract), but the cleaniness and "well-documentedness" of WCF far outweigh this so far. Is there, something in the ClientBase<T> RESTful implementation that I should be aware of that makes you suggest your solution? I think Darrel's point is that HTTP is an application protocol that is based on resources and HTTP methods, not on classes and class methods. ClientBase<T> is designed around the fundamental idea that you are invoking a method on the server. When you use it you are working in a model that is protocol agnostic and thus you are not really taking advantage of HTTP and are coupling to implementation details. HttpClient however is designed entirely around HTTP, thus things like working with resources, multiple representations, hypermedia or etags are much more natural. It's all about tradeoffs. I do remember you showing us some neat stuff, such as using exactly the same resource location to retrieve different types of data (text vs an image) simply by specifiying the http-accept type, but in my world, you were still invoking a method call; you just chose to put some of the parameters in the http header. Wouldn't this be equally achievable in WCF by use of "HttpRequestHeader" of sorts, or simply: [ServiceContract] public interface IPersonServiceClient { [OperationContract, WebGet(UriTemplate="people/{personId}", RequestHeader="Accept: text/xml")] public XElement GetPersonData(int personId); [OperationContract, WebGet(UriTemplate="people/{personId}", RequestHeader="Accept: image/jpeg")] public Object GetPersonImage(int personId); } The above example is just a suggestion, of course, it's not real. The overhead given by WCF probably warrants the HttpClient object in many cases, however, I dont see this as something we as developers have to choose between; we should be able to get that cake AND eat it too! Digital Dias, Using WCF in a transport agnostic way is like cake. REST is like bacon. Both awesome, but not together. Pick the right one for the right occasion. Very interesting thread when it comes to distributed application development. I'm with digitaldias because I bought into the fact that WCF is suppose to be transport agnostic. I dove into Silverlight and WCF because Silverlight was a fully graphical interface via the web, and WCF was something that Microsoft put milllions and millions of dollars into to create service endpoints with a vast arrary of features. Now I've heard Ron Jacobs/Microsoft, as well as Don Demsak/Tellago (Philly.Net Code Camp) both say that (proper) WCF Services is something that the market is not embracing, and that REST is the interface of choice..... Sure REST is simple and easy, but is it really for LOB applications that demand the security and robustness required for an enterprise? Does OData/WCF Data Services mean that professional LOB application will leave an entire database wired to the web? (Yes i know this can be limited, but that is not what is going to happen..) Silverlight needs to talk to services in order to retrieve data - why does WCF RIA Services has to have a custom binding in order to achieve it transport requirements? If MS is all about applications, then why is MS not concentrating on allowing their flag ship product to create a connection with service endpoints that are secure, reliable, and feature rich with WS*. The tcp implementation into Silverlight is a train wreck that no serious solutions architect will consider, so we are going to go with HTTP? Really? Come on MS - you can do better than this. With Bob M. gone, can we please have somebody step up the plate and make the hard decisions about how to move forward on this! ScottGu where are you! I want Silverlight, and I want proper WCF with all the features and capabilities that it has. I realize that this has turned somewhat into a rant but either HTTP steps up to the bar, or Silverlight gets the ability to invoke web services with the capabilities it needs. I don't really care which way, but somebody better get a direction on this, or somebody will step in and we'll all have to live the HTML saga overagain with HTML5 and browser incompatabilities.. (serious have we not learned yet that cross vendor compatability is simply not possible - SQL, Java, HTML, etc. it's 10am, and I'm ready for drink! argghhhh! Codputer, You ask an excellent question. Here are a few observations. - You don't need to deliver an application via a web browser to take advantage of the architecture of the web. - WCF supports transport agnostic development, but HTTP is not a transport protocol, it is an application protocol. - REST is only a valid architecture for certain scenarios. WCF based RPC is sometimes a better option. - REST is definitely not easy. - If banks can deliver bank account information to home users over the web, then it's secure enough for 99% of LOB applications - OData/WCF Data services should never be the primary backend for a LOB application IMHO. LOB applications may consume data from OData sources and may even do updates to it, but I do not believe that OData should be used for a LOB application backend. - WCF RIA Services violates my last assertion. IMHO it is just architecturally wrong. - If you really must host your app in a browser, Silverlight should be able to exist as a completely RESTful client using HTTP. You just need the right architecture. - Don't let any technology vendor define your architecture. Don't wait for MS to come up with an end-to-end technology stack. Design your architecture as per your requirements and plug in the right technology in the right place. - If you think the world of HTML has been bad so far, just wait, the pain is only just beginning. DarrelMiller wrote: Digital Dias, Using WCF in a transport agnostic way is like cake. REST is like bacon. Both awesome, but not together. Pick the right one for the right occasion. That just took the air out of me. I thought this was a professional forum. If you can't argue your point better than that, you shouldn't be posting. I see no benefit from this kind of reply whatsoever. Any moderator out there can just kill this thread please, I never meant for it to become this. @digitaldias both models are supported. Which one you choose is really a question of tradeoffs. When you choose the contract / client model you get something that feels very much like you are invoking a class and a method hence the RPC nature. The upside is you get compile time safety, intellisence, etc. The downside is you limit yourself in terms of fully leveraging HTTP as the model makes a whole bunch of assumptions of how it uses HTTP and does eveything to shield you from the underlying application layer protocol. It also creates coupling to implementation details on the server, something that HTTP was designed specifically to avoid. So if you if you want to take advantage of HTTP to it's fullest and yield the scalability, evolvabiltiy and simplicity benefits that the founders of HTTP wanted, you will find that model falls down quickly. If talking across multiple transports / transport independence is more important for you then those specific benefits than using client base is the right choice. Glenn What I'm trying to ask is: Why should I implement httpClient over WCF? Are there performance benefits, or design benefits that outweigh the use and/or simpllicity of the WCF architecture? (btw, Darrel: HTTP = Hyper Text TRANSFER Protocol, I hope you can forgive me for interpreting this as a transport protocol :) ) yes, sure. There are benefits: all the system properties induced by proper use of HTTP. E.g. scalability, maximized decoupling, etc. (check the REST vs. RPC debates on the Web on this). Since you can't do proper HTTP with WCF now, Glenn started the WCF HTTP effort (and, doh, - am I happy he did :-) I am with Darrel, BTW: "Pick the right one for the right occasion." -- Understanding the trade offs involved when choosing connector styles is the essence of good networked system design. Jan HttpClient was designed for sole purpose of interacting with distributed systems using the HTTP protocol. WCF enables you to create an RPC based application protocol . If you know you are going to be using HTTP, then HttpClient is going to be more efficient because you avoid the unnecessary layers of abstraction. You also get better control because the HTTP infrastructure is not hidden from you. Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
https://wcf.codeplex.com/discussions/244603
CC-MAIN-2017-09
refinedweb
2,075
53.31
This. - mark abortgo() as no-return function for GCC Index: engine/board.h =================================================================== RCS file: /cvsroot/gnugo/gnugo/engine/board.h,v retrieving revision 1.9 diff -u -p -r1.9 board.h --- engine/board.h 12 Apr 2004 15:22:27 -0000 1.9 +++ engine/board.h 19 Apr 2004 01:17:13 -0000 @@ -393,7 +393,11 @@ void simple_showboard(FILE *outfile); /* Our own abort() which prints board state on the way out. * (pos) is a "relevant" board position for info. */ -void abortgo(const char *file, int line, const char *msg, int pos); +void abortgo(const char *file, int line, const char *msg, int pos) +#ifdef __GNUC__ + __attribute__ ((noreturn)) +#endif + ; #ifdef GG_TURN_OFF_ASSERTS #define ASSERT2(x, i, j)
http://lists.gnu.org/archive/html/gnugo-devel/2004-04/msg00119.html
CC-MAIN-2014-15
refinedweb
118
68.36
In .NET Framework 4 we have introduced a streamlined subset and more compact version of the .NET Framework called the Microsoft .NET Framework 4 Client Profile (aka NET4 Client Profile). The Microsoft .NET Framework 4 which is the Full Framework (aka NET4 Full) still exists and it is a superset of the Client Profile. Hopefully folks have seen Soma’s blog announcing the availability of Visual Studio 2010 , .NET Framework 4 and .NET Framework 4 Client Profile. I have discussed some of the beta features of Microsoft .NET Framework 4 Client Profile in details in my previous Beta 1 blog and Beta 2 blog posts. In this post I wanted to highlight some of the key changes from our previous Beta 2 public release and reiterate some of the important features How big is Client Profile? Below are the redistributable download size improvements since NET 3.5 SP1. As you can see we have made significant improvements. Note that if you are downloading from the Web, the actual download size could be smaller since some components may already be on your machine (for example, Software Rasterizer (rgb9rast) , etc ) What is new in NET4 Client Profile RTM vs. Beta 2 ? Move System.ComponentModel.DataAnnotations.dll from the full framework to Client Profile Some additional file moves below. Since WIC is already included in XP SP3, Vista, Windows 7, and installed with .NET 3.5 SP1 it made sense to remove it and decrease setup size for almost all users that do not need it. Folks that need this component (mainly XP SP2/SP1 and Windows 2003 users that do not have NET 3.5 SP1 installed) can install it from here: 32 bit: 64-bit: Note that if WIC is missing, NET4 setup will fail. We expect that very few machines will require WIC. Some apps that chain-install the NET4 framework may need to either block on WIC or chain-install WIC. These are assemblies that although included in the NET4 Client Profile runtime they are not meant to be used by NET4 Client Profile applications. These assemblies are not included in the Reference Assemblies folder and they are not accessible/visible by Visual Studio 2010. NET4 currently includes only one such assembly: These are APIs/namespaces that although included in the NET4 Client Profile runtime they are not supported and not meant to be used by NET4 Client Profile applications. The main reason these assemblies are not supported in the Net4 Client Profile is that they have dependencies on assemblies from NET4 Full so your Client Profile app may crash if you do use them on machines that only have Client Profile installed. In RTM, these APIs/namespaces are “grayed out” from the Reference Assemblies and are not accessible/visible in Visual Studio 2010. Note that if your app is targeting the NET4 Full you will be able to access these APIs/namespaces. In System.Web.Services, the following namespaces are “greyed out” for NET4 Client Profile: - File moves: We moved few files between Client Profile to Extended (Full). Most notably: - Removed Windows Imaging Components (WIC) from NET4 setup package (Full & Client). - Black assemblies: - ISymWrapper - Grey APIs: - System.Web.Services.WebService - System.Web.Services.Description.BasicProfileViolation - System.Web.Services.Description.BasicProfileViolationCollection - System.Web.Services.Description.BasicProfileViolationEnumerator - System.Web.Services.Description.ProtocolImporter - System.Web.Services.Description.ProtocolReflector - System.Web.Services.Description.ServiceDescriptionImporter - System.Web.Services.Description.ServiceDescriptionReflector - System.Web.Services.Description.SoapExtensionImporter - System.Web.Services.Description.SoapExtensionReflector - System.Web.Services.Description.SoapProtocolImporter - System.Web.Services.Description.SoapTransportImporter - System.Web.Services.Description.WebServicesInteroperability - System.Web.Services.Discovery.ContractSearchPattern - System.Web.Services.Discovery.DiscoveryDocumentLinksPattern - System.Web.Services.Discovery.DiscoveryDocumentSearchPattern - System.Web.Services.Discovery.DiscoveryRequestHandler - System.Web.Services.Discovery.DiscoverySearchPattern - System.Web.Services.Discovery.DynamicDiscoveryDocument - System.Web.Services.Discovery.ExcludePathInfo - System.Web.Services.Discovery.XmlSchemaSearchPattern - System.Web.Services.Protocols.HtmlFormParameterReader - System.Web.Services.Protocols.MimeParameterReader - System.Web.Services.Protocols.ServerProtocol - System.Web.Services.Protocols.ServerProtocolFactory - System.Web.Services.Protocols.ServerType - System.Web.Services.Protocols.SoapServerMessage - System.Web.Services.Protocols.SoapServerMethod - System.Web.Services.Protocols.SoapServerProtocol - System.Web.Services.Protocols.SoapServerProtocolFactory - System.Web.Services.Protocols.SoapServerType - System.Web.Services.Protocols.UrlParameterReader - System.Web.Services.Protocols.ValueCollectionParameterReader - System.Web.Services.Protocols.WebServiceHandlerFactory What is new in Visual Studio 2010 for NET4 Client Profile Since Beta 2 we made some small but important improvements to the he VS 2010 RTM UI: (You can read about the changes we in Beta2 in my Beta 2 blog ) A) Starting with VS 2010 RTM, the “Add Reference” indicates the target framework that assemblies are filtered against. B) The VS 2010 RTM toolbox now clearly indicates if 3rd party controls are not available for the selected profile. How to use Client Profile in Visual Studio 2010 Visual Studio 2008 introduced multi-targeting to allow application to target 2.0 and 3.x versions of the .NET Framework. VS 2010 has improved multi-targeting and starting in VS 2010 Beta2 many of the Client projects are targeting the NET4 Client Profile by default. I also discussed this in my Beta 2 blog . Projects that target NET4 Client Profile by default These projects starting with VS 20101 Beta2. Mixed-target scenarios using Class Library may present interesting challenges. Read more below. How to retarget your C#/VB.Net project To change targeting of your project, open the project properties, select the "Application" page, and change the “Target framework” drop-down. C# project example: VB project example (Project Properties > Compile tab > “Advanced Compile Options…”): Note that if you right-click the project and select “Add References”, the dialog shows only the .NET Framework assemblies that are part of the selected a project targeting the Client Profile has a reference to a .NET assembly that is not included in the "Client List", Visual Studio displays compile-time errors in the Error List. How to change targeting for other projects Some other VS 2010 projects such as Managed C++ (C++/CLI) still target the Full Framework by default. VS 2010 unfortunately does not provide UI to change the targeting. Fortunately, you can still edit the project file manually in order to change the profile targeting. To do so: a) Right click “Unload Project” b) Right-Click “Edit <project_name>” c) Set the appropriate project property to target Client Profile. e.g. <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> <TargetFrameworkProfile>Client</TargetFrameworkProfile> d) Right click “Reload Project” In addition, for these projects, notice that VS does not create an <app.config> file for your project. Note: If your project does not add references or access assemblies that are included in the Full Framework but are not part of the Client Profile, there is nothing to worry about. Your app will run on machines with either NET4 Client Profile or Full Framework just fine. Otherwise, if you do access assemblies from the Full Framework, you should add <app.config> to indicate to CLR not to load your app if it is launched on the NET4 Client Profile. E.g. add this: <?xml version="1.0"?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> </startup> </configuration> If you don’t do so, your app may crash at random when it needs to load the assemblies that are missing from the Client Profile. Deployment The project Publish property page allows you to select the prerequisite needed for your ClickOnce deployment. VS 2010 automatically selects the correct profile (Client Profile or Full) depending on your primary project target. Setup and Deployment Projects The same prerequisite dialog from above appears when you create “Setup and Deployment” project (under “Add New Project”/“Other Project Types”). The NET4 Client Profile prerequisite entry is checked by default in this case. If you create a new “Visual Studio Installer” setup project (under “Setup and Deployment“) and add the output of your NET4 Client Profile to it (Right-Click ->“Add”-> “Project Output…”’ select “Primary output”) , VS2010 adds a new “Launch Condition”. (Right-click on your new Setup project and then do “View->Launch Conditions”) By default VS2010 will add NET4 Client Profile as a launch condition. What this means is that once all prerequisites are installed and before the main installation launches, setup checks whether all the launch conditions are met. If not, setup blocks and displays an error message. Testing NET4 Client Profile applications VS 2010 itself requires the NET 4 Full in order to run and it therefore install NET 4 Full. If your target NET4 Client Profile, it is highly recommended that you test your application on a separate machine that only includes NET4 Client Profile. Common Questions & Issues with NET4 Client Profile 1. How can I select the .NET Profile in the “New Project” dialog? When you create new project in VS 2010, the “New Project” dialog does not indicate if the new project you are about to create is targeting Client Profile or Full. You can always go to the project Properties (see above) and change the target if you like. 2. I cannot find an assembly in “Add Reference” dialog The “Add Reference” .NET tab dialog only shows the .NET Framework assemblies that are part of the selected profile. So some assemblies, such as System.Web.dll are not included in NET4 Client Profile and will only show if you target the Full framework. If you must use System.Web.dll you need to retarget to the Full framework. Starting with VS 2010 RTM, the “Add Reference” indicates the target framework that assemblies are filtered against. 3. My project cannot compile when I reference a Class Library You may encounter mixed-target scenarios: for example, when your Client Profile app adds a reference to a Class Library that is targeting the Full Framework (which it targets by default). You should be able to successfully build such solutions, as long as the Class Library does not use references to assemblies that only exist in the Full Framework. If it does, you may get warning/errors that are not completely clear. For example you may see an error in your Client Profile app saying: “The type or namespace name 'ClassLibrary1' could not be found (are you missing a using directive or an assembly reference?)” This error is not clear because the class library exists and can be compiled when it is compiled by itself. However, when MSBuild tries to resolve the transitive closure of the Client Profile project, it cannot find the Full Framework assembly that is referenced by the Class Library. In this case it is better to look at the generated warnings which are more informative: “The referenced assembly " …<your assembly>.." could not be resolved because it has a dependency on ""…<some assembly only available in Full Framework>…” which is not in the currently targeted framework ".NETFramework,Version=v4.0,Profile=Client". Please remove references to assemblies not in the targeted framework or consider retargeting your project.” 4. My controls or 3rd party controls is now showing in the VS 2010 toolbox Some VS 2008 3rd party Winforms controls will not work with VS 2010 NET4 Client Profile projects. The reason is that some of these controls have do not have separate design-time and run-time components and have dependencies on assemblies that are in the Full Framework (for example dependency on System.Windows.Forms.Design.dll which is Full). In VS 2010 RTM we made some changes to make it easier for developers to realize that. Per the image below you can see that the VS 2008 DevExpress Winforms control are not showing in VS 2010 Toolbox and instead you see the message “Controls in this category are unavailable for the .NET Framework 4 Client Profile. To change this setting, open the Project Properties windows.” The Xceed VS 2008 controls on the other hand do have separate design-time and run-time components and works fine in VS 2008 and VS 2010. The good news is that many of the control vendors plan to release update to their control soon after VS 2010 RTM. Until such updates are available you need to retarget your project to NET4 Full if you must use these controls. 5. What should I do if a component that I need is not in NET4 Client Profile? Your first option is to try to find a workaround by modifying your code to use a component that is included in NET4 Client Profile. If this is not possible retarget your project to NET4 Full. As mentioned before, this is not ideal as most desktops are ikely to only have NET4 Client Profile so your app would need to chain-install NET4 full or block your app setup on NET4 full being present. 6. I want to write a custom WinForms control, what do I need to do for it to work with NET4 Client Profile? When developing Windows Forms control libraries, it is necessary to separate the runtime code from the control designers in order to target the new Client Profile. If the assembly references classes that exist in the Full framework but not in the Client Profile, the project will not compile successfully. Custom control designers usually inherit from the System.Windows.Forms.Design.ControlDesigner class in System.Design.dll, which is not included in .Net Framework 4 Client Profile. We posted a guide that can walk you through the steps of creating a Windows Forms control that can be used in the .NET Framework 4 Client Profile. See: Note that WPF custom controls do not inherit from classes in System.Design.dll and do not have this issue. 7. What’s the deal with <app.config> file ? If you change the project to target the Full Framework, VS will add a configuration file (<app.config>) that declares the application as a "full" application. This enables the CLR loader to block any NET4 apps that target full on machines that only have the Client Profile. In this case, the CLR prompts the user to install NET4 full. E.g. you may see this dialog: Note that in NET4 Beta1 and NET3.5 SP1 Client Profile if the <app.config> was missing the CLR the assumption was that you targeted the Full Framework. This is now reversed. In other words, if your NET4 app is missing <app.config> , by default the CLR assume that your app is targeting NET4 Client Profile! so, your app may crash at random when it needs to load the assemblies that What components are new in NET4 Client Profile RTM? This has not significantly changed since Beta2, so read my Beta 2 blog. We did make some tweaks however in RTM (and RC), most notably: - Developers who need to use System.Web.HttpUtility in their client apps and had to reference System.Web.dll and therefore target NET4 full (System.Web.dll is in Full) , can now target the NET4 Client Profile by using the new System.Net.WebUtility class which is in System.dll (System.dll is in NET4 Client Profile). System.Net.WebUtility includes HtmlEncode and HtmlDecode. Url encoding can be accomplished using the System.Uri class (also in System.dll). - Files moved from Client to Extended (Full): - csc.rsp and vbc.rsp - Files moved from Extended (Full) to Client: - System.ComponentModel.DataAnnotations.dll - Microsoft.CSharp.Resources.dll and System.Dynamic.Resources.dll - InstallUtil.exe, Installutil.exe.config and InstallUtillib.dll Enhancements in NET4 Client Profile vs. NET 3.5 SP1 Client Profile This has not changed since Beta2, so read my Beta 2 blog . What’s in and what’s not included in the Client Profile? Other than the APIs that were “Grey” out in RTM (and RC) and the tweaks mentioned above, we did not make other significantly changes since Beta2, so read my Beta 2 blog. Where can I get the NET4 Client Profile? You can get .NET Framework 4 from here: - dotNetFx40_Client_x86_x64.exe (41 MB): This is the Client Profile SKU that you must install on any supported 64-bit OS. This will also install on any supported 32-bit OS. Your app could run in WOW64 if it was compiled w/ "32-bit" flag or as 64-bit if you compile with "AnyCPU" or "64-bit" flags. If you are redistributing the Client Profile with your application you most likely want to redist this package as it can install on both 32 and 64 bit OS’s. - dotNetFx40_Client_x86.exe (28.8 MB): This is the Client Profile SKU that you could use to install on any supported 32-bit OS. Choose this only if all your users are running 32 bit OS. (in most times this will not be your case…) - dotNetFx40_Full_x86_x64.exe (48.1 MB): This is the Full Framework SKU that you must install on any supported 64-bit OS. This will also install on any supported 32-bit OS. If you are redistributing the Full Framework with your application you most likely want to redist this package as it can install on both 32 and 64 bit OS’s. - dotNetFx40_Full_x86.exe (35.3 MB): This is the Full Framework SKU that you could use to install on any supported 32-bit OS. Choose this only if all your users are running 32 bit OS (in most times this will not be your case…) - NET 4 RTM Web Bootstrapper: This is what you want to install if you need NET4 Full and you are online. This will detect your OS and processor architecture and will install the appropriate Framework. - NET 4 Client Profile RTM Web Bootstrapper: This is what you want to install if you need NET4 Client Profile and you are online. This will detect your OS and processor architecture and will install the appropriate Client Profile. Related Blogs and Resources - What's New in the .NET Framework 4 - NET Framework 4 Client Profile - Introduction - What’s new in .NET Framework 4 Client Profile Beta 2. - How to: Build Windows Forms Custom Control that Supports NetFx 4 Client Profile - NET Framework 4 Beta 2 on WU Appendix A: Here are the files that exist in the NET4 Client Profile and NET4 Full framework.
https://blogs.msdn.microsoft.com/jgoldb/2010/04/12/whats-new-in-net-framework-4-client-profile-rtm/
CC-MAIN-2019-04
refinedweb
3,012
54.73
SMIL is indeed one of the reasons I want namespaces. SMIL doesn't require namespaces (as someone suggested), but we definitely want them to be able to incorporate our cmif-specific features in a SMIL document. And to answer Lars' question "why I don't use architectural forms": because I'm not familiar enough with them, I guess. Namespaces seem like a nice lightweight mechanism to allow easy reuse of standards. What I would like to do (i.e. what I would like us, as python-xml sig to do:-), before we go off and implement namespaces in the various python modules is to determine how people would want to use namespaces and how this would be facilitated in the API. (Or, perhaps better, to find out how other groups such as the DOM people envision doing this). I can think of a two ways in which I might want to treat unknown namespaces, and each would require a slightly different API in DOM (SAX probably isn't as much of a problem): - Pretend that stuff in unrecognized namespaces isn't there at all, - Treat stuff in unrecognized namespaces as opaque (i.e. leave it in the tree, but during transforms and such treat it as you would PCDATA) For known namespaces there are again various issues. I might want to treat one of the namespaces as "primary", where the tag/element names would be simple strings (backward compatible) and names from other namespaces are returned as "ns:elemname" or ("ns", "elemname"). But, for other applications I might want the namespaces to be treated pretty much separately. And, of course, there are probably quite a few applications that are happy enough if we just treat ":" as part of the identifier... (half a :-) -- Jack Jansen | ++++ stop the execution of Mumia Abu-Jamal ++++ Jack.Jansen@cwi.nl | ++++ if you agree copy these lines to your sig ++++ | see
https://mail.python.org/pipermail/xml-sig/1998-November/000482.html
CC-MAIN-2017-39
refinedweb
315
66.67
At the core of Modeler is the ModelMBean interface — for those unfamiliar with this, it allows a developer to wrap up any old Java class into an MBean which can be then managed via normal JMX means. In other words, you can take any class you want to export to JMX and without changing your class, without your class even "knowing" it’s going to be JMX‘d, you can do so — by the usage of a ModelMBean! Unfortunately, for those of you who tried to use a ModelMBean — in fact same for DynamicMBean — the interfaces for creating these and defining the metadata for each bean can be quite clunky and awkward at times to use. I thought in the past, when working outside the Spring framework, that it would be so good to have a way to just say "here’s my class, a standard Java class, not aligned to any JMX naming conventions or anything — please register this somehow with JMX so I can inspect data through JMX Console". This is possible through Commons Modeler. In this "how to", I'm going to start with a very simple bean and show how to wrap it up using Commons Modeler. For the purpose of this I'm going to use a (very) simple Java bean: /** * Simple bean class with a few basic properties. * * @author Liviu Tudor */ public class JacksMagicBean { private int magicNumber; private String magicWord; private boolean magicBoolean; public JacksMagicBean() { this(0, null, false); } public JacksMagicBean(int magicNumber, String magicWord, boolean magicBoolean) { this.magicNumber = magicNumber; this.magicWord = magicWord; this.magicBoolean = magicBoolean; } public int getMagicNumber() { return magicNumber; } public void setMagicNumber(int magicNumber) { this.magicNumber = magicNumber; } public String getMagicWord() { return magicWord; } public void setMagicWord(String magicWord) { this.magicWord = magicWord; } public boolean isMagicBoolean() { return magicBoolean; } public void setMagicBoolean(boolean magicBoolean) { this.magicBoolean = magicBoolean; } public void switchMagicBoolean() { magicBoolean = !magicBoolean; } public void addNumber( int number ) { this.magicNumber += number; } @Override public String toString() { return "JacksMagicBean [magicNumber=" + magicNumber + ", magicWord=" + magicWord + ", magicBoolean=" + magicBoolean + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + magicNumber; result = prime * result + ((magicWord == null) ? 0 : magicWord.hashCode()); result = prime * result + (magicBoolean ? 1 : 0); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; JacksMagicBean other = (JacksMagicBean) obj; if (magicNumber != other.magicNumber) return false; if (magicBoolean != other.magicBoolean) return false; if (magicWord == null) { if (other.magicWord != null) return false; } else if (!magicWord.equals(other.magicWord)) return false; return true; } } As you can see, nothing tricky here -- just a bunch of properties and a couple of methods. You could use a JMXBean I suppose to define an interface and have this JMX‘d — but this introduces another interface and makes (to me at least) the code less readable. You could of course used the ModelMBean class as it is — and after you’ve fallen asleep on your keyboard writing all the code to deal with the attribute information and the method metadata etc etc etc you’ll get there Or you can use a piece of code like this (look at registerBean function): MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); BaseModelMBean bmBean = new BaseModelMBean(JacksMagicalBean.class.getCanonicalName()); ObjectName name = new ObjectName(someStringName); mbs.registerMBean(bmBean, name); If you run the attached code and inspect it with JConsole (I’ve put a few “breakpoints” in the code, so the program stops waiting for user input in the console, giving you time to look at JConsole) you will see that auto-magically all the bean properties are exposed via JMX and the methods too! And if you take the instantiation of the platform MBeanServer out, you are left with only a couple of lines! You are however still left with the task of creating the ObjectName instance — small task, I know, but the constructor throws a MalformedObjectNameException, which presents the inconvenience (when coding around it) of having to wrap it up in try/catch, even though you know for sure the naming used is perfectly valid! So would be good if we can shorten this sequence just a bit more and pass the responsibility of the whole ObjectName creation to a function that handles that too. This is possible by using the Registry class. This is a wrapper ultimately for the MBeanServer but offers a few extra features — as to be expected. One of them, is a method which takes an object (instance of your bean you want to JMX) and a name to use and does all the work under the covers: - create a ModelMBean to wrap up your bean - the newly-created ModelMBean will introspect your bean and create all the metadata needed to made all the bean’s properties and methods it then creates an ObjectName with the given name - and finally registers the ModelMBean with the registry — which in turns means registering this with the platform MBeanServer So if you look at the registerObject() method, you will see that it’s very short — and calls simply just one function on the Registry class: private static void registerObject(final Registry registry, final Object obj, String oName) { try { registry.registerComponent(obj, oName, null); } catch (Exception e) { e.printStackTrace(); System.exit(4); } } In fact apart from the call registry.registerComponent(), all the extra code in this function is just to prevent exception from bubbling up the call stack! One line of code for each of your beans to export it to JMX — not bad, huh? And here’s what JConsole reports at the first “breakpoint” — which is after we register 2 sets of beans, one using the MBeanServer method, and one using Registry — the outcome being exactly the same. And here’s another feature that I did like in Registry: you can invoke a method on a set of beans in one go — by calling invoke() and passing it a list of object names! Might not sound like much, but imagine a scenario where you have a plugin-based system: 3rd parties can extend certain classes of yours and at some point you want to ensure all of these plugins get to a certain state — maybe you just want to initialize them, or reset them etc. You can of course build a whole listener/notification mechanism, or you can avoid that, and simply send the notifications in one go via JMX — by calling invoke()! Finally, below is the source of samples program: import java.io.BufferedReader; import java.io.InputStreamReader; import java.lang.management.ManagementFactory; import java.util.ArrayList; import java.util.List; import javax.management.MBeanServer; import javax.management.ObjectName; import org.apache.commons.modeler.BaseModelMBean; import org.apache.commons.modeler.Registry; /** * Sample entry point. * * @author Liviu Tudor */ public class SamplesDriver { private static final int N_BEANS = 10; /** * Program entry point. Simply starts the Sun JDMK agent. * * @param args * command-line parameters -- ignored */ public static void main(String[] args) { // do the actual work MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); // instantiate N_BEANS beans for (int i = 1; i < N_BEANS; i++) { registerBean(mbs, baseModelName(i), JacksMagicBean.class); } // retrieve the registry Registry reg = getRegistry(); // an easier way of registering for (int i = 1; i < N_BEANS; i++) { registerObject(reg, new JacksMagicBean(), simpleObjectName(i)); } // invoked method on all of the beans we created above List Please note this article is a copy from my initial blog post here, slightly modified to include the complete sources here. Also I couldn't figure out how to include the screenshot (still a rookie with wiki sorry ) so it does look slightly different to the original, but the contents is nevertheless the same. One last note -- the waitForUserInput() function has an if/else branch as it turns out System.console() can return null when run in most IDE's nowadays, as such, for those of you who want to run this in an IDE, you will not get a prompt -- hence the if/else.
http://wiki.apache.org/commons/WrapUpBeanWithBaseModelMBean
CC-MAIN-2014-23
refinedweb
1,303
50.97
#include <CGAL/IO/Geomview_stream.h> At the moment not all classes of the CGAL kernel have output operators. 2D objects are embedded in the xy-plane. At the moment input is only provided for points. The user has to select a point on the pick plane with the right mouse button. The pick plane can be moved anywhere with the left mouse button, before a point is entered. #include <CGAL/IO/Polyhedron_geomview_ostream.h> #include <CGAL/IO/Triangulation_geomview_ostream_2.h> #include <CGAL/IO/Triangulation_geomview_ostream_3.h> Geomview distinguishes between edge and face colors. The edge color is at the same time the color of vertices. The following functions are helpful if you develop your own insert and extract functions. The following functions allow to pass a string from Geomview and to read data sent back by Geomview.. <!Next_reference_link_10_15_2!>
http://www.cgal.org/Manual/3.1/doc_html/cgal_manual/Geomview_ref/Class_Geomview_stream.html
crawl-001
refinedweb
135
60.21
This chapter includes answers to the most frequently asked questions about the Sun Cluster system. The questions are organized by topic. What. Can I run one or more of the cluster nodes as highly available NFS servers with other cluster nodes as clients?Answer: No, do not do a loopback mount.Question: Can I use a cluster file system for applications that are not under Resource Group Manager control?Answer: Yes. However, without RGM control, the applications need to be restarted manually after the failure of the node on which they are running.Question: Must all cluster file systems have a mount point under the /global directory?Answer: No. However, placing cluster file systems under the same mount point, such as /global, enables better organization and management of these file systems.Question: What are the differences between using the cluster file system and exporting NFS file systems?Answer: Several differences exist:, the cluster file system caches files when a file is being accessed from multiple nodes for read, write, file locks, async I/O. change can take much longer. The file system /global/.devices/node@nodeID appears on my cluster nodes. Can I use this file system to store data that I want to be highly available and global?Answer: These file systems store the global device namespace. These file system?Answer: For a disk device to be considered highly available, it must be mirrored, or use RAID-5 hardware. All data services should use either highly available disk devices, or cluster file systems mounted on highly available disk devices. Such configurations can tolerate single disk failures.Question: Can I use one volume manager for the local disks (boot disk) and a different volume manager for the multihost disks?Answer: SPARC: This configuration is supported with the Solaris Volume Manager software managing the local disks and VERITAS Volume Manager managing the multihost disks. No other combination is supported. x86: No, this configuration is not supported, as only Solaris Volume Manager is supported in x86 based clusters. Which Sun Cluster data services are available?Answer: The list of supported data services is included in Supported Products in Sun Cluster 3.1 4/05 Release Notes for Solaris OS.Question: Which application versions are supported by Sun Cluster data services?Answer: The list of supported application versions is included in Supported Products in Sun Cluster 3.1 4/05 Release Notes for Solaris OS.Question: Can I write my own data service?Answer: Yes. See the Chapter 11, DSDL API Functions, in Sun Cluster Data Services Developer’s Guide for Solaris OS for more information.Question: When creating network resources, should I specify numeric IP addresses or hostnames?Answer: The preferred method for specifying network resources is to use the UNIX hostname rather than the numeric IP address.Question: When creating network resources, what is the difference between using a logical hostname (a LogicalHostname resource) or a shared address (a SharedAddress resource)?Answer: Except in the case of Sun Cluster HA for NFS, wherever the documentation recommends the use of a LogicalHostname resource in a Failover mode resource group, a SharedAddress resource or LogicalHostname resource can be used interchangeably. The use of a SharedAddress resource incurs some additional overhead because the cluster networking software is configured for a SharedAddress but not for a LogicalHostname. The advantage to using a SharedAddress resource is demonstrated when you configure both scalable and failover data services, and want clients to be able to access both services by using the same hostname. In this case, the SharedAddress resources along with the failover application resource are contained in one resource group. The scalable service resource is contained in a separate resource group and configured to use the SharedAddress resource. Both the scalable and failover services can then use the same set of hostnames/addresses that are configured in the SharedAddress resource. Which. Do all cluster members need to have the same root password?Answer: You are not required to have the same root password on each cluster member. However, you can simplify administration of the cluster by using the same root password on all nodes.Question: Is the order in which nodes are booted significant?Answer: In most cases, no. However, the boot order is important to prevent amnesia. For example, if node two was the owner of the quorum device and node one is down, and then you bring node two down, you must bring up node two before bringing back node one. This order prevents you from accidentally bringing up a node with outdated cluster configuration information. Refer to About Failure Fencing for details about amnesia.Question: Do I need to mirror local disks in a cluster node?Answer: Yes. Though this mirroring is not a requirement, mirroring the cluster node's disks prevents a nonmirrored disk failure from taking down the node. The downside to mirroring a cluster node's local disks is more system administration overhead.Question: What are the cluster member backup issues?Answer: You can use several backup methods for a cluster. One method is to have a. What. Which cluster interconnects does the Sun Cluster system support?Answer: Currently, the Sun Cluster system supports the following cluster interconnects: Ethernet (100BASE-T Fast Ethernet and 1000BASE-SX Gb) in both SPARC based and x86 based clusters Infiniband in both SPARC based and x86 based clusters SCI in SPARC based clusters only What is the difference between a “cable” and a transport “path”?Answer: Cluster transport cables are configured by. These cables are not probed and therefore their state is unknown. You can obtain the state of a cable by using the scconf -p command. Transport paths are dynamically established by the cluster topology manager. The “status” of a transport path is determined by the topology manager. A path can have a status of “online” or “offline.” You can obtain the status of a transport path by using the scstat(1M) command. Consider the following example of a two-node cluster with four cables. Two possible transport paths can be formed from these four cables. Do. Does the Sun Cluster system require an administrative console?Answer: Yes.Question: Does the administrative console have to be dedicated to the cluster, or can it be used for other tasks?Answer: The Sun Cluster, for example, in the same room?Answer: Check with your hardware service provider. The provider might require that the console be located in close proximity to the cluster. No technical reason exists for the console to be located in the same room.Question: Can an administrative console serve more than one cluster, if any distance requirements are also first met?Answer: Yes. You can control multiple clusters from a single administrative console. You can also share a single terminal concentrator between clusters. Does the Sun Cluster system require a terminal concentrator?Answer: No software releases starting with Sun Cluster 3.0 require a terminal concentrator to run. Unlike the Sun Cluster 2.2 product, which required a terminal concentrator for failure fencing, later products do not depend on the terminal concentrator node from a remote workstation anywhere on the network. This access is provided even when the node is at the OpenBoot PROM (OBP) on a SPARC based node or a boot subsystem on an x86 based node node. Administering Sun Cluster Overview in Sun Cluster System Administration Guide for Solaris OS Chapter 2, Installing and Configuring the Terminal Concentrator, in Sun Cluster 3.0-3.1 Hardware Administration Manual for Solaris OS What if the terminal concentrator itself fails? Must I have another one standing by?Answer: No. You do not lose any cluster availability if the terminal concentrator fails. You do lose the ability to connect to the node.
http://docs.oracle.com/cd/E19636-01/819-0421/x-17ei8/index.html
CC-MAIN-2014-42
refinedweb
1,289
56.96
{-# .Str import Data.Generics import Data.Maybe import Data.List import qualified Data.IntSet as IntSet import Control.Monad.State import Data.Ratio -- | An existential box representing a type which supports SYB -- operations. data DataBox = forall a . (Typeable a, Data a) => DataBox a data Box find = Box {fromBox :: forall a . Typeable a => a -> Answer find} data Answer a = Hit {fromHit :: a} -- you just hit the element you were after (here is a cast) | Follow -- go forward, you will find something | Miss -- you failed to sink my battleship! containsMatch :: (Data start, Typeable start, Data find, Typeable find) => start -> find -> Box find #if __GLASGOW_HASKELL__ < 606 -- GHC 6.4.2 does not export typeRepKey, so we can't do the trick -- as efficiently, so we just give up and revert to always following containsMatch start find = Box query where query a = case cast a of Just y -> Hit y Nothing -> Follow #else -- GHC 6.6 does contain typeRepKey, so only follow when appropriate containsMatch start find = Box query where typeInt x = inlinePerformIO $ typeRepKey x query :: Typeable a => a -> Answer find query a = if tifind == tia then Hit (unsafeCast a) else if tia `IntSet.member` timatch then Follow else Miss where tia = typeInt $ typeOf a tifind = typeInt tfind timatch = IntSet.fromList $ map typeInt tmatch tfind = typeOf find tmatch = f [tfind] (filter ((/=) tfind . fst) $ containsList start) f want have = if null want2 then [] else want2 ++ f want2 no where want2 = map fst yes (yes,no) = partition (not . null . intersect want . snd) have containsList :: (Data a, Typeable a) => a -> [(TypeRep, [TypeRep])] containsList x = f [] [DataBox x] where f done [] = [] f done (DataBox t:odo) | tt `elem` done = f done odo | otherwise = (tt,map (\(DataBox a) -> typeOf a) xs) : f (tt:done) (xs++odo) where tt = typeOf t xs = contains t -- = [] where f ctr = gmapQ DataBox (asTypeOf (fromConstr ctr) x) ctrs = dataTypeConstrs dtyp dtyp = dataTypeOf x #endif instance (Data a, Typeable a) => Uniplate a where uniplate =) collect_generate :: (Data on, Data with, Typeable on, Typeable with) => (forall a . Typeable a => a -> Answer with) -> on -> CC with on collect_generate oracle item = fromC $ gfoldl combine create item where -- forall a b . Data a => C with (a -> b) -> a -> C with b combine (C (c,g)) x = case collect_generate_self oracle x of (c2, g2) -> C (Two c c2, \(Two c' c2') -> g c' (g2 c2')) -- forall g . g -> C with g create x = C (Zero, \_ -> x)
http://hackage.haskell.org/package/uniplate-1.2.0.3/docs/src/Data-Generics-PlateData.html
CC-MAIN-2014-52
refinedweb
396
69.21
If we uncompress the juddi-core service classes into WEB-INF/classes, will that work? Jeff Faath wrote: > > All, > > I was able to get further along in the investigation of getting the > JAX-WS web services to work with Tomcat and Axis2. Turns out it wasn’t > working before because Axis2 couldn’t properly deploy the services > when classes were compiled into a jar. I think there is a way to > configure Axis2 to deploy within a jar, but unfortunately there is a > bigger issue. > > When trying to bring up the WSDL, I get a namespace conflict issue. > Upon further investigation, it turns out we are getting hit by a > flavor of WSCOMMONS-377. And this issue doesn’t look like it’s going > to get fixed anytime soon. > > So, I’m not sure where to go from here. Any suggestions? > > -JF > --------------------------------------------------------------------- To unsubscribe, e-mail: juddi-dev-unsubscribe@ws.apache.org For additional commands, e-mail: juddi-dev-help@ws.apache.org
http://mail-archives.us.apache.org/mod_mbox/juddi-dev/200811.mbox/%3C4931C0D9.6020400@redhat.com%3E
CC-MAIN-2019-26
refinedweb
163
57.16
Today a (slightly confused) question on StackOverflow wondered how to access R’s facilities for eigenvalues calculations from C code. For this, we need to step back and consider how this is done. In fact, R farms the calculation out to the BLAS. On could possibly access R’s functions—but would then have to wrestle with the data input/output issues which make Rcpp shine in comparison. Also, Rcpp gets us access to Armadillo (via the RcppArmadillo) package and Armadillo’s main focus are exactly the linear algebra calculations and decompositions. And with facilities that were added to Rcpp in the 0.10.* release series, this effectively becomes a one-liner of code! (Nitpickers will note that there are also one include statement, two attributes declarations and the function name itself.) #include <RcppArmadillo.h> // [[Rcpp::depends(RcppArmadillo)]] // [[Rcpp::export]] arma::vec getEigenValues(arma::mat M) { return arma::eig_sym(M); } We can illustrate this easily via a random sample matrix. set.seed(42) X <- matrix(rnorm(4*4), 4, 4) Z <- X %*% t(X) getEigenValues(Z) [,1] [1,] 0.3319 [2,] 1.6856 [3,] 2.4099 [4,] 14.2100 In comparison, R gets the same results (in reverse order) and also returns the eigenvectors. eigen(Z) $values [1] 14.2100 2.4099 1.6856 0.3319 $vectors [,1] [,2] [,3] [,4] [1,] 0.69988 -0.55799 0.4458 -0.00627 [2,] -0.06833 -0.08433 0.0157 0.99397 [3,] 0.44100 -0.15334 -0.8838 0.03127 [4,] 0.55769 0.81118 0.1413 0.10493 Armadillo has other eigenvector computations too, see its...
http://www.r-bloggers.com/armadillo-eigenvalues/
CC-MAIN-2016-30
refinedweb
265
60.41
Determining the best programming language for web scraping may feel daunting as there are many options. Some of the popular languages used for web scraping are Python, JavaScript with Node.js, PHP, Java, C#, etc. The problem is deciding which language is the best since every language has its strengths and weaknesses. In this article, we will focus on web scraping with Java and create a web scraper using Java. Navigation: Web scraping frameworks There are two most commonly used libraries for web scraping with Java— JSoup and HtmlUnit. JSoup is a powerful library that can handle malformed HTML effectively. The name of this library comes from the phrase “tag soup”, which refers to the malformed HTML document. HtmlUnit is a GUI-less, or headless, browser for Java Programs. It can emulate the key aspects of a browser, such as getting specific elements from the page, clicking those elements, etc. As the name of this library suggests, it is commonly used for unit testing. It is a way to simulate a browser for testing purposes. HtmlUnit can also be used for web scraping. The good thing is that with just one line, the JavaScript and CSS can be turned off. It is helpful in web scraping as JavaScript and CSS are not required most of the time. In the later sections, we will examine both libraries and create web scrapers. Prerequisite for building a web scraper with Java This tutorial on web scraping with Java assumes that you are familiar with the Java programming language. For managing packages, we will be using Maven. Apart from Java basics, a primary understanding of how websites work is also expected. Good knowledge of HTML and selecting elements in it, either by using XPath or CSS selectors, would also be required. Note that not all the libraries support XPath. Quick overview of CSS Selectors Before we proceed with this Java web scraping tutorial, it will be a good idea to review the CSS selectors: #firstname– selects any element where idequals “firstname” .blue– selects any element where classcontains “blue” p– selects all <p>tags div#firstname– select divelements where idequals “firstname” p.link.new– Note that there is no space here. This selects <p class="link new"> p.link .new– Note the space here. Selects any element with class “new”, which are inside <p class="link"> Now let’s review the libraries that can be used for web scraping with Java. Web scraping with Java using JSoup JSoup is perhaps the most commonly used Java library for web scraping with Java. Let’s examine this library to create a Java website scraper. Broadly, there are three steps involved in web scraping using Java. Getting JSoup The first step of web scraping with Java is to get the Java libraries. Maven can help here. Use any Java IDE, and create a Maven project. If you do not want to use Maven, head over to this page to find alternate downloads. In the pom.xml (Project Object Model) file, add a new section for dependencies and add a dependency for JSoup. The pom.xml file would look something like this: <dependencies> <dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.14.1</version> </dependency> </dependencies> With this, we are ready to create a Java scraper. Getting and parsing the HTML The second step of web scraping with Java is to get the HTML from the target URL and parse it into a Java object. Let’s begin with the imports: import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; Note that it is not a good practice to import everything with a wildcard – import org.jsoup.*. Always import exactly what you need. The above imports are what we are going to use in this Java web scraping tutorial. JSoup provides the connect function. This function takes the URL and returns a Document. Here is how you can get the page’s HTML: Document doc = Jsoup.connect("").get(); You will often see this line in places, but it has a disadvantage. This shortcut does not have any error handling. A better approach would be to create a function. This function takes a URL as the parameter. First, it creates a connection and stores it in a variable. After that, the get() method of the connection object is called to retrieve the HTML document. This document is returned as an instance of the Document class. The get() method can throw an IOException, which needs to be handled. public static Document getDocument(String url) { Connection conn = Jsoup.connect(url); Document document = null; try { document = conn.get(); } catch (IOException e) { e.printStackTrace(); // handle error } return document; } In some instances, you would need to pass a custom user agent. This can be done by sending the user agent string to the userAgent() function before calling the get() function. Connection conn = Jsoup.connect(url); conn.userAgent("custom user agent"); document = conn.get(); This action should resolve all the common problems. Querying HTML The most crucial step of any Java web scraper building process is to query the HTML Document object for the desired data. This is the point where you will be spending most of your time while writing the web scraper in Java. JSoup supports many ways to extract the desired elements. There are many methods, such as getElementByID, getElementsByTag, etc., that make it easier to query the DOM. Here is an example of navigating to the JSoup page on Wikipedia. Right-click the heading and select Inspect, thus opening the developer tool with the heading selected. In this case, either getElementByID or getElementsByClass can be used. One important point to note here is that getElementById (note the singular Element) returns one Element object, whereas getElementsByClass (note plural Elements) returns an Array list of Element objects. Conveniently, this library has a class Elements that extends ArrayList<Element>. This makes code cleaner and provides more functionality. In the code example below, the first() method can be used to get the first element from the ArrayList. After getting the reference of the element, the text() method can be called to get the text. Element firstHeading = document.getElementsByClass("firstHeading").first(); System.out.println(firstHeading.text()); These functions are good; however, they are specific to JSoup. For most cases, the select function can be a better choice. The only case when select functions will not work is when you need to traverse up the document. In these cases, you may want to use parent(), children(), and child(). For a complete list of all the available methods, visit this page. The following code demonstrates how to use the selectFirst() method, which returns the first match. Element firstHeading= document.selectFirst(".firstHeading"); In this example, selectFirst() method was used. If multiple elements need to be selected, you can use the select() method. This will take the CSS selector as a parameter and return an instance of Elements, which is an extension of the type ArrayList<Element>. Web scraping with Java using HtmlUnit There are many methods to read and modify the loaded page. HtmlUnit makes it easy to interact with a web page like a browser, which involves reading text, filling forms, clicking buttons, etc. In this case, we will be using methods from this library to read the information from URLs. As discussed in the previous section, there are three steps involved in web scraping with Java. Getting and parsing the HTML The first step of web scraping with Java is to get the Java libraries. Maven can help here. Create a new maven project or use the one created in the previous section. If you do not want to use Maven, head over to this page to find alternate downloads. In the pom.xml file, add a new section for dependencies and add a dependency for HtmlUnit. The pom.xml file would look something like this: <dependency> <groupId>net.sourceforge.htmlunit</groupId> <artifactId>htmlunit</artifactId> <version>2.51.0</version> </dependency> Getting the HTML The second step of web scraping with Java is to retrieve the HTML from the target URL as a Java object. Let’s begin with the imports: import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.DomNode; import com.gargoylesoftware.htmlunit.html.DomNodeList; import com.gargoylesoftware.htmlunit.html.HtmlElement; import com.gargoylesoftware.htmlunit.html.HtmlPage; As discussed in the previous section, it is not a good practice to do a wildcard import such as import com.gargoylesoftware.htmlunit.html.*. Import only what you need. The above imports are what we are going to use in this Java web scraping tutorial. In this example, we will scrape this Librivox page. HtmlUnit uses WebClient class to get the page. The first step would be to create an instance of this class. In this example, there is no need for CSS rendering, and there is no use of JavaScript as well. We can set the options to disable these two. WebClient webClient = new WebClient(); webClient.getOptions().setCssEnabled(false); webClient.getOptions().setJavaScriptEnabled(false); HtmlPage page = webClient.getPage(""); Note that getPage() functions can throw IOException. You would need to surround it in try-catch. Here is one example implementation of a function that returns an instance of HtmlPage: public static HtmlPage getDocument(String url) { HtmlPage page = null; try (final WebClient webClient = new WebClient()) { webClient.getOptions().setCssEnabled(false); webClient.getOptions().setJavaScriptEnabled(false); page = webClient.getPage(url); } catch (IOException e) { e.printStackTrace(); } return page; } Now we can proceed with the next step. Querying HTML There are three categories of methods that can be used with HTMLPage. The first is DOM methods such as getElementById(), getElementByName(), etc. that return one element. These also have their counterparts like getElementsById() that return all the matches. These methods return a DomElement object or a List of DomElement objects. HtmlPage page = webClient.getPage(""); DomElement firstHeading = page.getElementById("firstHeading"); System.out.print(firstHeading.asNormalizedText()); // prints Jsoup The second category of a selector uses XPath. In this Java web scraping tutorial, we will go through creating a web scraper using Java. Navigate to this page, right-click the book title and click inspect. If you are already comfortable with XPath, you should be able to see that the XPath to select the book title would be //div[@class="content-wrap clearfix"]/h1. There are two methods that can work with XPath — getByXPath() and getFirstByXPath(). They return HtmlElement instead of DomElement. Note that special characters like quotation marks will need to be escaped using a backslash: HtmlElement book = page.getFirstByXPath("//div[@class=\"content-wrap clearfix\"]/h1"); System.out.print(book.asNormalizedText()); Lastly, the third category of methods uses CSS selectors. These methods are querySelector() and querySelectorAll(). They return DomNode and DomNodeList<DomNode> respectively. To make this Java web scraper tutorial more realistic, let’s print all the chapter names, reader names, and duration from the page. The first step is to determine the selector that can select all rows. Next, we will use the querySelectorAll() method to select all the rows. Finally, we will run a loop on all the rows and call querySelector() to extract the content of each cell. String selector = ".chapter-download tbody tr"; DomNodeList<DomNode> rows = page.querySelectorAll(selector); for (DomNode row : rows) { String chapter = row.querySelector("td:nth-child(2) a").asNormalizedText(); String reader = row.querySelector("td:nth-child(3) a").asNormalizedText(); String duration = row.querySelector("td:nth-child(4)").asNormalizedText(); System.out.println(chapter + "\t " + reader + "\t " + duration); } Conclusion Almost every business needs web scraping to analyze data and stay competitive in the market. Knowing the basics of web scraping and how to build a web scraper using Java can result in much more informed and quick decisions, which are essential for a business to succeed. In this article, we have seen two Java web scraping examples. If you already know Java, there may not be a need to explore any other language used for web scraping. Still, if you want to see how Python can be used for web scraping, we have a tutorial on Python web scraping. We also have a tutorial on web scraping with JavaScript and Node.js. All these articles should help you select the best programming language suitable for your specific needs. People also ask Can you web scrape with Java? Yes. There are many powerful Java libraries used for web scraping. Two such examples are JSoup and HtmlUnit. These libraries help you connect to a web page and offer many methods to extract the desired information. If you know Java, it will take very little time to get started with these Java libraries. Is Web Scraping Legal? This is a complex question that needs a detailed examination. We have explored this subject in-depth in our “Is web scraping legal?” article, and we highly recommend that you read it. In short, web scraping is a legal activity as long as it complies with the laws regarding the source targets or data itself.
https://oxylabs.io/blog/web-scraping-with-java
CC-MAIN-2022-05
refinedweb
2,163
59.4
The easiest way to create business applications for the Desktop and the Cloud Let’s get started Download the AmazingPie POS Sample database 3. Select “Database” 4. Enter the connection information for your AmazingPie database 5. Select all the tables 6. Verify the Data Source is named AmazingPieData, and click [Finish] 1. Right-click on the HTML Client node in the Solution Explorer and select “Add Screen” 2. Select the “Browse Data Screen” template, using the “AmazingPieData.Locations” entity as a Data Source 3. We’ll change the default display a bit: 2. Select the “View Details Screen” template, using the “AmazingPieData.Location” entity as a Data Source 3. We’ll change the default display a bit: 5. Select viewSelected 6. Verify Navigate To: is set to Location View and click [OK] 4. Add the style and js file references Since LightSwitch works as a single page application model, we’ll just need to add the references to the default.htm page 5. Now, add the SeatedGuests render code: 7. Configure the route Note: For more info on Routes see ASP.net Routing Note: For more info on Routes see ASP.net Routing VB Imports System.Web.Routing Imports System.Web.Http C# using System.Web.Routing; using System.Web.Http; 8. Add the following route to the Application_Start method VBSub. 1. Hit F5 to launch our app and get the root URL. In my case, it’sPublic Debugging Tip: If you have your service running, you can copy/paste the result into your javascript to test your UI without having to make the service calls. This is where we’re going to capture the total number of seats for each location. Using LINQ, we’re going to: 1. Open the SeatingController from the Server\Reports folder 2. Add the Extension Methods for query operators Note: this is an important step. Without these extension methods, the LINQ query operators will not be available on the DataWorkspace(); } } To understand how the LINQ query is working here: Remember, Tables is the name of our SQL Table that contains the list of tables in the restaurant. It’s not the collection of SQL Tables. Remember, Tables is the name of our SQL Table that contains the list of tables in the restaurant. It’s not the collection of SQL Tables. 'BelSquare': With our WebAPI written and tested, we can now replace our SampleData with the WebAPI call 1. Rather than switch back to logical view, we can stay in the File view to open our Location_View.js which is located under the UserCode folder. And the Graph of the tables for BelSquare: Thanks, Steve Lasker Microsoft Program Manager Visual Studio LightSwitch Very nice. Could you do a piece on adding a jQuery jq grid for example ? A grid is one of the most important parts of nearly every business application. Very well done :). No category labels due to case-sensitive typo in SeatingController.cs : TableType_ID = g.Key.TableType_Id.Trim() :):\temp\LightSwitch AmazingPie Sample Database\C#> .\LoadAmazingPieIntoLocalDB.ps1 Security warning Run only scripts that you trust. While scripts from the internet can be useful, this script can potentially harm your computer. Do you want to run C:\temp\LightSwitch AmazingPie Sample Database\C#!
http://blogs.msdn.com/b/lightswitch/archive/2013/04/22/create-dashboard-reports-with-lightswitch-webapi-and-serverapplicationcontext.aspx
CC-MAIN-2015-11
refinedweb
539
69.07
.1 (tar.gz) [PGP] [SHA1] [MD5] Apache ServiceMix 3.3.1 (zip) Source assembly Use this if you want to build Apache ServiceMix from source yourself Apache ServiceMix Sources 3.3.1 (tar.gz) Apache ServiceMix Sources 3.3.1 (zip) Web assembly Use this if you want to run Apache ServiceMix as a web application inside an existing web container Apache ServiceMix WAR 3.3 2009.01 of servicemix-bean Version 2009.01 of servicemix-camel Version 2009.01 of servicemix-cxf-bc Version 2009.01 of servicemix-cxf-se Version 2009.01 of servicemix-drools Version 2009.01 of servicemix-eip Version 2009.01 of servicemix-file Version 2009.01 of servicemix-ftp Version 2009.01 of servicemix-http Version 2009.01 of servicemix-jms Version 2009.01 of servicemix-jsr181 Version 2009.01 of servicemix-mail Version 2009.01 of servicemix-osworkflow Version 2009.01 of servicemix-quartz Version 2009.01 of servicemix-script Version 2009.01 of servicemix-scripting Version 2009.01 of the standard ServiceMix shared library Version 2009.01 of servicemix-smpp Version 2009.01 of servicemix-snmp Version 2009.01 of servicemix-truezip Version 2009.01 of servicemix-validation Version 2009.01 of servicemix-vfs Version 2009.01 of servicemix-wsn2005 Version 2009.01 of servicemix-xmpp This release also includes: Version 1.1.0 of servicemix-utils Version 5.2.0 of ActiveMQ You can use it together with Version 4.0 of the Maven plugins Version 2008.01 of the archetypes Release Notes - ServiceMix - Version 3.3.1 Bug * SM-1438 - Exceptions while shutting down ServiceMix * SM-1456 - Statistics Service throws NPE on startup. * SM-1521 - Released version of archetype-catalog is corrupt * SM-1654 - Format of the Message cannot be different than XML within Camel * SM-1657 - Auto-enlistment should only occur when transactions status is ACTIVE * SM-1685 - The DeliveryChannel does not recognize the new MessageExchangeListener interface * SM-1712 - ExchangeListener is called with exchangeSent instead of exchangeAccepted when using sendSync * SM-1713 - servicemix common component should be moved before deployable as servicemix-lwcontainer need it. (this was fixed in 3.2 but not on trunk) * SM-1719 - org.apache.servicemix.jdbc.JDBCAdapter : bug in Statements and add of new functionnality doLoadData * SM-1749 - Incorrect Logger name creation in ComponentContextImpl * SM-1761 - AutoDeployment stops working after x deployments * SM-1766 - servicemix-web sample in Servicemix 3 trunk is broken because of the removal of ManagedHttpServlet from servicemix-http component. * SM-1773 - xercesImpl and xml-apis conflict when running inside Jboss * SM-1791 - org.apache.servicemix.jbi.framework.InstallerMBeanImpl is missing bootstrap.init() call on uninstall phase which is required as per JBI specs. * SM-1818 - invoking stop on SA in SHUTDOWN state brings it to STOPPED state * SM-1819 - jms archetypes generate extra http:// for xmlns:xsi namespace. * SM-1820 - Almost all archetypes generate extra http:// for xmlns:xsi namespace. * SM-1824 - BUG in JDK6 ReentrantReadWriteLock can cause SMX hang when redeploy SA * SM-1827 - servicemix-camel-service-unit archetype depends on non-existent servicemix-camel jbi-component * SM-1835 - whitespace interfering with ResolvedEndpoint.resolveEndpoint() * SM-1845 - keystore.jks should be filtered during distribution package * SM-1853 - ClassCast exception in ClassLoaderXmlPreprocessor Improvement * SM-1302 - Make failover:// transport the default protocol used in ServiceMix. * SM-1317 - Add a system property to change CXF to use Log4J instead of JUL * SM-1360 - Add a reference to the XSD in the archetype-generated xbean.xml files * SM-1573 - Use of useJBIWrapper flag in smx-cxf-bc consumer and smx-http soap-consumer endpoints is inconsistent * SM-1607 - JBI container should be able to initialize all SAs first and then start them * SM-1621 - New JMS in/out provider should support temporary queues/topics (as reply destinations) * SM-1659 - should filter the version for kit_camel_example_pom.xml which is used in kit * SM-1660 - add createDaemonExecutor api for ExecutorFactory * SM-1688 - update classworlds version from 1.0.1 to 1.1 * SM-1717 - getError() shouldn't return a null exception in case of sendSync timeout * SM-1808 - Back port the patch of SMXCOMP-455 to SMX 3.2 branch * SM-1810 - should use new activemq namsespace instead of the old one * SM-1817 - Publish components schema files as part of the distribution in a schemas/ directory * SM-1822 - Add JMS connection credentials to JCAFlow * SM-1839 - Main entry improvement to allow run by procrun as Windows Service * SM-1843 - pick up new added bridge-camel sample in the distribution kit * SM-1848 - add client.html for wsn-http-binding example * SM-1870 - Upgrade to Geronimo 2.0.2 New Feature * SM-1756 - add CXFManagedServlet to apache-servicemix-web to enable servicemix-cxf-bc endpoint deploy into servlet container without starting jetty * SM-1782 - Add JBoss Deployer to platforms module * SM-1856 - Add archetype for servicemix-smpp component Task * SM-1723 - Upgrade to ActiveMQ 5.2.0 * SM-1846 - add wsn-cxfbc-binding example * SM-1867 - upgrade to spring 2.5.6 Test * SM-1306 - Improve success ratio of timing sensitive tests * SM-1811 - bridge-sa-itest failed due to missing activemq-camel dependency svn co For a more detailed view of new features and bug fixes, see the changelog
http://servicemix.apache.org/SM/downloads/servicemix-3.3.1.html
CC-MAIN-2015-35
refinedweb
864
58.79
Python provides the regular expression or Regex module as re . Regex library provides a lot of features where strings can be replaced with regex definitions. The regex library provides the sub() method for a substitution or replacement. In this tutorial, we examine how to use the replace operation. re.sub() Method Syntax In order to replace string with regex, the re.sub() method is used. The sub() method accepts multiple parameters which are explained below. re.sub(PATTERN,REPLACEMENT,STRING,count=COUNT) - PATTERN is the regex pattern which is searched inside the STRING. - REPLACEMENT is the string which will be replaced according to PATTERN. - STRING is the string where replacement procedure done. - COUNT is the count of replacement. COUNT is optional and if not specified all occurences are replaced. Replace All Regex Occurences By default is the count parameter is not specified for the sub() method all occurrences are replaced according to the specified regex and replacement string. In the following example we replace the names with new names. import re str = "Ali likes to live in Ankara." print(re.sub('A','a',str)) ali likes to live in ankara. We can also replace multiple strings with a single string. The |sign is used to specify multiple strings. import re str = "Ali, Ahmet and Elif like to live in Ankara." print(re.sub('Ali|Ahmet|Elif','NAME',str)) NAME, NAME and NAME like to live in Ankara. Replace Specified Regex One Time The count parameter of the sub() method can be used to specify the replacement count if the specified regex is matched multiple times. In the following example, we replace the character A just one time. import re str = "A, A and A like to live in Ankara." print(re.sub('A','NAME',str,count=1)) NAME, A and A like to live in Ankara. Replace Specified Regex Multiple Times The count parameter can be also used to replace specified regex multiple times but not for all occurrences. In the following example, we change character A just 2 times. import re str = "A, A and A like to live in Ankara." print(re.sub('A','NAME',str,count=2)) NAME, NAME and A like to live in Ankara.
https://pythontect.com/python-regex-string-replace-tutorial/
CC-MAIN-2022-21
refinedweb
369
67.76
Rails 2.0.2 Ruby 1.8.5 SQLite3 CentOS-5.1 models/ Entity entity has_one client Client client belongs_to entity validates_associated view/ clients/new.html.erb New client <%= error_messages_for :client %> <%= error_messages_for :entity %> <% form_for(@client) do |f| %> <% fields_for(@entity) do |e| %> Client Name <%= e.text_field :entity_name %> <p> <b>Client Legal Name</b><br /> <%= e.text_field :entity_legal_name %> </p> <p> <b>Client Legal Form</b><br /> <%= e.text_field :entity_legal_form %> </p> <% end %> Client status <%= f.text_field :client_status %> controllers/ clients_controller.rb POST /clients POST /clients.xml def create @entity = Entity.new(params[:entity]) @client = Client.new(params[:client]) respond_to do |format| if @entity.save && @client.save flash[:notice] = 'Client was successfully created.' format.html { redirect_to(@client) } format.xml { render :xml => @client, :status => :created, :location => @client } else format.html { render :action => “new” } format.xml { render :xml => @client.errors, :status => :unprocessable_entity } end end end What I want to do is to have an entity created if one does not exist and the existing entity.id returned to client otherwise. The above code almost works when there is no existing entity but the client.entity_id is not set to the id of the newly created entity throwing an SQL error. Question 1. Must I create a method in clients.rb, say entity_build, that checks for the existence of an entity (find_by_entity_name) or creates a new entity otherwise? What would this look like? Question 2. What do I pass the method from the controller? @entity, @client? Question 3. How do I get the fields from the view into the entity from within the client model? See Q.2 Question 4. Is there a simpler way do do this? I am twisting in the breeze her trying to figure out how to make this work. I have read any number of tutorials and code examples but I am just not getting it. Any help is most welcome.
https://www.ruby-forum.com/t/wiring-a-dependent-update/131848
CC-MAIN-2021-31
refinedweb
308
54.29
I2C Data Logger Using ATmega328p and DS3232 – II In my last blog post, I showed you the schematic of a I2C data logger I built. Here I will discuss some sample code used for this data logger and how to make it even more flexible. I will use the triple accelerometer digital level I built a while ago as an example and use it as the data source to measure vibrations and accelerations. The type of data source is not that important as long as it supports I2C. The following is a picture of this setup, as you can see the accelerometer and the data logger are connected via the I2C bus. In this example, the accelerometer is set as an I2C slave. The I2C related code is shown below: void TWIRequest() { byte xlow, xhigh, ylow, yhigh, zlow, zhigh; byte ay[6]; xlow = vx & 255; xhigh = (vx & (255 << 8)) >> 8; ylow = vy & 255; yhigh = (vy & (255 << 8)) >> 8; zlow = vz & 255; zhigh = (vz & (255 << 8)) >> 8; ay[0] = xlow; ay[1] = xhigh; ay[2] = ylow; ay[3] = yhigh; ay[4] = zlow; ay[5] = zhigh; Wire.send(ay, 6); } ...... void setup() { ...... Wire.begin(TWI_ADDR); Wire.onRequest(TWIRequest); } As you can see, whenever the accelerometer receives a request from the I2C master, the TWIRequest method is automatically called and the values for the x,y,z axes are then sent. Note that since the values for the x,y,z axes are integers and not bytes, the value for each axis is represented by two bytes. After the value bytes are transferred to to host, the bytes are assembled back into integers again. The rest of the code used for the accelerometer is similar to what I had written about before so I will not repeat here. The code on the data logger side is a bit more complex as it needs to handle RTC/SD Card and the I2C communication between the slave and master devices. Here is the code listing: #define __AVR_ATmega328P__ #include <binary.h> #include <HardwareSerial.h> #include <pins_arduino.h> #include <WConstants.h> #include <wiring.h> #include <wiring_private.h> #include <Wire/utility/twi.h> #include <Wire/Wire.h> #include <WProgram.h> #include <EEPROM/EEPROM.h> #include <SdFat/SdFat.h> #include <SdFat/SdFatUtil.h> #define DS3232_I2C_ADDRESS B01101000 // This is the I2C address 7bits const int ACC_SENSOR_ADDR = 100; Sd2Card card; SdVolume volume; SdFile root; SdFile file; typedef struct { byte second; byte minute; byte hour; byte dayOfWeek; byte dayOfMonth; byte month; byte year; } Date; Date pD; byte decToBcd(byte val) { return ( (val/10*16) + (val%10) ); } byte bcdToDec(byte val) { return ( (val/16*10) + (val%16) ); } void getDateDS3232() { // Reset the register pointer Wire.beginTransmission(DS3232_I2C_ADDRESS); Wire.send(0x00); //move to reg 0 Wire.endTransmission(); int vBytesToRead = 7; Wire.requestFrom(DS3232_I2C_ADDRESS, vBytesToRead); pD.second = bcdToDec(Wire.receive() & 0x7f); pD.minute = bcdToDec(Wire.receive() & 0x7f); pD.hour = bcdToDec(Wire.receive() & 0x3f); // Need to change this if 12 hour am/pm pD.dayOfWeek = bcdToDec(Wire.receive() & 0x07); //0= sunday pD.dayOfMonth = bcdToDec(Wire.receive() & 0x3f); pD.month = bcdToDec(Wire.receive() & 0x1f); pD.year = bcdToDec(Wire.receive()); Wire.endTransmission(); } void setControlRegisters(){ Wire.beginTransmission(DS3232_I2C_ADDRESS); Wire.send(0x0E); //Goto register 0Eh Wire.send(B00011100); Wire.send(B10000000); Wire.endTransmission(); } void setupRTC3232(){ Wire.begin(); setControlRegisters(); } char formatStrFileName[]="%02d%02d%02d%02d.txt"; char fileName[20];; } void setup() { setupRTC3232(); pinMode(16, OUTPUT); digitalWrite(16, LOW); pinMode(17, OUTPUT); digitalWrite(17, HIGH); card.init(); volume.init(card); root.openRoot(volume); getDateDS3232(); sprintf(fileName, formatStrFileName, pD.month, pD.dayOfMonth, pD.second, random(100)); file.open(root, fileName, O_CREAT | O_EXCL | O_WRITE); file.writeError = false; } char lineStr[50]; char lineFormat[] ="%02d%02d%02d %d %d %d"; int counter = 0; byte xlow, xhigh, ylow, yhigh, zlow, zhigh; int x, y, z; void loop() { counter++; getDateDS3232(); Wire.requestFrom(ACC_SENSOR_ADDR, 6); xlow = Wire.receive(); xhigh = Wire.receive(); ylow = Wire.receive(); yhigh = Wire.receive(); zlow = Wire.receive(); zhigh = Wire.receive(); x = xlow | xhigh << 8; y = ylow | yhigh << 8; z = zlow | zhigh << 8; sprintf(lineStr, lineFormat, pD.hour, pD.minute, pD.second, x, y, z); file.println(lineStr); if (counter == 100) { counter = 0; file.close(); file.open(root, fileName, O_CREAT | O_APPEND | O_WRITE); } delay(100); } As you can see from the code above, the accelerometer data is retrieved using the Wire.requestFrom statement, and 6 bytes are reassembled into the three integer values. A trick was used to prevent frequent write activities to the SD card. In the code above, we close the file handle at an interval of every 100 lines and re-open the file for the coming operations. As a draw back, if power is lost before the file handle closes, up to 100 line of data can be lost. But for long running data logging operations, this should not be an issue. The following images illustrate some of the data logged during a test run. In this particular case, I placed the data logger in my car and drove around the town. The accelerometer is in 2g mode and the recorded data has a 12bit resolution. The x axis data can be used to analyze the number of turns I made during that trip. The y axis data can be used to analyze the acceleration/deceleration and the z axis data can be used to analyze the road surface condition. The flat regions can be used to count how many times I had stopped in that trip. Even though the example I used above needed to code the data logger side specifically to accommodate the data coming from the accelerometer, this data logger code can be generalized a bit more to accommodate a larger set of I2C slave devices. One way to achieve this is as follows: Upon powering up, the slave would send a “magic” packet to the master, inside which the slave’s data type format (e.g. whether it is integer or byte) and data length (how many bytes are there in the payload) are included. As long as all the slaves use the same handshake packet data sequence, we can detect what specific data format (i.e. whether it is byte or integer and what is the length) a slave uses at the I2C master device side. The slave side code may look like the following (we use five consecutive 200’s as the magic packet and the data type and data length are immediately followed. In this case, we use 1 to represent integer and 2 to represent byte): #include <Wire.h> const int TWI_ADDR = 100; byte HAND_SHAKE_PACKET[]={200,200,200,200,200, 1, 10}; boolean configured = false; void TWIRequest() { if (configured) { byte ay1[] = {0,1,2,3,4,5,6,7,8,9}; Wire.send(ay1, 10); } else { Wire.send(HAND_SHAKE_PACKET,7); configured = true; } } void setup() { Wire.begin(TWI_ADDR); Wire.onRequest(TWIRequest); } void loop() { } On the I2C master’s side, we can use a fixed slave address. Note that the fixed address is only possible if the slave side is using the same device or the slave side uses a microcontroller. Since different slave devices may transmit data of different lengths, the I2C master need to be able to handle all the possibilities. One way to achieve this is to set the data length (NUM_DATAPOINTS) to be the longest among all possible I2C slaves. If the data provided to the I2C master is less than the preset data length, the received data would simply be 0’s after the desired length. A more elegant approach would be using the exact number of bytes indicated in the magic packet. Depending on the data type, the I2C master would handle the incoming data accordingly. The code on the I2C master side can be very complex, but the general approach can be illustrated as follows: #include <Wire.h> const int ACC_SENSOR_ADDR = 100; const int NUM_DATAPOINTS = 10; void setup() { Wire.begin(); } void loop() { Serial.println("------"); Wire.requestFrom(ACC_SENSOR_ADDR, NUM_DATAPOINTS); //procedures to handle the magic packets ... for (int i = 0 ; i < NUM_DATAPOINTS; i++) { byte d = Wire.receive(); //code to handle different data type depending on what is read from the master packet ... } delay(100); } Since the magic packet is only sent during a power cycle event on the I2C slave’s side, this approach requires the power at the master’s side to be stable. Should the I2C master loose power, it would not be able to infer the data type of the incoming packets unless the slave is restarted. More advanced messaging scheme can be address this shortcoming, but it is beyond the scope of this discussion.
http://www.kerrywong.com/2010/10/02/i2c-data-logger-using-atmega328p-and-ds3232-%E2%80%93-ii/
CC-MAIN-2020-29
refinedweb
1,414
65.93
bindresvport, bindresvport_sa - bind a socket to a privileged IP port Standard C Library (libc, -lc) #include <sys/types.h> #include <rpc/rpc.h> int bindresvport(int sd, struct sockaddr_in *sin); int bindresvport_sa(int sd, struct sockaddr *sa); bindresvport() and bindresvport_sa() are used to bind a socket descriptor to a. If the bind is successful, a 0 value is returned. A return value of -1 indicates an error, which is further specified in the global errno. [EPFNOSUPPORT] If second argument was supplied, and address family did not match between arguments. bindresvport() may also fail and set errno for any of the errors specified for the calls bind(2), getsockopt(2), or setsockopt(2). bind(2), getsockopt(2), setsockopt(2), ip(4) BSD November 22, 1987 BSD
https://nixdoc.net/man-pages/NetBSD/man3/bindresvport.3.html
CC-MAIN-2020-29
refinedweb
125
57.27
Quick Links RSS 2.0 Feeds Lottery News Event Calendar Latest Forum Topics Web Site Change Log RSS info, more feeds Topic closed. 22 replies. Last post 9 years ago by BaristaExpress. Given the high JP for Euromillions, I have been trying to figure out the best way to minimize income taxes and maximize interest income while still living in the U.S. I know that the actual JP is tax-free in Europe and that if the entire amount is brought into the U.S., then it is taxable. My question is if the JP money is left in Euros in a Swiss bank and is invested in European securities, then theoretically, the principal JP will never be taxed, only the interest income that is generated would be taxed, right? I ask the question, because I contacted the IRS and they told me that all income (global or domestic) is subject to income tax and must be reported on my tax return. Gambling winnings (including lottery winnings) are classified as income, therefore according to the IRS, I would be taxed on the prinicpal JP even if I left it in a European bank, plus I would be taxed on any interest income. So, assuming that what the IRS told me was correct and by my calculations, I would need to earn about 9% on my European investments on the taxed JP to match a 4% tax-free investment return in the US (municipal bonds and other triple tax free investments). If I am not taxed on the full JP but only on the interest income, then I would only need about a 5.3% European return - which leaves more room for a greater income generating potential. Plus, by leaving the prinicipal in Euros, I can lever the increasing strength of the Euro to the weakening dollar when I do decide to convert the currency and bring some money into the U.S. Does anyone have better information than I have been able to find? I am working on the assumption of being totally honest and not hiding money, though I always enjoy the "creative" solutions that LP members come up with. It would be strange if someone would win Euro Millions and then pay tax. It'll be a lot of income tax if only one ticket would win the Euro Millions jackpot. Allow me to clarify. If I were a resident and citizen of one of the Euromillions member countries, then it is my understanding that I would not pay taxes on the JP. But as a citizen and resident of the U.S., according to the IRS, I am required to pay income tax on any winnings whether foreign or domestic. Part of the discussion at LP about Euromillions has been on the fact that the JP is the cash value (fantastic!) and is tax-free if not brought into the U.S. But, the IRS seems to think that even if the JP is not brought into the U.S., it is still taxable if the winner is a resident and citizen of the U.S. It may even be taxable if I am a U.S. citizen residing in a European country if I file a U.S. income tax return (though I can qualify for a foreign tax exclusion up to $80,000). So, short of becoming a European citizen prior to claiming the JP, as a U.S. citizen, I would be taxed on the JP. I have thought of using an offshore LLC to claim the prize and then pay myself a salary from the LLC, thereby only being taxed on the salary that I decide to pay myself. But, that is a bit subversive and I am trying to see if there is a totally clean and honest way to avoid about $50 million in taxes. If not, then so be it. Any suggestions? I don't know where you guys get your figures, but the best I can find with a little research is that the tax on a foreign income is 25%. That's for an individual; however I think tax on foreign income for a Partnership or LLC are income tax free as long as none of there investments are in the USA or are Invested in a US company overseas. So I would get a really good team of tax attorneys and financial advisors together before I claimed the jackpot. Mabey Incorprate in Ireland, I hear they give lot's of tax breaks to Companies there much lower than in rest of Europe. Of course the IRS is going to say give us the money. Advice is usually worth what you pay for it. Ask a well qualified pro that deals with international tax. You will have to pay for that advice but if you win it will be well worth it. Indeed, yes, the IRS is going to say to give them the money. I was just curious to see if anyone else had given serious research into this hypothetical situation. As for the 25% tax rate on foreign income, foreign income is taxed at whatever tax bracket you are at, in the case of a massive JP like this, it would be the top bracket (currently 35%). And, yes, I would hire the best tax attorneys and financial advisors I could get before claiming the JP, but even some of the best attorneys may not be able to save me from the IRS if we run afoul of the current tax law. Besides, how do you find out who are the truly qualified individuals to hire? Not being in that circle, I would not know whom to hire. Likely, I would turn to the large investment firms and see where they take me. But, I did find an interesting article on secrecy and Swiss bank accounts for U.S. citizens. If I do not invest in any U.S. securities, then Swiss banks would not report the income to the IRS, thereby evading tax (which is legal in Switzerland but not necessarily in the U.S.). But, I still would have to pay taxes on what I pay myself from an offshore LLC, since that would technically be "earned income". Alas, given the huge JP, I would not be managing the money directly anyways, so I will leave the mental gymnastics up to my financial/legal team. So whether it is the full $177 million JP or ~$120 million after taxes, it is still an incredibly large sum of resources. What I will have to be concerned more with is my stewardship of the blessing than with whether or not I make $4 million or $7 million interest income each year, since either amount is more than what I would probably make in my lifetime! USA does its dern'est to confuse the average citizen from ever finding the loop holes or savings that can be made. And yes your correct- the percentage is 35-38%. Not including your state and local taxes having to be paid. So it racks up to 47% in some state areas. With that said, its wise to ask a tax lawyer . Most here are involved in winning and playing and not really qualified to give tax advice without a license. A tax lawyer has to go thru the exam and be qualified to look out for your best interest. Georgetown has a great program in tax law and has referral programs for folks when they do need a qualified attorney in this matter. ________________________________ Signature quote: Thinking positive never won me a lottery, Thinking negative never lost me a lottery, Playing it though, wins more often. If you were to win an overseas lottery why would you want to continue to live in America but not contribute to it in the form of taxation at the going rate? Taxation is part of the responsibility of being a U.S. citizen. Sure people don't enjoy paying taxes. But compared to the rest of the world the USA is a very comfortable society because of its infrastructure and public services and tax dollars go towards these. Tax dollars also get redistributed to help people on low wages and their families; people in their millions. Taxes also go towards paying for the military and other programs which Americans take for granted. Your avatar has a cross with the logo "All for Jesus". In your case you should change it to a dollar sign and say "All for Me". I agree!!! I find it ridiculous that the USA taxes lottery winnings. This is unheard of elsewhere. If you play the lottery does the US tax people give you a rebate if you win nothing? This appears to be the ultimate swindle by a government. If I was a US citizen and won the Eurolottery I would invest it in Europe and not tell the US authorities. Better still, emigrate to Europe or Australia. Well, I too think the taxation of the lottos is a bit ridiculous. Good advice Zulu. Huh, as I see it, when big business/corporations pay very little or next to nothing in taxes and the average person pays 3-4 times more than they do, as an injustice to the majority in this country! And you can't tell me that there isn't a bunch of them out there that don't get Tax Credits every year and pay nothing every year or at the least, very, very little in taxes! So, when they start to pay their fair share, is the day I'll pay the IRS what it says I owe and not complain about it! But until then, I'll do my damnedest to keep the IRS out of my back pocket any way I can! So go waive the flag somewhere else! And if you even think of saying I'm anti- American or anything of the sort, it will be a lie for one! And second of all, you'll be showing nothing more than your ignorance! Keep dreaming the impossible dream, it just may come true! I think you missed the point of this hypothetical discussion and by the honesty disclaimer on my initial posting. I have no problem paying taxes, but I do not want to be fleeced by our already over zealous federal and state governments. Alas, the money would not be all for me. In fact, it would be "none for me", since the reason that I play the lottery at all is to meet the needs of others. As for as my needs, I am already taken care of by my Savior (John 3:16, Matthew 6). I need nothing more. Yet, I can only do so much or reach only so many people with the limited time and income that I have. With a gift from God of a larger financial base as a resource, my ministries would be able to expand. Yet, the ministries can still expand without the money, since all things are possible with Him and through Him. Indeed expansion without the money would be an even greater testament to His power and glory, since with the money, people can just say "oh, well the funding comes from a lottery win." As for taxes, I feel the U.S. government has overstepped its bounds in taxation and has become a bloated bureaucracy that wastes too much money. Our country has moved from the freedom-based republic created by the founding fathers to a socialist democracy where wealth is taken by force and redistributed by lawmakers whose primary objective is to keep their constituents happy with pork to get themselves re-elected. I know for certain that I could do a better job in stewardship. The Biblical model for taking care of the poor and needy was for people to help them directly, not to give all their money to the government and have it do it. By doing the work yourself, you are blessed with having blessed someone else. So in fact, it is a double blessing. My avatar "All for Jesus" with the Cross on it has a two-fold meaning. The Cross represents what He has done for me and the "All for Jesus" means every quark of my being, every work, every cent, every breath is for Him.? Normally, LP is a nice place to discuss topics in an intellectual manner. Everytime people try to start flame wars, I usually stay away for awhile. I thought perhaps this time would be different, but I guess I should just learn that I am bound to be attacked personally no matter what I discuss. But, hey, I do not really care what you think of me or how much you want to belittle me because of my views. The last time I checked, Todd still allowed people to voice their opinions on lottery topics here at LP and I was just trying to get an interesting discussion going. But, uh, oh well, so much for that. Take care and God bless! You complain about businesses avoiding tax but then want to be just like them and pay next to nothing yourself. And how much do you pay in things like sales tax living there in Delaware? Oh, that's right, you don't pay any sales tax. Yeah pal, you really can stand shoulder to shoulder with "the average person" you mention in your last comment. Poor you. You sound just like many people in that generation of Americans currently heading into retirement who feel just because you breathe air you should be given royal treatment and life should be free or better yet with cash back. It's clear from your remarks you really believe being selfish is the true mark of being an American. You're wrong of course but obviously you just felt the need to display your ignorance. You wrote: "But, hey, I do not really care what you think of me..." Really? So then why did you write eight paragraphs and quote scripture if you really don't care? You wrote: ?" Jesus said: "Go and sell ALL that thou hast, and give it to the poor; and come and follow me." From your original remarks of seeking advice on tax avoidance using off shore bank accounts it is very clear you are quite prepared to keep everything you get strictly for yourself. If you really want to pick up your cross then give away all the money and assets you currently own to the poor. And remember that every little bit helps so don't say the challenge is too great and therefore you won't do it. There are plenty of well established charities of every single denomination out there too so you don't need to set up your own "ministry" first to channel funds or complain that government redistribution is socialist or inefficient. Few people actually give away all they have to the poor because most people realize that doing so would force them to join the ranks of the poor. Jesus lived a life of poverty and if you are a true beliver then you will as well. Greed comes in many ways and trying to hide it by praying to a divine power for vast sums of money as well as telling others far and wide that you'll use such a huge fortune to help others really doesn't wash. Bill Gates and other wealthy philanthropists have already beat you to the punch on that so you don't need to wait to you are filthy rich to start giving. God doesn't dare us to keep anything. I dare you though to give all you own now away because you know yourself there many people out there who are in greater need for your belongings. Eye of the Needle, buddy, Eye of the Needle. But take the log out of your own eye first; it should help you see life a lot more.
http://www.lotterypost.com/thread/127104
CC-MAIN-2014-52
refinedweb
2,683
68.81
30 July 2013 17:24 [Source: ICIS news] HOUSTON (ICIS)--With prices so low that no one really wants to sell product, the August US butadiene (BD) contract has settled, with a separate price from nearly every one of the four main ?xml:namespace> Two producers have set their August price at 40 cents/lb ($882/tonne, €662/tonne), one producer has set its price at 46 cents/lb, and another has set its price at 47 cents/lb, sources said. who account for about 85% of US BD production in January was 76 cents/lb. It rose to 84 cents/lb in March and April and early-year forecasts had BD rising to over $1/lb. But then the replacement-tyre market collapsed, and demand for BD and styrene-butadiene-rubber (SBR) along with it. About 85% of BD production goes to make SBR for tyres. In May, the monthly Compared with the lowest proposed August contract price of 40 cents/lb, the Major BD producers in the US include ExxonMobil, LyondellBasell, Shell
http://www.icis.com/Articles/2013/07/30/9692394/august-us-bd-contract-falls-to-40-47-centslb-in-split-settlement.html
CC-MAIN-2014-41
refinedweb
174
65.46
Statements outside of explicit transactions in SQLite (1) By James Oldfield (james.oldfield) on 2021-01-03 18:00:10 [link] [source] There's a lot of waffle below, but I suppose you could summarise it all as: What happens to statements outside of explicit transactions? The documentation seems a bit unclear on this (although it's usually excellent by the way, many thanks for that). Autocommit mode vs implicit transactions: Oddly, the section on implicit transactions doesn't mention autocommit mode. Autocommit mode only seems to be mentioned in passing on the sqlite3_get_autocommit(), which conversely doesn't mention implicit transactions! But both talk about statements not executed within an explicit transaction ( BEGIN and COMMIT/ ROLLBACK), so those are related... right? Am I right in thinking that an implicit transactions are only ever started when in autocommit mode, and conversely any statement executed in autocommit mode (except BEGIN ...) will start an implicit transaction? Implicit transactions with multiple statements: This is my key confusion, where the documentation doesn't seem to match reality. The section on implicit transactions, linked above, says: An implicit transaction ... is committed automatically when the last active statement finishes. A statement finishes when its last cursor closes ... So I tried a test: In one thread, I ran a SELECT statement, but in between retrieving rows (2 at a time) I INSERTed some more rows (1 at a time) and did deliberate pauses. In another thread, using a different connection, I repeatedly did a SELECT COUNT(*). From what I understand of that quote, the SELECT and INSERTs in the first thread should have consisted of a single implicit transaction, because the "last active statement" on that connection had not yet finished (I hadn't reset the SELECT, and indeed continued to retrieve more rows through it afterwards). But, instead, the COUNT(*) kept increasing on the other thread, showing that the INSERT had committed immediately. Is that quoted text correct? Does it mean something different than I interpreted it? (Just to be clear: I'm actually very happy that statements not in a transaction are committed immediately, even when a cursor for a SELECT statement is also open. It's just that I'm confused about what the documentation is referring to.) Can an implicit transaction hold up an explicit transaction being committed: The document File Locking And Concurrency In SQLite Version 3 mentions: The SQL command "COMMIT" does not actually commit the changes to disk. It just turns autocommit back on. Then, at the conclusion of the command, the regular autocommit logic takes over and causes the actual commit to disk to occur. But according to that earlier quotation, an implicit transaction won't be committed if a cursor is still open. Does this mean that even an explicit COMMIT statement for an explicit transaction might not actually commit data right away, if a cursor is still open from a statement? That would be very surprising! It seems not, given my previous experiment, but I just wanted to confirm this. (2) By Tim Streater (Clothears) on 2021-01-03 19:20:12 in reply to 1 [source] Far as I know, any isolated statement (select, insert, etc) is automatically surrounded by BEGIN/COMMIT unless you've already opened an explicit BEGIN. My app has a couple of hundred usually isolated statements to update this or that part of some db or other. If I had to BEGIN/COMMIT each of these life would be rather tedious. I also have a couple of places where I know I'll be doing a lot of inserts, so I do all those inside a transaction, for speed. That clear? (3) By Keith Medcalf (kmedcalf) on 2021-01-03 19:27:40 in reply to 1 [link] [source] Your description is accurate. "Transaction" processing is controlled by "locks". All "lock" processing is "automatic". An "explicit transaction" is merely exerting manual control by "turning off (BEGIN) and on (COMMIT)" the automation. A "read-lock" is required when reading from the database, and a "write-lock" is required to write to it (and exclusive access -- meaning no OTHER readers -- is required to "make it so"). Every statement, when executed, must acquire the locks that it requires for the duration of its execution. When the statement completes, the additional locks that the statement acquired are released. Locks which were already acquired on the same connection will not be released until that other statement that acquired them is complete. This means that when you execute a SELECT statement on a connection, it will acquire a READ lock for the entire duration of the statement execution. If while this statement is executing you execute an INSERT statement (on the same connection), that connection must acquire a WRITE lock. When that INSERT statement completes then the data is written (assuming there is NO OTHER CONNECTION that has a READ lock by temporarily acquiring an EXCLUSIVE lock and writing the data) and releases the WRITE lock. It cannot release the READ lock because the SELECT still requires it. Once the SELECT statement is complete, then the READ lock can be released. The BEGIN statement makes some small changes to this process. It sets a flag that stops the "automatic release of acquired locks". In addition it may also acquire a specific lock type at the time it is executed though the default is just to set the flag and not acquire any locks. If you use the form BEGIN IMMEDIATE, then a WRITE lock is obtained immediately as well as turning off the "auto release mode". Mutatis Mutandis BEGIN EXCLUSIVE with an EXCLUSIVE lock. Now when you make changes (ie, execute an INSERT statement) and the "auto release" mechanism is turned off, the WRITE lock is held after the statement completes and the changes are not yet written to the database. Eventually a COMMIT statement will be executed. This will "turn the auto-release" flag back on and when the COMMIT statement ends it will release the locks THAT ARE NO LONGER REQUIRED (in the case of releasing an EXCLUSIVE or WRITE lock, it will write the changes to the database). However, if there is a statement executing which requires a READ lock then that read lock will not be released until that statement ends (which will now release its locks because the "auto-release" flag has now been turned back on). (4.1) By Keith Medcalf (kmedcalf) on 2021-01-03 19:42:55 edited from 4.0 in reply to 3 [link] [source] This "auto-release" process and the flag are called "auto-commit". What it means is that lock levels that are no longer required are "automatically released and associated data is committed to the database in the case of a WRITE lock" when a statement ends. BEGIN and COMMIT merely disable and enable this flag. The process of lock acquisition by a connection and the statements executing on it is unchanged. (5) By James Oldfield (james.oldfield) on 2021-01-04 22:21:57 in reply to 4.1 [link] [source] Many thanks for this very comprehensive reply. It's much appreciated, especially since I can see there's a continuous deluge of questions here. Out of curiosity, I made a little of test of what you said, and verified it's correct (although I never doubted it): On one connection I executed BEGIN, then SELECT and started iterating over the results, then COMMIT and continued iterating over the earlier cursor. On another connection I repeatedly tried executing INSERT statements. This was in journaling mode so the SELECT held up the INSERTs as expected. Sure enough, as you said, this did not release on the COMMIT, and instead the INSERT only progressed once the SELECT was exhausted. I have to admit, I find this very surprising. I'd expect COMMIT (or ROLLBACK) to release all locks, and an attempt to continue using an open statement from before to result in an error, something like "transaction for that statement has now been closed". Now I know, I'll be more careful about resetting incompletely iterated statements! (I'm actually using the Python sqlite3 wrapper module, so this translates to calling .close() on the Cursor object in that API.) I have a follow up question: Are there are any statements that write to the database but return multiple rows? I just ask because, if so, that would mean that an open cursor to such a statement would cause the write lock to be retained even after a COMMIT. Assuming that's not the case, we can always be sure a successful COMMIT will at least store all data in the database, even if it potentially doesn't release a read lock. (6) By Keith Medcalf (kmedcalf) on 2021-01-04 23:09:52 in reply to 5 [link] [source] All statements which "write" to the database occur within the processing of that one statement. The only statements which can "write" to the database are CREATE, INSERT, UPDATE, DELETE, ALTER, and DROP (I think I got them all). In each case the database change (the writing) is entirely contained within the single "execution" of the statement (that is, the statement runs to entirely to completion in a single sqlite3_step). The execution state is not "held open" because there is no actual cursor involved (no result generator). This is in contrast to a SELECT statement which is conceptually similar to a Python generator function. The first sqlite3_step causes the statement to begin execution (and obtain a read lock), and it then yields a row, and each time it is subsequently stepped, until eventually it runs out of rows (raises a StopIteration exception) at which point the execution context is closed (and the read lock released, if autocommit is in effect). That is, it ends up looking like this: def Statement() beginingLockState = getReadLock() while (row := findNextResult()) is not None: yield row if autocommit is True: releaseLocksExcept(beginningLockState) There have been occasional requests to implement INSERT ... RETURNING ... and UPDATE ... RETURNING ... which would mean that those statements would generate result rows while executing their updates (although there are other methods which could be used to obtain the same effect without having to have the RETURNING clause that could already be implemented with existing facilities, doing that is complicated and some people are lazy). At present, however, RETURNING is not implemented so all SQL statements which can perform updates are single-step execution contexts and only the SELECT statement is a result generator. Note that the PRAGMA statement is a special case and may fall into either class (or in some cases is performed at PREPARE time and does not require execution at all) depending on the particular PRAGMA. (7) By Keith Medcalf (kmedcalf) on 2021-01-04 23:24:52 in reply to 5 [link] [source] Also note that the Python sqlite3 wrapper automagically manages the transaction state for you (success at this depends on the version of the PySqlite2 extension code that the wrapper is using -- newer versions use a better detection of "write" statements and old ones are limited by guessing based on the first word in the SQL statement). This automagic is controlled by the isolation_level parameter of the sqlite3.connect function. If the isolation_level is not None (the default is '', an empty string) then it must be a character string which is appended to a BEGIN statement that is automagically executed before any write statement. To turn off the automagic you need to open the connection with isolation_level=None. See also APSW that behaves more like sqlite3 and less like a lowest-common-denominator DB-API interface. (8.1) By James Oldfield (james.oldfield) on 2021-01-05 14:19:51 edited from 8.0 in reply to 7 [link] [source] Thanks for another great reply. Yes, the Python sqlite3 wrapper sometimes fiddles with transactions automatically. I actually started this whole process by innocently wondering how to start and stop transactions and ended up much further down the rabbit hole than I intended! At some point I hope to document my findings in a StackOverflow answer which, no doubt, no one will ever read :-) I'll include a note about closing cursors for incompletely exhausted SELECT statements. As a result, I've spent a lot of time reading the source code to sqlite3 and pysqlite recently. Sadly, I can tell you that the logic for when to automatically start a transaction in sqlite3 does still depend on textual matching: if the statement starts with INSERT, UPDATE, DELETE or REPLACE (intended to catch DML statements) then a transaction is started just before executing the statement itself. This comparison skips over whitespace but not comments (e.g. "/*foo*/INSERT ..." is not considered to start with INSERT). This only happens if isolation_mode is not None, as you said, and only if a transaction is not already started (as determined with sqlite3_get_autocommit(), so it will notice transactions started by the developer manually executing BEGIN). It's true that there was a move in the past to away from statement parsing. Here's how the situation got (back) to this point: In the past (before Python 3.6 and before pysqlite 2.8.0), some statements would cause an implicit COMMIT beforehand (if a transaction was open, as determined with !sqlite3_get_autocommit()). Again, this only happened if isolation_mode is not None. The rule was: if a statement started with INSERT, UPDATE, DELETE or REPLACE (intended to catch DML), BEGIN a transaction; if it started with SELECT (i.e. DQL), do nothing; otherwise (this case is meant to catch DDL like CREATE TABLE), COMMIT a transaction. Then pysqlite (commit 94eae50) got rid of all the above logic, and replaced it with simply: if !sqlite3_stmt_readonly() then start a transaction. That got rid of all the statement parsing, and the removal of the implicit transaction COMMIT meant you could include DDL like CREATE TABLE in a transaction implicitly started by pysqlite. But this exact version of the code never made it into a release. The next day, the logic was changed (commit 796b3af) to if !sqlite3_stmt_readonly() && !is_ddl then start a transaction, where is_ddl was defined as a statement starting with CREATE, DROP or INDEX, so there was still text matching in there. This was done to improve backwards compatibility with existing code. This version still never implicitly committed transactions. This was released as pysqlite 2.8.0. That is still how it stands to this day, and is unlikely to change given that its readme says "This project is not actively maintained any more: You are better off using the sqlite3 module in the Python standard library". This was initially merged into Python 3.6 beta, but issue 28518 was raised about backwards compatibility: conn.execute("BEGIN IMMEDIATE"), which had previously worked, would raise an exception "cannot start a transaction within a transaction". That's because this is not a read only statement (as explained in a comment by D. Richard Hipp), so a transaction was now being started automatically just before it was executed. Such statements are better suited to isolation_mode = None, but the issued showed the change would've broken existing code, so before Python 3.6 was released the code was changed to the current logic. Compared to Python 3.5, that meant that only the "otherwise" branch had really changed, and the release notes simply said "sqlite3 no longer implicitly commits an open transaction before DDL statements". Funnily enough, the DB API spec - which as you said is the motivation for all this funkiness - says that a transaction should be opened before any statement at all, even a SELECT. This isn't clear from the document itself but I came across an archived email from the PEP author that says this is what they intended (but I can't find the link at the moment). Given that sqlite3 doesn't satisfy the spec, all this automagic behaviour seems like wasted effort!
https://sqlite.org/forum/info/c5c281dce2d04e80
CC-MAIN-2021-49
refinedweb
2,658
59.74
The path element line is used to draw a straight line to a point in the specified coordinates from the current position. It is represented by a class named LineTo. This class belongs to the package javafx.scene.shape. This class has 2 properties of the double datatype namely − X − The x coordinate of the point to which a line is to be drawn from the current position. Y − The y coordinate of the point to which a line is to be drawn from the current position. To draw a line, you need to pass values to these properties. This can be either done by passing them to the constructor of this class, in the same order, at the time of instantiation, as shown below − LineTO line = new LineTo(x, y); Or, by using their respective setter methods as follows − setX(value); setY(value); To draw a line to a specified point from the current position the path class object as shown below. //Creating a Path object Path path = new Path(); Create the MoveTo path element and set the XY coordinates line by instantiating the class named LineTo which belongs to the package javafx.scene.shape as follows. //Creating an object of the class LineTo LineTo lineTo = new LineTo(); Specify the coordinates of the point to which a line is to be drawn from the current position. This can be done by setting the properties x and y using their respective setter methods as shown in the following code block. //Setting the Properties of the line element lineTo.setX(500.0f); lineTo.setY(150.0f); Add the path elements MoveTo and LineTo created in the previous steps to the observable list of the Path class as shown below − //Adding the path elements to Observable list of the Path class path.getElements().add(moveTo); path.getElements().add(lineTo); Create a group object by instantiating the class named Group, which belongs to the package javafx.scene. Pass the Line (node) object created in the previous step as a parameter to the constructor of the Group class. This should); } The following program shows how to draw a straight line from the current point to a specified position using the class Path of JavaFX. Save this code in a file with the name LineToExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.LineTo; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; import javafx.stage.Stage; public class LineToExample extends Application { @Override public void start(Stage stage) { //Creating a Path object Path path = new Path(); //Moving to the starting point MoveTo moveTo = new MoveTo(); moveTo.setX(100.0f); moveTo.setY(150.0f); //Instantiating the LineTo class LineTo lineTo = new LineTo(); //Setting the Properties of the line element lineTo.setX(500.0f); lineTo.setY(150.0f); //Adding the path elements to Observable list of the Path class path.getElements().add(moveTo); path.getElements().add(lineTo); //Creating a Group object Group root = new Group(path); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle("Drawing a Line"); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. javac LineToExample.java java LineToExample On executing, the above program generates a JavaFX window displaying a straight line, which is drawn from the current position to the specified point, as shown below.
https://www.tutorialspoint.com/javafx/2dshapes_lineto.htm
CC-MAIN-2020-05
refinedweb
591
54.32
THIS IS AN UNOFFICIAL, FAN-MADE WRAPPER. IT IS IN NO WAY ENDORSED BY TWITCH.TV What is It?What is It? Swift Twitch is a library intended for client-facing applications interaction with the New Twitch API, Helix. This library aims to ease API interaction by returning typed data values to help you finish your application without headaches. For example, after a non-empty Get Videos call, you can do the following: let firstVideoData: VideoData = getVideosData.videoData.first! let title: String = firstVideoData.title let viewCount: Int = firstVideoData.viewCount Available API CallsAvailable API Calls You can run the following API calls: DocumentationDocumentation New Twitch API (Helix) Documentation Swift Twitch Documentation Example UsageExample Usage How to check if a user is following another user import SwiftTwitch class AwesomeClass { func spectacularFunction() { TwitchTokenManager.shared.accessToken = "$SomeValidToken" let user1Id = "1234" let user2Id = "5678" Twitch.Users.getUsersFollows(followerId: user1Id, followedId: user2Id) { result in switch result { case .success(let getUsersFollowsData): /* If the total = 1, we know that user1 is following user2 as it is documented in the Twitch API docs. */ if getUsersFollowsData.total == 1 { print("User \(user1Id) is following user \(user2Id)!") } else { print("User \(user1Id) is not following user \(user2Id)") } case .failure(let data, let response, let error): print("The API call failed! Unable to determine relationship.") } } } } I don't have an access token!I don't have an access token! In order to use this library, you must first have an application register on the Twitch Developer portal. You can register your application quickly on Twitch's official application creation dashboard. After this step, there are two methods to retrieving API keys. Manually Retrieve Access TokenManually Retrieve Access Token To manually retrieve an access token, please utilize this guide by Twitch. Automatically Retrieve Access TokenAutomatically Retrieve Access Token I'm in the process of creating an pain-free way to retrieve tokens with a separate library! Feel free to email me at [email protected] and I'll inform you when the library is public. I have my access token, now what?I have my access token, now what? Now that you have an access token, you can provide it to the application in the following manner: TwitchTokenManager.shared.accessToken = "$Your_Token" Once this command is run, all of your API calls are now automatically authenticated! Now go make some API calls. :) I still have questions!I still have questions! For Twitch Swift support, feel free to open up an issue. For API-based support, please visit The Twitch Developer Forums Example ProjectExample Project To run the example project, clone the repo, and run pod install from the Example directory. After that, open the resulting .xcworkspace file and go nuts! The example project is a simple Videos browser for a pre-selected user on Twitch. To run the example project properly, you will need an access token. Set this access token in TwitchVideosTableViewController's viewDidLoad method. InstallationInstallation - Add this repo to your Podfile target 'Example' do # IMPORTANT: Make sure use_frameworks! is included at the top of the file use_frameworks! pod 'SwiftTwitch' end Run pod installin the podfile directory from your terminal Open up the .xcworkspacethat CocoaPods created Done! LicenseLicense SwiftTwitch is available under the MIT license. See the LICENSE file for more info.
https://cocoapods.org/pods/SwiftTwitch
CC-MAIN-2019-35
refinedweb
536
51.65
All I want to do is write one long int to offset 0x18 and another separate long int to offset 0x1C into a file I've opened. These offsets always contain the relevant data for the file format I'm processing, so there's no need to worry about that--all I need to do is make the value at these addresses equal to some specified number. I have no problem opening the file, but I'm not sure how to accomplish this since I'm not very experienced with C. Right now I'm opening the file in write mode with fopen(), seeking to 0x18 with fseek, writing "XXXXX" with fputs (XXXXX is just some number), seeking again to 0x1C, doing the same thing again, and closing the file. Not only do I feel like this approach is mistaken, it also does nothing and I have no idea why. Am I right and I should be going about this some other way, or am I just missing something? EDIT: Code: void modify_data(unsigned long int samp1, unsigned long int samp2, char fname[]) { FILE * newfile; newfile = fopen(fname, "w"); fseek(newfile, 0x18, SEEK_SET); fputs("180000", newfile); // 180000 is a placeholder while I test fseek(newfile, 0x1C, SEEK_SET); fputs("600000", newfile); // 600000 is a placeholder while I test fclose(newfile); } int main(int argc, char * argv[]) { char fname[sizeof(argv[1])]; strcpy(fname, argv[1]); modify_data(0, 0, fname); // the first two arguments are placeholders while I test return 0; } You probably want this: #include <stdio.h> void modify_data(unsigned int samp1, unsigned int samp2, char fname[]) { FILE * newfile; newfile = fopen(fname, "r+"); // or "r+b" on Windows if (newfile != NULL) { printf("Could not open file"); return; } fseek(newfile, 0x18, SEEK_SET); fwrite(&samp1, sizeof (unsigned int), 1, newfile); fseek(newfile, 0x1c, SEEK_SET); fwrite(&samp2, sizeof (unsigned int), 1, newfile); } int main(int argc, char * argv[]) { modify_data(0, 0, argv[1]); // the first two arguments are placeholders while I test return 0; }
https://codedump.io/share/668AoFjEdAoE/1/how-to-write-to-a-specific-address-in-a-file-in-c
CC-MAIN-2016-44
refinedweb
330
54.9
I don't get why you use fgets. If it's an ASCII file, and it should be for the thing you're trying to do, all you need to do is strstr(buff, find) and then memcpy. Not strcpy, in an ASCII file aren't any NULL bytes. Well, not that I know of. I've never encountered NULL bytes in an ASCII file. So it'd be more like this: //read in the whole file char *ptr = strstr(buf, find); memcpy(ptr, find, sizeof(char) * strlen(find)); Something like that. SOMENAME: C does not lend itself to easily extracting and replacing arbitrary text from a file. you can do it, only if the field from which you are extracting/replacing is a FIXED WIDTH. there can not be any variation in the width of the text field. if thats the case, then you can use a combination of functions like FSEEK, FTELL and REWIND. if its not the case (and it tends to not be the case for typical applications), then you will need to: --open the original file for reading --open a new file for writing --read orig file one line at a time, modifing as needed --write that line to the new file. --when done, delete the original file --rename the new file with the original file's name. sucks, i know. if you really need to get into serious text file manipulation, you might look into Perl. but that's a whole 'nother can of worms. . SOMENAME: you're essentially on the right track, and you've basically got it. i think you're getting bogged down in some detail or other. check this out, and see how it's pretty much what you're doing: #include <stdio.h> #include <string.h> #define MAX_LEN_SINGLE_LINE 120 // ? int main() { const char fileOrig[32] = "myOriginalFile.txt"; const char fileRepl[32] = "myReplacedFile.txt"; const char text2find[80] = "lookforme"; const char text2repl[80] = "REPLACE_WITH_THIS"; char buffer[MAX_LEN_SINGLE_LINE+2]; char *buff_ptr, *find_ptr; FILE *fp1, *fp2; size_t find_len = strlen(text2find); fp1 = fopen(fileOrig,"r"); fp2 = fopen(fileRepl,"w"); while(fgets(buffer,MAX_LEN_SINGLE_LINE+2,fp1)) { buff_ptr = buffer; while ((find_ptr = strstr(buff_ptr,text2find))) { while(buff_ptr < find_ptr) fputc((int)*buff_ptr++,fp2); fputs(text2repl,fp2); buff_ptr += find_len; } fputs(buff_ptr,fp2); } fclose(fp2); fclose(fp1); return 0; } it has a couple caveats... it requires that you #define the max length of a file line. any that exceed that length are at risk of missing an instance of the search text. could be a candidate for a carefully implemented malloc() call also, it won't find a search text that is split across two lines. which would be a serious flaw in many situations. . would jephthah's code work with outputting to the SAME file? Not as-is. To be completely safe you'd want to write to a temporary file first. Then delete the original and rename the temporary to the original. Reading from and writing to the same file line by line, if it works at all due to file locking, would be very likely to corrupt subsequent reads.
https://www.daniweb.com/software-development/c/threads/125898/find-and-replace-string-in-a-text-file
CC-MAIN-2015-18
refinedweb
513
73.37
The following is a guest blog post by Nathan Franzen, Software Engineer at StackPointCloud. StackPointCloud is the creator of Stackpoint.io, the leading multi-cloud management platform for cloud native workloads. They are the developers of the Cloudflare Ingress Controller for Kubernetes. Deploying Applications on Minikube with Argo Tunnels This article assumes basic knowledge of Kubernetes. If you're not familiar with Kubernetes, visit to learn the basics. Minikube is a tool which allows you to run a Kubernetes cluster locally. It’s not only a great way to experiment with Kubernetes, but also a great way to try out deploying services using a reverse tunnel. At Cloudflare, we've created a product called Argo Tunnel which allows you to host services through a tunnel using Cloudflare as your edge. Tunnels provide a way to expose your services to the internet by creating a connection to Cloudflare's edge and routing your traffic over it. Since your service is creating its own outbound connection to the edge, you don’t have to open ports, configure a firewall, or even have a public IP address for your service. All traffic flows through Cloudflare, blocking attacks and intrusion attempts before they ever make it to you, completely securing your origin. Deploying your service to more locations around the world is as simple as spinning up more containers. Anything which uses the Ingress Controller will receive your traffic, wherever the container is running in the world or on the Internet. Tunnels make it simpler to have robust security even while deploying across multiple regions or cloud providers. Usually Minikube applications need to be ported over to a production Kubernetes setup to be deployed, but with Argo Tunnel, you can easily deploy a locally-running yet publicly-available Minikube instance making it a great way to try out both Kubernetes and Argo Tunnel. In this example, we’ll create a simple microservice that returns data when given a key, deploy it into Minikube, and start up the Argo Tunnel machinery to get it exposed to the Internet. Getting Started with an Application API We'll start by by creating a web service in Python using Flask. We'll write a simple application to represent a small piece of an API in just a few lines of code. The complete application, secret_token.py is simply: from flask import Flask, jsonify, abort app = Flask(__name__) @app.route('/api/v1/token/<key>', methods=['GET']) def token(key): test_data = { "e8990ab9be26": "3OX9+p39QLIvE6+x/w=", "b01323031589": "wBvlo9G7Wqxsb2P9YS=", } secret = test_data.get(key) if secret is None: abort(404) return jsonify({"key": key, "token": secret}) This tiny service will simply respond to a GET request with some secret data, given a key. Using Docker We’ll take the next step toward deployment and package our application into a portable Docker image with a Dockerfile: FROM python:alpine3.7 RUN pip install flask gunicorn COPY secret_token.py . CMD gunicorn -b 0.0.0.0:8000 secret_token:app This will allow us to define a Docker image, the blueprint for the containers Minikube will build. Deploying into Minikube If you don't have Minikube installed, install it here: Usually, we would build the Docker image with our Docker daemon and push it to a repository where the cluster can access it. With Minikube, however, that’s a round-trip we don’t need. We can share the Minikube Docker daemon with the Docker build process and avoid pushing to a cloud repository: $ eval $(minikube docker-env) $ docker build -t myrepo/secret_token . The image is now present on the Minikube VM where Kubernetes is running. In a production Kubernetes system, we might spend a good deal of time going over the details of the deployment and service manifests, but kubectl run provides a simple way to get the basic app up and running. We add the image-pull-policy flag to make sure that Kubernetes doesn’t first try to pull the image remotely from Docker Hub. $ kubectl run token --image myrepo/secret_token --expose --port 8000 --image-pull-policy=IfNotPresent --replicas=3 We now have a Kubernetes deployment running with our 3 replicas of containers built from our image, and a service associated with it that exposes port 8000. Save the two manifests locally into files: kubectl get deployment token --export -o yaml > deployment.yaml kubectl get svc token --export -o yaml > service.yaml We’ll be able to edit these files to make changes to our cluster configuration. For local testing, let's change that service so that it exposes a NodePort -- this will proxy the service to a port on the Minikube VM. Replace the spec in the service.yaml file with: spec: ports: - nodePort: 32080 port: 8000 protocol: TCP targetPort: 8000 selector: run: token sessionAffinity: None type: NodePort And apply the change to our cluster: $ kubectl apply -f service.yaml Now, we can test locally with curl, reaching the service via the NodePort on the Minikube VM: $ minikube start $ export MINIKUBE_IP=$(minikube ip) $ curl Using Cloudflare’s Argo Tunnel The NodePort setup is fine for testing the application locally, but if we want to share this service with others or better simulate how it will work in the real world, we need to expose it to the internet. In most cases, this means running in a cloud environment and dealing with load balancer configuration or setting up an NGINX ingress controller and dealing with network rules and routing. The Cloudflare Argo Tunnel Ingress Controller allows us to route almost anything to a Cloudflare domain, including services running inside of Minikube. In the Kubernetes cluster, an ingress is an object that describes how we want our service exposed on the internet and an ingress-controller is the process that actually exposes it. To install the Cloudflare Ingress Controller, you’ll need to have a Cloudflare domain and an Argo Tunnel certificate, configured with the cloudflared application. kubectl run was fine for quickly installing the test application, but for more complex installations, helm is a great tool, and is used to package the Cloudflare agent. Once you have the helm client installed, a simple helm init will configure Minikube to work with it. The chart for the ingress controller is found at the trusted-charts public repository and can be installed directly from there. Cloudflared Configuration Cloudflared is the end of the tunnel that runs on your machine and proxies traffic to and from your origin server through the tunnel. If you don't have it installed already, the cloudflared application complete quickstart instructions can be found at Installing the Controller with Helm Now we will run some commands that define the repository that holds our chart and override a few default values: $ helm repo add trusted-charts $ DOMAIN=anthopleura.net $ CERT_B64=$(base64 -w0 ~/.cloudflared/cert.pem 2>/dev/null|| base64 ~/.cloudflared/cert.pem) $ NS="default" $ USE_RBAC=true $ NAME=cloudflare $ helm install --name $NAME --namespace $NS \ --set rbac.install=$USE_RBAC \ --set secret.install=true \ --set secret.domain=$DOMAIN,secret.certificate_b64=$CERT_B64 \ trusted-charts/argo-ingress This installation configures two cloudflare-warp-ingress controller replicas so that any service we expose will get two separate tunnels to the Cloudflare edge, paired together in a single pool. Exposing Our Application with an Ingress We'll need to write an ingress definition. Create a file called warp-controller.yaml: apiVersion: extensions/v1beta1 kind: Ingress metadata: annotations: kubernetes.io/ingress.class: argo-tunnel name: token namespace: default spec: rules: - host: token.anthopleura.net http: paths: - backend: serviceName: token servicePort: 8000 And apply the definition: $ kubectl apply -f service.yaml Examining the deployment $ kubectl get pod Should print: NAME READY STATUS RESTARTS AGE cloudflare-argo-ingress-6b886994b-52fsl 1/1 Running 0 34s token-766cd8dd4c-bmksw 1/1 Running 0 2m token-766cd8dd4c-l8gkw 1/1 Running 0 2m token-766cd8dd4c-p2phg 1/1 Running 0 2m The output shows the three token pods and the cloudflare-warp-ingress pod. Examine the logs from the argo pod to see the activity of the ingress controller: $ kubectl logs cloudflare-argo-ingress-6b886994b-52fsl The controller watches the cluster for creation of ingresses, services and pods. The endpoint is live at returning { "key": "e8990ab9be26", "token": "3OX9+p39QLIvE6+x/YK4DxWWCFi/D+c7g99c14oNB8g=" } Now this small piece of an api is available publicly on the internet for testing. Obviously you don’t want to serve public traffic into a minikube instance, but it’s certainly handy for sharing preliminary work across development teams. The Cloudflare dashboard under the analytics tab will show some general statistics about the requests to your zone. Routing and relationships A quick sketch of the routing in the Kubernetes cluster and from the Cloudflare network: The warp controller pods provide a way for Argo Tunnels to connect the pods containing your application to the internet through Cloudflare's edge. Going farther with Cloudflare Load Balancers This demo exposes a service through a single Argo Tunnel. If your Cloudflare account is enabled with load balancing, you can route traffic through a load balancer and pool of tunnels instead, by adding the annotation argo.cloudflare.com/lb-pool=token to the ingress. For details of load balancer routing and weighting please refer to the Cloudflare docs. If you do use load balancing, then it is possible to run multiple instances of the ingress controller. When installing from the helm chart, set the value replicaCount to two or more and get multiple instances of the controller in the minikube cluster. The configuration will be useful for high availability in a single cluster. Load balancing can also be used to spread traffic across multiple clusters with different argo ingress controllers connecting to the same load balancing pool. With two ingress controllers, the Cloudflare UI will show a pool named token.anthopleura.net with two origins with tunnel ids as origin addresses:
https://blog.cloudflare.com/minikube-cloudflare/
CC-MAIN-2018-30
refinedweb
1,639
51.68
Comment on Tutorial - wait(), notify() and notifyAll() in Java - A tutorial By Jagan Comment Added by : aatish Comment Added at : 2011-09-14 09:52:28 Comment on Tutorial : wait(), notify() and notifyAll() in Java - A tutorial By Jagan I could not understand, anyone having an easier example with simple explanation then plz: diana jeng at 2009-04-21 03:50:39 2. #include <iostream> using namespace s View Tutorial By: Jorgeus at 2012-08-30 09:07:03 3. Awesome............ View Tutorial By: Amol at 2011-06-11 05:32:49 4. excellent, thanks a lot.............. View Tutorial By: yellareddy at 2013-03-12 06:56:12 5. Nice tutorial, I got how it's done, but the differ View Tutorial By: FriendlyNoob at 2015-07-20 17:27:08 6. I have got "time out at step 6". How can View Tutorial By: MCHON at 2008-10-05 12:36:42 7. import gnu.io.*; import java.io.*; < View Tutorial By: Anonymous at 2013-03-29 02:39:00 8. For Jaime, Maybe using JavaScript f View Tutorial By: Jair Aviles at 2011-11-22 05:49:05 9. very good.... View Tutorial By: satish at 2010-03-03 22:47:25 10. w0w amazing View Tutorial By: elvin at 2009-01-05 01:00:13
https://java-samples.com/showcomment.php?commentid=36697
CC-MAIN-2022-21
refinedweb
218
65.42
How to style GridPane each grid's border934225 May 5, 2012 2:33 PM I wants to style gridPane like a table that each cell have border. But when I add below code, it just outer most rectangle have border, but inner cell didn't have border. This content has been marked as final. Show 2 replies 1. Re: How to style GridPane each grid's borderjsmith May 7, 2012 6:39 AM (in response to 934225)A few methods:1 person found this helpful a) style borders of the individual cells (and ensure that they fill their entire grid position) or b) you style the background of the whole grid leaving gaps between cells which fill their entire grid position as is shown below or c) add new grid nodes with lines and then style the added lines. I chose method b (styling the grid background) for the code below: import javafx.application.Application; import javafx.geometry.HPos; import javafx.geometry.VPos; import javafx.scene.*; import javafx.scene.control.*; import javafx.scene.layout.*; import javafx.stage.Stage; public class GridPaneStyle extends Application { @Override public void start(final Stage stage) { // create a grid with some sample data. GridPane grid = new GridPane(); grid.addRow(0, new Label("1"), new Label("2"), new Label("3")); grid.addRow(1, new Label("A"), new Label("B"), new Label("C")); // make all of the Controls and Panes inside the grid fill their grid cell, // align them in the center and give them a filled background. // you could also place each of them in their own centered StackPane with // a styled background to achieve the same effect. for (Node n: grid.getChildren()) { if (n instanceof Control) { Control control = (Control) n; control.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE); control.setStyle("-fx-background-color: cornsilk; -fx-alignment: center;"); } if (n instanceof Pane) { Pane pane = (Pane) n; pane.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE); pane.setStyle("-fx-background-color: cornsilk; -fx-alignment: center;"); } } // style the grid so that it has a background and gaps around the grid and between the // grid cells so that the background will show through as grid lines. grid.setStyle("-fx-background-color: palegreen; -fx-padding: 2; -fx-hgap: 2; -fx-vgap: 2;"); // turn layout pixel snapping off on the grid so that grid lines will be an even width. grid.setSnapToPixel(false); // set some constraints so that the grid will fill the available area. ColumnConstraints oneThird = new ColumnConstraints(); oneThird.setPercentWidth(100/3.0); oneThird.setHalignment(HPos.CENTER); grid.getColumnConstraints().addAll(oneThird, oneThird, oneThird); RowConstraints oneHalf = new RowConstraints(); oneHalf.setPercentHeight(100/2.0); oneHalf.setValignment(VPos.CENTER); grid.getRowConstraints().addAll(oneHalf, oneHalf); // layout the scene in a stackpane with some padding so that the grid is centered // and it is easy to see the outer grid lines. StackPane layout = new StackPane(); layout.setStyle("-fx-background-color: whitesmoke; -fx-padding: 10;"); layout.getChildren().addAll(grid); stage.setScene(new Scene(layout, 600, 400)); stage.show(); // can be uncommented to show the grid lines for debugging purposes, but not particularly useful for styling purposes. //grid.setGridLinesVisible(true); } public static void main(String[] args) { launch(); } } 2. Re: How to style GridPane each grid's border934225 May 7, 2012 2:42 PM (in response to jsmith)This example is very very helpful.
https://community.oracle.com/thread/2386973
CC-MAIN-2016-44
refinedweb
540
55.95
put Vector in run(), and update him Marko Debac Ranch Hand Joined: Aug 21, 2006 Posts: 121 posted Nov 16, 2006 04:37:00 0 Hallo to all, I have a burdensome problem: I have one servlet who is sterted at deploy and in his init() its created main thread which is supposed to run forewer. Her run() method should execute other threads which are created on demand from other class (or servlet). For this other child threads I had created class with schedule tasks (so it is not new thread, but new class in which I put (on creation)various times for executing her tasks). So, the problem is: I have that other servlet, I have that class with schedule tasks and I have main servlet thread runnig, so, I must put those new classes created on demand in some vector, and put that vector in main run() to execute forewer, and so I can add new classes on demand with new times, and put it in this vector (or, on demand remove from vector, to not execute any more). How? This is my class Profile with schedule time job: public class Profile { private int id_user; private int time; //max 180 min Timer timer1; public Profile(int id, int t) { id_user=id; time=t; timer1 = new Timer(); Task1 t1 = new Task1(); timer1.schedule(t1, 0, time*60*60*1000); } class Task1 extends TimerTask{ public Task1() {} public void run() { //something useful which is started every "time" } } //.. some getters and setters This is my main servlet thread code: public class RunningServlet extends HttpServlet implements Runnable { Thread someThread; boolean always = true; public void init(ServletConfig config) throws ServletException{ super.init(config); nekiThread = new Thread(this); someThread.start(); public void run() { while(always) { // in here I must put this vector (how can I put him in here?), and must can update him with new Profile on demand whith different time and id: so, I can search it and delete it from vector by his id } } Please help me to create new Profile, put them into Vector for execute regardes, Marko Marko Debac Ranch Hand Joined: Aug 21, 2006 Posts: 121 posted Nov 17, 2006 05:30:00 0 Maybe with HttpSessionAttributeListener: every time when I call function from somewhere, like function(id, time){ session.setAttribute("name", new Profile(id,time)) } and put in Listener public void attributeAdded(.. event){ Profile p = event.getValue(); String name = event.getName(); } and in running servlet public class RunningServlet extends HttpServlet implements Runnable { Thread someThread; boolean always = true; public void init(ServletConfig config) throws ServletException{ super.init(config); nekiThread = new Thread(this); someThread.start(); Vector v; public void run() { while(always) { v.add(session.getAttribute("name")) } } every time when I call function() with diferent parameters, I will add new Profile in Vector, to execute new task with diferent id for (every) diferent time, or not? I agree. Here's the link: subject: put Vector in run(), and update him Similar Threads Timer, Again Timer inside a Thread is not working! Set Timer Looping tasks and thread schedule method in timer class All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/233601/threads/java/put-Vector-run-update
CC-MAIN-2015-40
refinedweb
529
62.21
I didn't mentioned that I'm running on Tomcat 7, sorry about that. Yep, Tomcat and Eclipse might be trolling me. I tried running with Jetty. I noticed that it seems ignores the "welcome-file-list" property from "web.xml" because I got an exception when accessing "localhost:8080/message_resource". I just added an index action pointing to "/index.jsp" so you can see the dummy form. The register action just points to "thankyou.jsp" in case of a successful result. The "thankyou.jsp" doesn't use the .properties file. I pushed my changes into my hotfix branch. Maybe you could try clonning again the project [1] and see if the form from index.action displays correctly. [1] Jeanderson Barros Cândido 2015-03-12 10:15 GMT-03:00 Lukasz Lenart <lukaszlenart@apache.org>: > Just cloned your repo and started the app with mvn jetty:run and > pointed browser to - > everything looks good :) > > I think Eclipse is cheating you ;-) > > 2015-03-12 13:50 GMT+01:00 Jeanderson <jeandersonbc@gmail.com>: > > Hi Lukasz, > > > > Actually the resource file is located in an action folder as the > > documentation suggests: > > > > * Register.properties - > > > > > */src/main/resources/lab_struts/tutorial/message_resource/action* > > * Register.java - > > > > > */src/main/java/lab_struts/tutorial/message_resource/action* > > > > However, I tried renaming Register.properties to package.properties, as > you > > suggested, but I'm still getting errors > > > > 2015-03-12 09:37:23,181 WARN > > (com.opensymphony.xwork2.util.LocalizedTextUtil:64) - Missing key > > [formBean.firstName] in bundles [[org/apache/struts2/struts-messages, > > com/opensymphony/xwork2/xwork-messages]]! > > 2015-03-12 09:37:23,227 WARN > > (org.apache.struts2.components.ServletUrlRenderer:60) - No configuration > > found for the specified action: 'register' in namespace: ''. Form action > > defaulting to 'action' attribute's literal value. > > > > It's a bit frustrating to get stuck with this kind of issue but I think > it > > could be some problem hidden somewhere. > > Both .java and .properties files are in the place they're supposed to be. > > Just a random guess, isn't there any sort of configuration missing in any > > xml file? > > > > Thanks for your time and attention, > > > > Regards, > > > > Jeanderson Barros Cândido > > > > > > 2015-03-12 2:44 GMT-03:00 Lukasz Lenart <lukaszlenart@apache.org>: > > > >> Almost gut > >> > >> your action is in: > >> src/main/java/lab_struts/tutorial/message_resource/action > >> > >> but the related properties file in: > >> src/main/resources/lab_struts/tutorial/message_resource/ > >> > >> so they differ on the last part - "action" and that's why message > >> cannot be found. You have two options here: > >> - rename Register.properties to package.properties then it will be > >> used for all actions in this package and below > >> - create subdirectory "action" and move Register.properties there > >> > >> It's explained here > >> > >> > >> > >> 2015-03-11 21:58 GMT+01:00 Jeanderson <jeandersonbc@gmail.com>: > >> > Hello Lukasz Lenart, > >> > > >> > Thank you for your message. I imagined that working with a directory > tree > >> > generated by Eclipse could be a problem. > >> > I started a new project based on Maven [1], however, if you run my > code, > >> > you will get again a warning: > >> > > >> > " > >> > 2015-03-11 17:48:00,316 WARN > >> > (com.opensymphony.xwork2.util.LocalizedTextUtil:64) - Missing key > >> > [formBean.firstName] in bundles [[org/apache/struts2/struts-messages, > >> > com/opensymphony/xwork2/xwork-messages]]! > >> > 2015-03-11 17:48:00,340 WARN > >> > (org.apache.struts2.components.ServletUrlRenderer:60) - No > configuration > >> > found for the specified action: 'register' in namespace: ''. Form > action > >> > defaulting to 'action' attribute's literal value. > >> > " > >> > > >> > It is not clear for me what is wrong, it is like the framework can't > find > >> > the properties files for some reason. > >> > Any idea of what am I missing? > >> > > >> > [1] > >> > > >> > > >> > > >> > Best regards, > >> > Jeanderson Barros Cândido > >> > > >> > > >> > 2015-03-11 16:10 GMT-03:00 Lukasz Lenart <lukaszlenart@apache.org>: > >> > > >> >> 2015-03-11 18:09 GMT+01:00 Jeanderson <jeandersonbc@gmail.com>: > >> >> > Hi everyone, > >> >> > > >> >> > I am a beginner in Struts 2 and so far, I've been working with the > >> >> official > >> >> > tutorials to get started with the framework. Also, I'm using > Eclipse. > >> >> > > >> >> > In the "Message Resource Files" [1], the framework can't find the > key > >> >> > located in the .properties file although it is placed in the same > >> package > >> >> > of its related action class. > >> >> > > >> >> > Since I'm using Eclipse to create every Struts 2 project and > knowing > >> that > >> >> > Struts 2 is a "convention over configuration" framework, I wonder > if > >> I'm > >> >> > having this problem because the generated directory tree is not the > >> same > >> >> as > >> >> > the one created using Maven. > >> >> > > >> >> > Is there any recommended way to start a Struts 2 project? My code > is > >> >> hosted > >> >> > at Github [2] and maybe someone could give me a hint of what is > wrong > >> >> with > >> >> > it. I did everything as suggested in the tutorial and that's why I > >> >> believe > >> >> > the issue is having a different directory tree. > >> >> > > >> >> > [1] > >> >> > [2] > >> >> > > >> >> > >> > > >> >> > >> >> Your project [2] is a bit messy, you're using Maven (pom.xml) but you > >> >> don't follow standard layout structure for Maven projects. If you > want > >> >> to use Maven to build your Struts2 project it's far better to start > >> >> with Maven Archetypes, read this > >> >> > >> >> > >> >> > >> > > >> >> > >> >> and basically use this > >> >> > >> >> mvn archetype:generate -DarchetypeCatalog= > >> >> > >> >> > >> >> Regards > >> >> -- > >> >> Łukasz > >> >> + 48 606 323 122 > >> >> > >> >> --------------------------------------------------------------------- > >> >> > >
http://mail-archives.us.apache.org/mod_mbox/struts-user/201503.mbox/%3CCAA6YxDMCmjeXJrE=mttAMKj=_nq35ycfz50TonhT6Ua7G=NtmQ@mail.gmail.com%3E
CC-MAIN-2019-26
refinedweb
843
50.94
anyone?????????? arrays in C++ Page 1 of 1 help needed 4 Replies - 917 Views - Last Post: 19 March 2008 - 07:47 PM #1 arrays in C++ Posted 19 March 2008 - 06:25 PM Replies To: arrays in C++ #2 Re: arrays in C++ Posted 19 March 2008 - 07:13 PM What do you need to know about them?? Just the syntax??: Hope that hels you. //example program #include <stdio.h> #include <iostream> using namespace std; int main(void) { int counter; int arrayName[10]; //define a one dimensional array //using the array for(counter=0; counter<10; counter++) { arrayName[counter] = counter; //assigns value of counter to array of counter } for(counter=0; counter<10; counter++) { cout << arrayName[counter] << endl; //prints value of array of counter } return 0; } //your output should look like this: //*************************** 0 1 2 3 4 5 6 7 8 9 ***************************// Hope that hels you. #3 Re: arrays in C++ Posted 19 March 2008 - 07:32 PM I have posted another topic about arrays today and nobody posted any reply yet so if u could look at my problems I would appreciate it! #4 Re: arrays in C++ Posted 19 March 2008 - 07:39 PM #5 Re: arrays in C++ Posted 19 March 2008 - 07:47 PM My orginal question has the topic "arrays in C++, little bit help needed" Page 1 of 1
http://www.dreamincode.net/forums/topic/46739-arrays-in-c/
CC-MAIN-2016-26
refinedweb
225
66.71
by Michael S. Kaplan, published on 2006/12/16 03:01 -05:00, original URI: Speaking of Open it all up, get out of the way, and then what happens?.... There are times while I am at work where I occasionally think about how my emotional state keeps going up and down like crazy. Like first I am really pleassed about something and the next moment I am filled with despair, And then back again. And again. I wonder whether I might be bipolar. And then I realize it is just that I am thinking about MUI (Multilingual User Interface), pronounced either EM-YOU-EYE or MOO-EE depending on a constellation of factors worthy of their own blog post! I'll tell you about what I mean, about the bipolar thing (the pronunciation can be for another day). As an example, just the other day: I got depressed that MUI is LCID based rather than name based. But then I got excited when I was pointed at all the new MUI API functions that are name based. But then I got depressed when I thought about how CurrentUICulture is thread based in .NET yet session-based in Windows. But then I got excited when others suggested that although the defaults are session based that there are a whole bunch of thread-specific functions that are now a part of the MUI API. But then I got depressed when I thought about how the list of available UI languages in Vista is limited to the ones that are installed on the machine. But then I got excited when Mike (over in MUI test) explained to me that the thread-based functions do not have this limitation -- it only applies to the default for OS resource loading. But then I got depressed when I realized that custom locales are probably not supported. But then I got excited when Erik (the MUI dev manager) explained to me that one of the biggest reasons that the push to using names happened in the resource loader was to allow support for custom locales. So that this scenario should work. So at this point I stoped and then I decided it was time to either Since I doubt my neurologist would write the Rx, I opted for the second choice. :-) There is way too much confusion both in the documents and among the various experts here. So let's see once and for all what works in Vista. Off to the code.... First a moment about SetThreadPreferredUILanguages. Now SetThreadPreferredUILanguages is a fascinating function. It wants a NULL delimited list of locale names, a list which can be of somewhat arbitrary length. It will basically scroll through the list and set a maximum of ten of them, based on the first ten valid ones it can find in the list. It will return TRUE if at least one was set, and it will give you no indication of what may have failed along the way (you have to call GetThreadPreferredUILanguages to find out what was actually set). Is it just me or should SetThreadPreferredUILanguages have been named TryToSetThreadPreferredUILanguages or AttemptToSetThreadPreferredUILanguages? :-) Oh well, at least I know the semantic going in. That word valid sets off some alarm bells so I decide to make sure my sample uses the new in Vista IsValidLocaleName function so I can make sure I am using the NLS understanding of "valid" locales. So I start writing some code that will use GetThreadPreferredUILanguages and SetThreadPreferredUILanguages. I decide to write it as managed code so I can be easily registering and unregistering custom cultures (which are also custom locales). That whole NULL delimited list will be a little weird but I'll work it out in the sample. Here is the code I write, designed for the RTM version of Vista: using System; using System.Text; using System.Globalization; using System.Runtime.InteropServices; namespace Testing { class TestMUI { // Some functions from winnls.h in the Vista Platform SDK [DllImport("kernel32.dll", CharSet=CharSet.Unicode, ExactSpelling=true, CallingConvention=CallingConvention.StdCall, SetLastError=true)] static extern bool IsValidLocaleName(string lpLocaleName); ); [DllImport("kernel32.dll", CharSet=CharSet.Unicode, ExactSpelling=true, CallingConvention=CallingConvention.StdCall, SetLastError=true)] static extern bool SetThreadPreferredUILanguages(uint dwFlags, string pwszLanguagesBuffer, ref int pulNumLanguages); // Some constants and functions from winnls.h in the Vista Platform SDK private const uint MUI_LANGUAGE_ID = 0x4; // Use traditional language ID convention private const uint MUI_LANGUAGE_NAME = 0x8; // Use ISO language (culture) name convention private const uint MUI_MERGE_SYSTEM_FALLBACK = 0x10; // GetThreadPreferredUILanguages merges in parent and base languages private const uint MUI_MERGE_USER_FALLBACK = 0x20; // GetThreadPreferredUILanguages merges in user preferred languages private const uint MUI_THREAD_LANGUAGES = 0x40; // GetThreadPreferredUILanguages merges in thread preferred languages private const uint MUI_CONSOLE_FILTER = 0x100; // SetThreadPreferredUILanguages takes on console specific behavior private const uint MUI_COMPLEX_SCRIPT_FILTER = 0x200; // SetThreadPreferredUILanguages takes on complex script specific behavior private const uint MUI_RESET_FILTERS = 0x001; // Reset MUI_CONSOLE_FILTER and MUI_COMPLEX_SCRIPT_FILTER [STAThread] static void Main(string[] args) { CultureInfo ci = CultureInfo.CurrentCulture; // A name that will be sure to not conflict! string stCulture = "random-piece-of-crap-locale"; // Create the replacement and fill it CultureAndRegionInfoBuilder carib = new CultureAndRegionInfoBuilder(stCulture, CultureAndRegionModifiers.None); carib.LoadDataFromCultureInfo(ci); carib.LoadDataFromRegionInfo(new RegionInfo(ci.Name)); // Make sure it is not valid, register it, then make sure it has become valid Console.WriteLine("Before register, is '{0}' valid? {1}\r\n", stCulture, IsValidLocaleName(stCulture)); carib.Register(); Console.WriteLine("After register, is '{0}' valid? {1}\r\n", stCulture, IsValidLocaleName(stCulture)); // Try to set a big weird list of langs and then see what was set SetLangs(stCulture); GetLangs(); // Unregister -- cleanup is important in samples CultureAndRegionInfoBuilder.Unregister(stCulture); } static void SetLangs(string stCulture) { int ulNumLanguages = 0; string[] rgst = new string[10]; // Create a weird list full of valid culture names and invalid ones, with our special custom // locale in the middke between two that are definitely valid. rgst[0] = "de-DE-crap\u0000" rgst[1] = "en-US-junk\u0000" rgst[2] = "fr-CA\u0000" rgst[3] = stCulture + '\u0000'; rgst[4] = "en-AU\u0000" rgst[5] = "this-is-an-arbitrary\u0000" rgst[6] = "strings-that-are\u0000" rgst[7] = "obviously-not-locales\u0000" rgst[8] = "randomly-interspersed\u0000" rgst[9] = "with-two-that-are\u0000" ulNumLanguages = rgst.Length; Console.WriteLine(string.Concat(rgst) + "\r\n"); Console.WriteLine("Did setting up our big list work? {0}, {1} entries.\r\n", SetThreadPreferredUILanguages(MUI_LANGUAGE_NAME, string.Concat(rgst), ref ulNumLanguages), ulNumLanguages); } static void GetLangs() { int ulNumLanguages = 0; int cchLanguagesBuffer = 0; // First call with a NULL target to get the size of the list if(GetThreadPreferredUILanguages(MUI_LANGUAGE_NAME | MUI_THREAD_LANGUAGES, ref ulNumLanguages, null, ref cchLanguagesBuffer)) { if(ulNumLanguages == 0) { Console.WriteLine("No thread preferred UI languages."); } else { // Success! Allocate a buffer filled with NULLs and have the MUI function fill it in string st = new string('\u0000', cchLanguagesBuffer); if(GetThreadPreferredUILanguages(MUI_LANGUAGE_NAME | MUI_THREAD_LANGUAGES, ref ulNumLanguages, st, ref cchLanguagesBuffer)) { // Success again! Replace the embedded NULLs with CRLF and dump out the list. st = st.Replace("\u0000", "\u000d\u000a"); Console.WriteLine(st); } } } } } } Ok, looks like the code is all set. The results, when this code is run, are quite depressing, though. :-( It turns out that not only are all locales that are not valid according to IsValidLocaleName are also invalid to MUI; I kind of expected that, and it is not the most unreasonable restriction. But it also turns out that the custom locale entitled "random-piece-of-crap-locale" that I created is also not valid. Because it turns out that in some low-level internal function, MUI is pivoting the potential locale name through an LCID value, and since most custom locales don't have unique LCID values, this small extra check is invalidating the custom locale for MUI. This means of course that if one sets the user default locale to be a custom locale that you can use that locale for the UI language too; however, the notion of an application whose success or failure entirely depends on a specific user locale is a really, really bad idea. Like Unicode lame list bad. It means that at least in Vista RTM, one cannot use custom locales in MUI for your unmanaged applications (it works just fine in the unmanaged world, even pre-Vista). Now I have reported this to the folks on the MUI team and I am optimistic that this awful behavior will be addressed as soon as they can address it. This bug, which breaks not only NLS/MUI parity but also managed/unmanaged parity and the whole intent of a new set of functions in the MUI API. You should feel free to weigh in with your opinion about this bug if you have an opinion; having the customer point of view never hurts in a triage meeting.... If they can get this one fixed, then MUI won't make me bipolar anymore! :-) This post brought to you by ⌣ (U+2323, a.k.a. SMILE) referenced by 2010/04/29 New for Windows 7: The PROCESS to keep MUI from being THREADbare.... 2010/02/09 Doing your own LIPs is not as easy for Windows as for a lady 2010/01/16 Culture: don't have none, won't be none! 2007/08/25 MSKLC keyboard layout names in your own language 2007/08/14 Do what Icon, not what I say, aka MUI is still making me bipolar 2007/06/23 Marshaling your resistance 2007/03/13 Track change (a.k.a. A new job that has a few things in common with the old one) 2007/01/31 Info needed from developers and architects about what they are (or want to be) doing with MUI 2007/01/26 If I were Australian I might say that Steve Jobs and the Klingon emporer were mates? go to newer or older post, or back to index or month or day
http://archives.miloush.net/michkap/archive/2006/12/16/1300320.html
CC-MAIN-2019-26
refinedweb
1,621
52.49
I want to create a Sprite with a custom transparent area... all of the examples I've found using the 'mask' property of a DisplayObject 'cheat' by creating either a rectangle or an oval as a Shape and use it as a mask... this is 'cheating' because these are very primitive convex shapes that have no holes, and 'graphics' doesn't draw any pixels that aren't shown, so there is no portion of the mask itself where 'this portion is transparent and this portion is opaque'... and such masks have no holes in them... i want, for example, to take a bitmap image of a dog and have a 'mask' that conforms precisely to the dog's visible shape... or something with see-through holes in it... the application doesn't need to figure out the mask shape on the fly, i'm fine with providing the mask shape at design time... but how do i provide this shape? in the past, either a specific color was designated as the transparent color (no mask needed)... or a 'mask' was an associated rectangle of the same height and width as the bitmap image with black meaning transparent and white (on any color other than black) was opaque... so how does one create such a custom/odd shaped mask in ActionScript/Flash Pro? put another way, how does one create iregular-shaped sprites? One way would be to use the brush tool and draw the shape. Another would be to take a bitmapo of the object and convert it to a vector drawing and then whittle away the portions that you do not want showing maybe these images will make it clearer what i'm asking... it would be insane to have to build the mask shape at run time using primitives... with no way to add a hole... i'm looking for a way to use the mask image above to only draw its white portion of the image and have the black part be transparent... this is the brute force method i'm working in right now... this should create a Shape that only has pixels where the 'mask' image has non-black pixels: package { import flash.display.BitmapData; import flash.display.Shape; public class MakeMask { public function MakeMask() {} public static function Make_Mask( bm_data:BitmapData, mask_color:uint = 0x000000 ):Shape { var w:int = bm_data.width ; var h:int = bm_data.height ; var bm_mask:Shape = new Shape() ; var pixel_clr:uint ; bm_mask.graphics.beginFill( 0xFFFFFF ) ; for ( var y:int = 0 ; y < h ; y++ ) { for (var x:int = 0 ; x < w ; x++ ) { pixel_clr = bm_data.getPixel( x, y ) ; if ( pixel_clr != mask_color ) { bm_mask.graphics.drawRect( x, y, 1, 1 ) ; } } } bm_mask.graphics.endFill() ; return bm_mask ; } } }
http://forums.adobe.com/thread/1186327
CC-MAIN-2014-15
refinedweb
448
72.87
Search results Create the page "Article message templates" on this wiki! See also the search results found. - The $1 indicates the article name on the external wiki. ===How do I put a text message (sitenotice) on every page?===59 KB (9,321 words) - 18:55, 27 January 2010 - #:If you encounter the error message <code>#1071 - Specified key was too long; max key length is 1000 bytes </co * [[User:Inquisitor_Ehrenstein/LQTavatar]] – Forum style LQT templates for including avatars and full forum style signatures.8 KB (1,038 words) - 08:25, 12 May 2014 - If the source is in the Main article namespace (e.g., "[[Cat]]"), you must put a colon (:) in front of the name, ...live" link between the template-page and the target-page(s) upon which the message should appear. When the template is edited, all the target-pages are edited7 KB (1,037 words) - 13:17, 27 October 2011 - :::This directory contains copyright templates :::*'''templates''' - This directory contains Android source code templates for building Android application.74 KB (10,389 words) - 07:36, 28 June 2013 - TIP: If you leave a message on the page, use this signature : <nowiki> ~~~~ </nowiki>. * prefix article name with RPi (RPi_Name)2 KB (363 words) - 14:14, 14 December 2012 - :::This directory contains copyright templates :::*'''templates''' - This directory contains Android source code templates for building Android application.92 KB (13,338 words) - 07:36, 28 June 2013 - ::::'''droiddoc''' - contains document templates that are used to generate documentation using Javadoc :::This directory contains copyright templates78 KB (10,509 words) - 14:24, 27 August 2018
https://www.elinux.org/index.php?title=Special:Search&search=Article+message+templates
CC-MAIN-2020-29
refinedweb
261
60.04
FAQ How to clear up set and bin names when it exceeds the maximum set limit. Please note that the set-delete command has been deprecated and the truncate command should now be used. -. Context Deleting set and bin names doesn’t delete the associated meta data. At some point the maximum limit for sets and bins would be breached. The following log entries would show up, indicating no more bin or set names can be added. WARNING (bin): (bin.c::377) {test-namespace} bin-name quota full - can't add new bin-name OR WARNING (namespace): (namespace.c:580) at set names limit, can't add set-name Method (truncate, post version 3.12) Execute the truncate command for the set (or the namespace to clear up bin names across a namespace): asinfo -v "truncate:namespace=<namespace name>[;set=<set name>]" Issue a cold restart on each node in a rolling fashion (waiting for migrations to complete before taking the next node down depends on the version, as the new cluster protocol introduced in version 3.13/3.14 does not require to wait for migrations to complete prior to taking the next node down). Be considerate of records of other sets that may be brought back as well. Deleting the whole persistent storage will avoid other deleted records, from other sets to come back. This would then require waiting for migrations to complete (to repopulate records on the empty namespace) prior to taking the next node down. Method (set-delete, prior to version 3.12) A clean up of the persisted storage for the relevant namespace, and accompanying user roles, followed by a start up will fully remove the set/bin names. But this would only work if the replica nodes have no references of the deleted sets or bins. It is important to do it for one node at a time, in a rolling fashion. The commands listed below refer to a set but the same steps can be used for bin names as well (replace with a bin name where applicable). Step 1: Run the set delete command for every node in the cluster (or run it from asadm to hit all the nodes): asinfo -v "set-config:context=namespace;id=<name space>;set=<set name>;set-delete=true;" Step 2: Ensure that all records in the set are deleted (n_objects is 0) and set-delete is back to “false”, for example, using aql: aql> show sets +-----------+------------------+----------------+-------------------+----------------+--------------+------------+------------+ | n_objects | disable-eviction | set-enable-xdr | stop-writes-count | n-bytes-memory | ns_name | set_name | set-delete | +-----------+------------------+----------------+-------------------+----------------+--------------+------------+------------+ | 0 | "false" | "use-default" | 0 | 0 | "test_file1" | "testset1" | "false" | +-----------+------------------+----------------+-------------------+----------------+--------------+------------+------------+ Step 3: Verify that no user roles (“read-write-ns-set”) with privileges on the set in that namespace (“read-write.test_file1.testset1”) exist, for example, using aql: aql> show roles +---------------------+----------------------------------+ | role | privileges | +---------------------+----------------------------------+ | "data-admin" | "data-admin" | | "read-write-ns-set" | "read-write.test_file1.testset1" | | "read" | "read" | | "read-write" | "read-write" | | "read-write-udf" | "read-write-udf" | | "sys-admin" | "sys-admin" | | "user-admin" | "user-admin" | +---------------------+----------------------------------+ Step 4: Drop any user roles(“read-write-ns-set”) with privileges on the set in that namespace(“read-write.test_file1.testset1”), for example, using aql: aql> drop role <role name> Step 5: Verify that no user roles (“read-write-ns-set”) with privileges on the set in that namespace (“read-write.test_file1.testset1”) exist, for example, using aql: aql> show roles +------------------+------------------+ | role | privileges | +------------------+------------------+ | "data-admin" | "data-admin" | | "read" | "read" | | "read-write" | "read-write" | | "read-write-udf" | "read-write-udf" | | "sys-admin" | "sys-admin" | | "user-admin" | "user-admin" | +------------------+------------------+ Steps 6 & 7 should be repeated for each node in the cluster. Step 6: Stop the aerospike daemon on a node then clear the data from the persistent store.This step is only applicable when the replication factor is 2 or more on the namespace For SDD, run the dd command for the device which is attached to the particular namespace and set: sudo dd if=/dev/zero of=/dev/<deviceID> bs=1M& OR For rotational drives, remove the file associated with the particular namespace and set: sudo rm /opt/aerospike/<filename> Step 7: Start the aerospike daemon. Depending on the specifics of the workload and potential other namespaces in the cluster, you may need to wait for migrations to complete before moving on to the next node. Step 8: Repeat Step 6 & 7 for every node in the cluster Keywords BIN SET LIMIT ROLE DELETE TRUNCATE Timestamp 12 June 2017
https://discuss.aerospike.com/t/how-to-clear-up-set-and-bin-names-when-it-exceeds-the-maximum-set-limit/3122
CC-MAIN-2018-30
refinedweb
740
55.88
A dynamic routing solution for the awesome Next.js framework. Next.js introduced in it's V2 a programmatic routing API allowing you to serve your Next app from, for example, an express server: // yourServer.jsserver // ./pages/index.js<Link = =><a>Visit me!</a></Link> But as the number of pages grows, it's getting a little hard to manage... npm install --save nextjs-dynamic-routes Create a routes.js file and list all your Dynamic routes. You don't have to list your regular routes, as Next.js will handle them as usual. const Router =const router =routerrouter// if the name of your route is different from your component file name:routermoduleexports = router const express =const next =const Router =const app =const server =const handle = Routerapp Then Nextjs Dynamic Routes exports a Link component. It's just like next/link, but it adds a route prop that let you refer to a route by its name. // pages/index.jsimport React from 'react'import Link from '../routes'<ul><li><<a>Luke Skywalker</a></Link></li><li><<a>C-3PO</a></Link></li><li><<a>A New Hope</a></Link></li><li><<a>The Empire Strikes Back</a></Link></li><li><<a>The Empire Strikes Back and Luke Skywalker</a></Link></li></ul> // pages/character.jsimport React from 'react'Componentstatic async {return}{return <p>thispropsname</p>} Next.js has this great feature allowing you to prefetch data for your next routes in the background. You can benefit of that by simply putting a prefetch property on any Link : <<a>The Empire Strikes Back</a></Link> import Router from '../routes'<button =>Go to film 2</button> import Router from '../routes'<button =>Go to film 2</button> import Router from '../routes'<button =>Prefetch film 2</button> console// => '/character-and-film/2/5'
https://www.npmjs.com/package/nextjs-dynamic-routes
CC-MAIN-2018-09
refinedweb
299
50.43
SausieMember Content count61 Joined Last visited Community Reputation139 Neutral About Sausie - RankMember Which programming language should I teach myself? Sausie replied to Sean Frazier's topic in For Beginnersnvm Decent Java Programming Book Sausie replied to JavaProgrammer7's topic in For BeginnersIt's not a book, but i used it a lot besides my book: I hope that's a help for you(although its not focused towards games) java beginner Sausie replied to grjmmr's topic in For BeginnersI dont see what you are trying to do... You're testing milli2 for truth and then u assign a String to an integer. Why dont you use the concat() method thats already in the String object? Here's the entry in the documentation: String concat(String str) Concatenates the specified string to the end of this string. Don't forget a String is an object and not a primitive datatype like int. - public class App { public static void main(String args[]) { soldier jimjim = new soldier(1); wall bigwall = new wall(10); } jimjim.attack(bigwall); System.out.println("Destroyed? "+veryBigWall.isDestroyed()); } The first closing bracket has to be set after the last statement. Now you are closing the main method before those two last statements. Edit: somebody already beat me to it. - In our Java classes we use Object Oriented Programming With Java: An Introduction by Barnes. Maybe you should look at that one. [url][/url] Oh, i see its kinda expensive without the special student price. n00b looking for partner(s) in crime. Sausie replied to jgmachine's topic in For BeginnersIm kind of interested in this. Currently I'm programming in Java, but i would like to learn C++ too. Contact me by pm or add to msn (also for more information): kevin_verhulst@hotmail.com One of my first advanced programs Sausie replied to Vinniee's topic in For Beginnershey vinnie, i see you're new and from the netherlands. Do you feel anything for going through learning C++ with someone else? If so, pm me. I don't think i have to give u any comments on your program, since the others already did that well.
https://www.gamedev.net/profile/24397-sausie/
CC-MAIN-2018-05
refinedweb
358
64
Markdown-based test runner for python. Good for github projects Project description Steady Mark Turning your github readme files into python test suites since 2012 Steady Mark was created for python developers that love Github and markdown. Example unicode.lower transforms string into lowercase from sure import expect assert expect(u"Gabriel Falcao".lower()).equals(u"gabriel falcao") python can add numbers assert assert "LOWERCaSe".lower() == "lowercase" ``` ## python can add numbers ```python assert (2 + 2) == 5, 'oops baby' ``` Just run with: $ steadymark README.md you can tell steadymark to load a "boot" file before running the tests, it's very useful for hooking up sure or HTTPretty Steadymark is on version 0.8.3 >>> from sure import expect >>> from steadymark import version >>> assert expect(version).should.equal("0.8.3") Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/steadymark/
CC-MAIN-2020-16
refinedweb
157
56.05
JAX-RS extension Introduction This Restlet Extension implements the Java Specification JAX-RS: Java API for RESTful Web Services. Note that this implementation is not final yet. Description To run this example, you need the Restlet libraries. Download a 2.4 version from restlet.com/downloads/. (For a general Restlet example take a look at the first steps examples). Now create a new Java Project, and add the following jars (resp. projects) to the classpath (right click on project, Properties, Java Build Path, Libraries (resp.Projects), Add): - org.restlet (the core Restlet API) - org.restlet.ext.jaxrs (the JAX-RS Runtime) - javax.ws.rs (the JAX-RS API and also the specification) Depending of your needs you have to add the following: - if you want to use the provider for javax.xml.transform.DataSource: add javax.activation and javax.mail - if you want to use the provider for JAXB: add javax.xml.bind and javax.xml.stream - if you want to use the provider for JSON: add org.json Click “Ok” twice. Now you are ready to start. - First we will create an example root resource class and then show how to get it running by the Restlet JAX-RS extension. For additional details, please consult the Javadocs. "\n" + "This is an easy resource (as html text).\n" + ""; } @GET @Produces("text/plain") public String getPlain() { return "This is an easy resource (as plain text)"; } } Create Application To provide a collection of root resource classes (and others) for a JAX-RS runtime you integrate these classes to an Application. Create a new class ExampleApplication in the same package with the following content: package test.restlet.jaxrs; import java.util.HashSet; import java.util.Set; import javax.ws.rs.core.Application; public class ExampleApplication extends Application { public Set<Class>> getClasses() { Set > rrcs = new HashSet<Class<?>>(); rrcs.add(EasyRootResource.class); return rrcs; } } The root resource class and the Application is specified by the JAX-RS specification. It can be used in any JAX-RS runtime environment. Now create a runtime environment instance and pass the Application application.add(new ExampleApplication()); // and sets the Guard and the RoleChecker (if needed). public class MyJaxRsApplication extends JaxRsApplication { public MyJaxRsApplication(Context context) { super(context); this.add(new ExampleApplication()); again. Comments are welcome to the Restlet mailing list or directly to Stephan.Koops<AT>web.de ! This extension is the result of a (german) master thesis.
https://restlet.talend.com/documentation/user-guide/2.4/extensions/jaxrs
CC-MAIN-2020-16
refinedweb
398
53.37
#include <db_cxx.h> int Db::set_re_len(u_int32_t re_len); For the Queue access method, specify that the records are of length re_len. For the Queue access method, the record length must be enough smaller than the database's page size that at least one record plus the database page's metadata information can fit on each database page.() method configures a database, not only operations performed using the specified Db handle. The Db::set_re_len() method may not be called after the Db::open() method is called. If the database already exists when Db::open() is called, the information specified to Db::set_re_len() will be ignored. The Db::set_re_len() method either returns a non-zero error value or throws an exception that encapsulates a non-zero error value on failure, and returns 0 on success. The Db::set_re_len()
http://idlebox.net/2011/apidocs/db-5.2.28.zip/api_reference/CXX/dbset_re_len.html
CC-MAIN-2014-10
refinedweb
136
59.13
Add info about - how to use it correctly - issues with fixed contents / solutions - view port meta tag - frame flattening QtWebView goes Mobile There is a lot of effort being put into QtWebKit in order to make it attractive on the mobile front. Among a tons of bug fixes and good performance improvements there are also lots of new features being developed, many: #include <QApplication> #include <QGraphicsScene> #include <QGraphicsView> #include <QGraphicsWebView> #include <QWebSettings> (QGV) application and add a QGraphicsWebView to the scene. It might seem a bit useless as you can only navigate through one website but it serves well as a simple example. Notice that I'm disabling the scrollbars on the QGV things, noticable. When using tiling, we basically want the QGraphicsWebView to act as our contents, as it supports tiling a.o. things. In order for this we need to make it resize itself to the size of its contents. #1 Magical Step - its content's size. Enabling it: webview.setResizesToContents(true); If we are going to expand our mobile web view to the size of the contents of its contained page, then that is going to make the view a lot bigger that what can fit on the device's screen! #3 Magical Step - Use a "view" and handle mouse events scrolling will have to be implemented manually, just as zoom etc. WebKit. Qt 4.7 docs also says: "This property should be used in conjunction with the QWebPage::preferredContentsSize property. If not explicitly set, the preferredContentsSize is automatically set to a reasonable value." #2 Magical Step - QWebPage::preferredContentsSize which. As some sites do not work with 980 or want to have control on how the page is laid out, QtWebKit as well as Android, Firefox Mobile and the iPhone Safari supports a meta tag called viewport. #6 Magical Step - Handle viewport meta tag. #5 Magical Step - Enable.
https://trac.webkit.org/wiki/QtWebKitTiling?version=4
CC-MAIN-2021-49
refinedweb
311
60.75
/* * dutil.c - AIX utility functions whose compilation conflicts with the * general header file tree defined by lsof.h and dlsof.h -- e.g., * the conflict between <time.h> and <sys/time.h> for the time(2) * and localtime(3) functions * * V. Abell * Purdue University */ /* * Copyright 2008. */ #ifndef lint static char copyright[] = "@(#) Copyright 2008 Purdue Research Foundation.\nAll rights reserved.\n"; static char *rcsid = "$Id: util.c,v 1.1 2008/04/01 11:56:53 abe Exp $"; #endif #if defined(HAS_STRFTIME) #include <time.h> #endif /* defined(HAS_STRFTIME) */ /* * util_strftime() -- utility function to call strftime(3) without header * file distractions */ int util_strftime(fmtr, fmtl, fmt) char *fmtr; /* format output receiver */ int fmtl; /* sizeof(*fmtr) */ char *fmt; /* format */ { #if defined(HAS_STRFTIME) struct tm *lt; time_t tm; tm = time((time_t *)NULL); lt = localtime(&tm); return(strftime(fmtr, fmtl, fmt, lt)); #else /* !defined(HAS_STRFTIME) */ return(0); #endif /* defined(HAS_STRFTIME) */ }
http://opensource.apple.com//source/lsof/lsof-49/lsof/util.c
CC-MAIN-2016-40
refinedweb
144
53.58
After playing with I2C, with various IO, I’ve decided to play a bit with SPI The real project behind using a SPI device is to be able to use it a a multiplexer/demultipler of IO. I want to pilot lights for my Lego train. The idea is to have the ability to switch a signal light to green or red. I want to be able to have 16 lights. The netduino board have only 14 digital IO and 6 analogic. And I’m already using some to pilot the Lego train thru infrared. See previous article. So I have to find a multiplexing solution. And one is used by most of the netduino fan: SPI. In terms of electronic it’s simple, it is a serial to parallel (and vice versa as you can read also). The component the most used for this is 74HC595. There are couple of basics explanations on the netduino wiki and also good examples as always on Mario Vernari blog. Each 74HC595 can have 8 output and they can be chained. Which mean that you can use 2 component to have 16 output. And you basically put them in series. One output of one 74HC595 to the input of the others. I spend quite a bit of time to understand how to plug the 74HC595 to the netduino. So here is what to do: And that’s it for the basics! Now what I want to do with the output is to be able to light one led green or switch it to red. So I’ll use the output of the 74HC595. When it will be 1, I’ll light the green one, when it will be 0, I’ll light the red one. Here is the hardware to schematic: When the signal will be 1, the current will go thru the green light light. And when it will be 0, the inverter will switch to 1 and the red light will light. It just need 3 cables per light and the current can be transported on long distance. The RS resistor can be adapted with a lower resistor to 100 or something like this in order to send a more intense current in the cable as there will be some loss if it is very long. by the way I recommend to read the excellent article on the length of cable and impact on signal noise from Mario. Now, in terms of software, It’s not so difficult. In my project, I’m using the SPI for multiple purpose. So I need to use it in a smart way. SPI can be shared and the only thing to do is to change the configuration and write (and read) right after. So I’m using the MultiSPI class from the NETMF Toolbox. It’s an impressive toolbox containing lots of helpers. It goes from hardware to HTTP web client. There is a 74HC595 also but I found it more complex to use that just directly using the MultiSPI class. Here the example of class to switch to green (1) or red (0) a specific output of the 2 74HC595: public class Signal { private byte mNumberSignal; private bool[] mSignalStatus; public const byte NUMBER_SIGNAL_MAX = 16; private MultiSPI MySignal; public Signal(byte NumberOfSignal) { mNumberSignal = NumberOfSignal; if ((mNumberSignal <= 0) && (mNumberSignal > NUMBER_SIGNAL_MAX)) new Exception("Not correct number of Signals"); mSignalStatus = new bool[mNumberSignal]; // open a SPI MySignal = new MultiSPI(new SPI.Configuration( Pins.GPIO_PIN_D10, // SS-pin false, // SS-pin active state 0, // The setup time for the SS port 0, // The hold time for the SS port false, // The idle state of the clock true, // The sampling clock edge 1000, // The SPI clock rate in KHz SPI_Devices.SPI1)); // The used SPI bus (refers to a MOSI MISO and SCLK pinset) //initialise all signals to "false" for (byte i = 0; i < mNumberSignal; i++) ChangeSignal(i, true); } public byte NumberOfSignals { get { return mNumberSignal; } } public void ChangeSignal(byte NumSignal, bool value) { if ((NumSignal <= 0) && (NumSignal > mNumberSignal)) new Exception("Not correct number of Signals"); //need to convert to select the right Signal mSignalStatus[NumSignal] = value; // fill the buffer to be sent ushort[] mySign = new ushort[1] { 0 }; for (ushort i = 0; i < mNumberSignal; i++) if (mSignalStatus[i]) mySign[0] = (ushort)(mySign[0] | (ushort)(1 << i)); //send the bytes MySignal.Write(mySign); } public bool GetSignal(byte NumSignal) { if ((NumSignal <= 0) && (NumSignal > mNumberSignal)) new Exception("Not correct number of Signals"); return mSignalStatus[NumSignal]; } } I just need to declare a MultiSPI. The SPI Configuration contains the necessary information to setup the 74HC595. The SS pin is set to D10. So I can use the SPI for other purposed to pilot my Lego infrared modules. And in the Lego module, I’ll have also to declare the SPI as MultiSPI. What the MultiSPI class is doing is very simple. It has a static SPI in its private variables. And a SPI.Configuration which is not static. /// <summary>Reference to the SPI Device. All MultiSPI devices use the same SPI class from the NETMF, so this reference is static</summary> private static SPI _SPIDevice; /// <summary>SPI Configuration. Different for each device, so not a static reference</summary> private SPI.Configuration _Configuration; // Store the configuration file for each MultiSPI instanceSets the configuration in a local value this._Configuration = config; // If no SPI Device exists yet, we create it's first instance if (_SPIDevice == null) { // Creates the SPI Device only 1 time as it is a static! _SPIDevice = new SPI(this._Configuration); } public void Write(byte[] WriteBuffer) { _SPIDevice.Config = this._Configuration; _SPIDevice.Write(WriteBuffer); } So each time a program want to write in a SPI, the right configuration is selected and the write command is send. It’s working like this to read. The full class is a bit more complex but the main principle is there. The rest of my code is very simple and I’m sure I would have been to write it in a better way. I’m just storing the state of a signal and then output all the buffer to the SPI. So bottom line, it is very easy to use SPI as a multiplexer/demultipler for IO. That was what I needed. I did not tested yet how to read the data but it should be as simple!
http://blogs.msdn.com/b/laurelle/archive/2012/05/22/using-a-spi-device-with-netduino-and-net-micro-framework.aspx
CC-MAIN-2014-23
refinedweb
1,047
63.49
- Step 1: Getting Started with Azure Command and Query - Step 2 : Setting up the Azure Environment Coding for the cloud can seem a mountainous challenge at the start. What resources do you need, how can you best use them, and just what will it cost to run your solution? In our previous step we built an application that exposes a WebAPI to receive new subscriptions to a book club. This is then stored in an Azure storage account queue, so that the user can continue whilst we process the request further using an Azure Function. The Azure function is triggered by the queue, and writes the data to table storage in the same storage account for us. To aid our development, and to allow us to focus, we used the Azure Storage Emulator to fake our storage account, and ran both the WebAPI and Function with 'F5' using the standard Visual Studio tooling to allow them to run locally. This is great for development and experimentation. But we need to deploy at some point. In this tutorial we are going to create an environment in Azure using the Azure Portal, and publish our code for testing. Getting Started You can find the starting point in the GitHub repo here Clone the repo, if you haven't already and checkout step-two-start The Azure Portal Before we can make the changes that we need to in our code, we first need an environment to communicate with, and deploy to. Note: For these steps you need a Microsoft Account. If you do not have one with access to Azure resources then you will need to create one. We are not covering that in this tutorial, but you can read more here - Open portal.azure.com - Login into your Microsoft Account We are now on the home page of the Azure Portal. Amongst other things from here we can check the state of your account, navigate around current resources and create new resources. It's the later that is important for us today. Resource Groups The first thing that we need to set up is an environment is a resource group. As the name implies a resource group ties the resources together in one group. This allows easy management of the resources. All related resources are located together, the costs for all related resources are grouped, and when the time comes to clean up your environment all are located together. - Click on the 'Resource Groups' icon - On the Resource Groups page click the '+ Create' button. - Select the subscription to attach the resource group to - Give your resource group a meaningful name - Select the region to store the metadata for your resource group - Click the 'Review and Create' button - Check that the data entered is correct and press 'Create' Azure will now create your resource group for you - Refresh the Resource Group List and you should now see your resource group Most resources take some time to create, the resource group is an exception to this and appears almost immediately. Creating the Web App Now we need to add something to it, the first thing that we need to be able to deploy our app is a Web App. We need a Web App in order to deploy our Web API application. Think of this like the IIS of a Windows Server. - Go to the page for the resource group that we just made - Click on the Add - Click on `Web app' Click on the Web Applink, otherwise we'll find ourselves in the quick start page 😉 - We should now be on the page to create a new web app - it should look like this - Make sure that the right subscription is selected - Make sure that the right resource group is selected (if you created the resource from the resource group this will be prefilled) - Give your Web App a name This name cannot contain spaces, and needs to be unique, globally. If someone else has used this name already you will get an error message - For publishing click Code - Runtime stack is .Net 3.1 LTS Windowsfor the Operating System Note: There are limitations with Linux App Service plans when using consumption based Function Apps (as we will later in this tutorial), so we are using Windows. If we were to use two Resource Groups to separate this App Service plan from the Function App then we could use Linux for our hosting. For more information see this wiki - For region select the same as your Resource Group Note: Depending on the subscription that you have you may not be able to select every region. In which case Central US- this one has always worked for me App Service Plan That is all of the settings that we'll be using today for the Web App itself, but you may have noticed that there are still some settings that we need to look at. The Web App needs somewhere to run. This is the App Service. If you think of the Web App as IIS, then think of the App Service as the machine it runs on. As we don't have an App Service in our Resource Group we are going to need to create one. - Click the Create Newlink - In the pop-up that opens fill in the name for your app service - Fill in a name (this does not have to be globally unique) - Click OK - Now we want to select the SKU and size of our App Service. - Click on Change Size We should now have a new fly-in open, allowing up to pick what specifications we want for our App Service Here we can find all of the options available to us for development, testing, production and isolated instances. Have a look around to see what is available Pick Dev / Test Pick F1 Shared Infrastructure. For our demo free is good enough! For practice, and demonstrations I always use the Dev/Test F1 tier. This is free, has 60 minutes run time a day and is good enough for what we are doing today. 60 minutes a day does not mean it is only available for 60 minutes a day. It means you only get 60 minutes of actual compute time. If our service is only busy for 1 minute per hour then you would only use 24 in that day even though it was available for the whole 24 hours. - Click apply We should now have a screen in front of us that looks a little like: - Click Review + Create - Check that everything on the review page looks OK - Click Create Azure will now create the resources for us, this will take a few minutes. Creating the Azure Storage Account The Web App allows us to host our API, but now we need some storage for it to talk to. - Go back to the page for the resource group, now with an App Service and Web App - Click on the Addbutton to open the new resource blade Storage Account Click on the Storage Account - blob, file, table, queueoption In the marketplace page that opens, click on Create - In the creation screen make sure that the subscription and resource group are correct - Fill in the `Instance Details' using this information as a guide - Click Review and Create - Check that the validation has passed, and that all of information is as you intended it to be - Click Create Azure will now provision our storage account for us! Whilst it's doing that lets take a quick look at those `Instance Details Storage Account Name The storage account name is a globally unique name within Azure. The same as our Web App, this means that we need to pick a name here that no one else has used. Unlike the Web App, we have more limitations with the name. The only characters allowed are lowercase letters and numbers. No PascalCase, camelCase or kebab-case names are allowed. Yes, this makes the name harder to read. Sorry. Location There are two rules of thumb here: - Keep it close to the metal where it will be written and read. - Make sure that your users data is compliant with local rules regarding data location. Performance For this example we do not need a high data throughput, or extreme response times, so the cheaper standard performance is good enough. Account Kind There are three account kinds: - Storage V2 (general purpose v2) - Storage (general purpose v1) - BlobStorage The Storage V2 accounts are general purpose accounts for File, Table, Queue and Blob storage. For general purpose use this is what we should always use. V1 accounts should only be used for legacy applications that need it. BlobStorage accounts are specialised for high performance block blobs, not for general purpose use. Replication Storage accounts always replicate data, but you can specify different levels of replication. This comes at a price, the further down this list you go, the more you pay. - LRS: Cheapest, locally redundant in 1 data center - ZRS: Redundant across multiple data centers in one zone - GRS: Redundant across two zones - RA-GRS: As above, but with read access across the zones - GZRS: Redundant across multiple data centers in the first zone, and a single data center in the second - RA-GZRS: As above, but with read access across the zones Updating the WebAPI with the Storage Account Now that we have an Azure Storage Account we can start to use it, to do so we need to make some changes to our WebAPI application. Get the connection string for the Storage Account - Open the resource group - Click on the Azure Storage Account created in the last step to open the resource - Click on 'Access Keys' The Access Keys are in the Settingssection - On the screen that opens we can see two keys and connection strings. Copy one of the connection strings You can do this easily using the copy button next to the connection string Note: Do not post keys online, the storage account is open for attack with these keys available. The keys seen here are no longer valid, which is why they are shared for demonstration purposes 😉 Update the WebAPI with the copied connection string - Open the WebAPI code - Open the QueueAccess.csfile - Replace the _connectionStringstring literal with the connection string copied from the Azure Portal It should look like this, but with your storage account connection string: C# public class QueueAccess { private const string _connectionString = "DefaultEndpointsProtocol=https;AccountName=mystor..."; Test the WebAPI and Queue We are now ready to run! - Start the WebAPI in debug mode - Open the following folder in a terminal (command prompt, Windows PowerShell, Bash etc). The folder is relative to the base folder of the git repo for this tutorial) <git repo folder>\front-end - Start the Angular front end application by running: ng serve Note: For this you need to have npm and the angular CLI installed. We are not covering that in this tutorial, but you can find more information here Angular CLI and here npm and NodeJS. - Browse to Fill in a name, email and preferred genre - Click Submit - Open the Azure Portal - Go to the Azure Storage Account we created - Open the Storage Explorer from the side bar Note: The Azure storage explorer is still in preview, as such there may be some issues. But for our example here it works without a problem. - Open the Queues\ bookclubsignups - We can see our sign up data in the queue! Deploying the WebAPI to Azure So now we have all of the resources that we need in Azure to host our WebAPI and to hold our queue, and we have a WebAPI that can send messages into our queue. It's time to deploy our code and see it work in the wild! - Open the - Right click on the - Click Publish Note: There are several notable public speakers who use the phrase friends don't let friends right click publish. But for experimentation and a quick deploy it's very useful! - In the window that opens select 'Azure' - In the 2nd step select Azure App Service (Windows) - In the 3rd step select the resource group inside your Azure subscription, and pick the WebApp from the tree view. - We now have our publish profile set up. We also have the option for setting up our storage account, which has been detected, and even a pipeline for CI deployments. But for now we are simply going to press the Publishbutton Visual Studio will run some checks to ensure that our code will run in the cloud, build, publish and push our code to Azure, and when everything is complete open a browser with the URL of the service. Don't worry that this shows an error, we only have one route set up for our WebAPI, so the root won't show anything... But do copy the URL! Testing the Azure Service We can test that our API is working using our front end application. - Open the front end angular project folder in VS Code <git rep folder>\front-end - Open the SubscriptionServiceclass src\app\service\subscription.service.ts - Change the URL for the API from localhost to the deployed web app From: ts`; const url = ` To: ts const url = ; - Run the Angular app and add a new sign up the the book club - Recheck the Azure Storage Account and check that your new signup is saved, below you can see Rory has signed up for book club now as well Creating the Azure Function We now have a working WebAPI, deployed and sending requests to the queue. Now we need to read that queue and store the data in a table. To do that we need to deploy our Azure Function, so we need a new resource. - Open the Azure Portal - Go to the Resource Group - On the Resource Groups page click the '+ Add' button - Click on the Function Applink (not Quick starts + tutorials) In the Create Function App Basics make sure the correct subscription and resource group are selected Give the function app a name, this has to be unique in Azure For Publishselect Code Pick .NET Corefor the Runtime Stack 3.1for Version Make sure that the Function App is located in the same Regionas the Storage Account and Resource group - Click 'Next: Hosting >' - For the Storage Accountpick the one we created in this tutorial Note: If this isn't available then double check your regions - you can only pick storage accounts in the same region as you are creating the Function App - Pick Windowsfor the operating system Note: As said earlier, there are limitations with Linux App Service plans when using consumption based Function Apps, so we are using Windows. If we were to use two Resource Groups to separate this App Service plan from the Function App then we could use Linux for our hosting. For more information see this wiki - For the Plan Typepick Consumption (Serverless) - Click Review + Create - Check the details of the Function App and if all are correct click Create Azure will now deploy the resources needed for our new Function App Once deployed, our resource group is now complete, and should look like this The function app creation also created the Application Insights resource, but we are not going to be using that for this tutorial, so we can ignore it. We can also see the new App Service Plan that has been created for the Function App. This will be spun up when the Function App is called, and the code for the function deployed to it from the Storage Account. Note: This does mean that there is a delay when calling a consumption based Function App from cold before it responds. This is why we have used a regular WebAPI hosted in a Web App for our API layer. Updating the Function App with the Storage Account Now that we have our Function App available we can update our Function App code to to triggered from our queue, and to write our data to the queue. Updating the Function App trigger to use the Storage Account There are three changes that we need to make to change the trigger - Open the Function App solution - Open the serviceDependencies.local.jsonfile - Copy the JSON below into the file json { "dependencies": { "storage1": { "resourceId": "/subscriptions/[parameters('subscriptionId')]/resourceGroups/[parameters('resourceGroup')]/providers/Microsoft.Storage/storageAccounts/<Storage Account Name>", "type": "storage.azure", "connectionId": "AzureWebJobsStorage" } } } Note: The resourceIdends with the Storage Account of our queue. In our example we used mystorageaccounttutorial, that is what we would use here. Whatever the name of the Storage Account is should be used. - Copy the connection Azure Storage Account connection string from the Azure Portal, as we did earlier - Open the local.settings.jsonfile You may need to recreate this file due to .gitignoresettings. If so create it in the root of the Functions project - Replace the value of AzureWebJobsStorage(currently "UseDevelopmentStorage=true") with the value copied from the Azure portal It should now look like this, but with your storage account connection string: json { "IsEncrypted": false, "Values": { "AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=mystor...", "FUNCTIONS_WORKER_RUNTIME": "dotnet" } } Note: This setting allows us to run the solution locally, but using the Azure Storage Account rather than the Storage Emulator - Finally, open the StorageTableAccess.csfile - Replace the _connectionStringstring literal with the connection string copied from the Azure Portal It should look like this, but with your storage account connection string: C# public class StorageTableAccess { private const string _connectionString = "DefaultEndpointsProtocol=https;AccountName=mystor..."; Test the full application locally We can now do a full local test! From web application, through our WebAPI, Azure Function running locally and into our Storage Table. - Start the function in Debug mode NOTE: Function Apps run in specialised environments in Azure, when you run your app in debug mode Visual Studio spins up an Azure Function Tools application to create this environment locally. - Run through the same same steps as our previous test - but don't look in the Queuesection! - Instead, look in the Tablesection, where we should now see our latest test: Deploying the Function App to Azure Now on to the last step, deploying our BookClubSignupProcessor to Azure! This flow is similar to deploying the WebAPI to azure - Open the BookClubSignupProcessorsolution - Right click on the BookClubSignupProcessorproject - Click Publish - In the window that opens select 'Azure' - In the 2nd step select Azure Function App (Windows) - In the 3rd step select the resource group inside your Azure subscription, and pick the Azure Function from the tree view. - We now have our publish profile set up. We also have the option for setting up our storage account, which has been detected, and even a pipeline for CI deployments. But for now we are simply going to press Publish Note: Here we see a big difference from the WebAPP deploy. The Azure Function has a dependency on the Storage Account, which has a warning. We are going to ignore it for now - Click the Publishbutton Now it's deployed, we can take a look at the function in the Azure Portal to ensure that it worked correctly. Check that the function has been deployed and is available Now that we have deployed our function app we can see it in the Azure portal NOTE: Functions take time to spin up, it may be that after you have deployed it doesn't appear straight away - Open the Azure Portal - Go to the Resource Group - In the list of resources click on the Function App created - In the side menu of the Function App click Functionsin the group Functions - In the blade that opens we can see all of the functions within the Function App, the type of trigger and if they are enabled Now that we know our Function is deployed and available we can run our final test! Test the deployed Function App We now have a full environment deployed and can do one final test to make sure that everything is set up as it should be. We are going to use the same test as we did running the Function locally. The only thing we need to run locally now is our front end! Closure and Next Steps You can find the end point in the GitHub repo here Clone the repo, if you haven't already and checkout step-three-start Files will need editing to run - ensure that the correct connection strings and storage account names are set. Due to the nature of publish profiles and their access tokens these files are not included - you will need to follow the publish steps yourself to deploy this repo. Our solution is now deployed, and running in the cloud. Using a Web App, Azure Storage Account and Azure Function to run in the wild. As with our previous work, this has been a quick skim through, and is just the start of making a maintainable cloud solution. In the following posts, over the coming months, we'll be - Taking a look at the Azure cost calculator so that we can check what the associated costs of that environment will be - Taking a deeper dive into each of the Azure resources we need for this experiment - Taking a deeper dive into each of the APIs that we are using to access them! - Finally, we'll be automating the deployment, using Azure DevOps, and quickly throwing a static Angular site into the air so that we can interact with our API Further Reading Azure Web App Azure Storage Azure Functions Cover photo by Philipp Birmes from Pexels Discussion (0)
https://dev.to/stacy_cash/setting-up-the-azure-environment-47fb?utm_source=cloudweekly.news
CC-MAIN-2021-43
refinedweb
3,603
61.19
Beyond the “hello, world” of Python’s “print” function One of the first things that anyone learns in Python is (of course) how to print the string, “Hello, world.” As you would expect, the code is straightforward and simple: print('Hello, world') And indeed, Python’s “print” function is so easy and straightforward to use that we barely give it any thought. We assume that people know how to use it — and for the most part, for most of the things they want to do, that’s true. But lurking beneath the surface of the “print” function is a lot of functionality, as well as some history (and even a bit of pain). Understanding how to use “print” can cut down on the code you write, and generally make it easier for you to work with. The basics The basics are simple: “print” is a function, which means that if you want to invoke it, you need to use parentheses: >>> print('hello') hello You can pass any type of data to “print”. Strings are most common, but you can also ints, floats, lists, tuples, dicts, sets, or any other object. For example: >>> print(5) 5 or >>> print([10, 20, 30]) [10, 20, 30] And of course, it doesn’t matter whether the thing you’re trying to print is passed as a literal object, or referenced by a variable: >>> d = {'a':1, 'b':2, 'c':3}>>> print(d) {'a':1, 'b':2, 'c':3} You can also put an expression inside of the parentheses; the value of the expression will be passed to “print”: >>> print(3+5) 8 >>> print([10, 20] + [30, 40]) [10, 20, 30, 40] Every object in Python knows how to display itself as a string, which means that you can pass it directly to “print”. There isn’t any need to turn things into strings before handing them to “print”: print(str([10, 20, 30]) # unnecessary use of "str" [10, 20, 30] After “print” displays its output, it adds a newline. For example: >>> print('abc') >>> print('def') >>> print('ghi') abc def ghi You can pass as many arguments as you want to “print”, separated by commas. Each will be printed, in order, with a space between them: >>> print('abcd', 'efgh', [10, 20, 30], 99, 'ijkl') abcd efgh [10, 20, 30] 99 ijkl We’ll see, below, how we can change these two default behaviors. Inputs and outputs If “print” is a function, then it must have a return value. Let’s take a look: >>> x = print('abcd') >>> type(x) NoneType In other words: “print” returns None, no matter what you print. After all, you’re not printing in order to get a return value, but rather for the side effect. What about arguments to “print”? Well, we’ve already seen that we can pass any number of arguments, each of which will be printed. But there are some optional parameters that we can pass, as well. The two most relevant ones allow us to customize the behavior we saw before, changing what string appears between printed items and what is placed at the end of the output. The “sep” parameter, for example, defaults to ‘ ‘ (a space character), and is placed between printed items. We can set this to any string, including a multi-character string: >>> print('a', 'b', 'c', sep='*') a*b*c >>> print('abc', 'def', 'ghi', sep='***') abc***def***ghi >>> print([10, 20, 30], [40, 50, 60], [70, 80, 90], sep='***') [10, 20, 30]***[40, 50, 60]***[70, 80, 90] Notice that “sep” is placed between the arguments to “print”, not between the elements of each argument. Thus in this third example, the ‘***’ goes between the lists, rather than between the integer elements of the lists. If you want the arguments to be printed alongside one another, you can set “sep” to be an empty string: >>> print('abc', 'def', 'ghi', sep='') abcdefghi Similarly, the “end” parameter defaults to ‘\n’ (newline), but can contain any string. It determines what’s printed after “print” is done. For example, if you want to have some extra lines after you print something, just change “end” so that it has a few newlines: >>> def foo(): print('abc', end='\n\n\n') print('def', end='\n\n\n') >>> foo() abc def If, by contrast, you don’t want “print” to add a newline at the end of what you print, you can set “end” to be an empty string: >>> def foo(): print('abc', end='') print('def', end='') >>> foo() abcdef>>> Notice how in the Python interactive shell, using the empty string to print something means that the next ‘>>>’ prompt comes after what you printed. After all, you didn’t ask for there to be a newline after what you wrote, and Python complied with your request. Of course, you can pass values for “end” that don’t involve newlines at all. For example, let’s say that you want to output multiple fields to the screen, with each field printed in a separate line: >>> def foo(): print('abc', end=':') print('def', end=':') print('ghi') >>> foo() abc:def:ghi Printing to files By default, “print” sends its data to standard output, known in Python as “sys.stdout”. While the “sys” module is automatically loaded along with Python, its name isn’t available unless you explicitly “import sys”. The “print” function lets you specify, with the “file” parameter, another file-like object (i.e., one that adheres to the appropriate protocol) to which you want to write. The object must be writable, but other than that, you can use any object. For example: >>> f = open('myfile.txt', 'w') >>> print('hello') hello >>> print('hello???', file=f) >>> print('hello again') hello again >>> f.close() >>> print(open('myfile.txt').read()) hello??? In this case, the output was written to a file. But we could also have written to a StringIO object, for example, which acts like a file but isn’t one. Note that if I hadn’t closed “f” in the above example, the output wouldn’t have arrived in the file. That’s because Python buffers all output by default; whenever you write to a file, the data is only actually written when the buffer fills up (and is flushed), when you invoke the “flush” method explicitly, or when you close the file, and thus flush implicitly. Using the “with” construct with a file object closes it, and thus flushes the buffers as well. There is another way to flush the output buffer, however: We can pass a True value to the “flush” parameter in “print”. In such a case, the output is immediately flushed to disk, and thus written. This might sound great, but remember that the point of buffering is to lessen the load on the disk and on the computer’s I/O system. So flush when you need, but don’t do it all of the time — unless you’re paid by the hour, and it’s in your interest to have things work more slowly. Here’s an example of printing with and without flush: >>> f = open('myfile.txt', 'w') >>> print('abc', file=f) >>> print('def', file=f) >>> print(open('myfile.txt').read()) # no flush, and thus empty file >>> print('ghi', file=f, flush=True) >>> print(open('myfile.txt').read()) # all data has been flushed to disk abc def ghi You might have noticed a small inconsistency here: “print” writes to files, by default “sys.stdout”. And if we don’t flush or close the file, the output is buffered. So, why don’t we have to flush (or close, not that this is a good idea) when we print to the screen? The answer is that “sys.stdout” is treated specially by Python. As the Python docs say, it is “line buffered,” meaning that every time we send a newline character (‘\n’), the output is flushed. So long as you are printing things to “sys.stdout” that end with a newline — and why wouldn’t you be doing that? — you won’t notice the buffering. Remember Python 2? As I write this, in January 2019, there are fewer than 12 months remaining before Python 2 is no longer supported or maintained. This doesn’t change the fact that many of my clients are still using Python 2 (because rewriting their large code base isn’t worthwhile or feasible). If you’re still using Python 2, you should really be trying to move to Python 3. And indeed, one of the things that strikes people moving from Python 2 to 3 would be the differences in “print”. First and foremost, “print” in Python 2 is a statement, not an expression. This means that the parentheses in 2 are optional, while they’re mandatory in 3 — one of the first things that people learn when they move from 2 to 3. This also means that “print” in Python 2 cannot be passed to other functions. In Python 3, you can. Python 2’s “print” statement didn’t have the parameters (or defaults) that we have at our disposal. You wanted to print to a file other than “sys.stdout”? Assign it to “sys.stdout” to use “print” — or just write to the file with the “write” method for files. You wanted “print” not to descend a line after printing? Put a comma at the end of the line. (Yes, really; this is ugly, but it works.) What if you’re working in Python 2, and want to get a taste of Python 3’s print function? You can add this line to your code: from __future__ import print_function Once you have done so, Python 3’s “print” function will be in place. Now I know that Python 3 is no longer in the future; indeed, you could say that Python 2 is in the past. But for many people who want to transition or learn how to do it, this is a good method. But watch out: If you have calls to “print” without parentheses, or are commas to avoid descending a line, then you’ll need to do more than just this import. You will need to go through your code, and make sure that it works in this way. So while that might seem like a wise way to to, it’s only the first step of a much larger transition from 2 to 3 that you’ll need to make. Enjoyed this article? Join more than 11,000 other developers who receive my free, weekly “Better developers” newsletter. Every Monday, you’ll get an article like this one about software development and Python: FYI Formatting seems to be a bit off in the code examples. Grr, thanks for pointing that out; I’ll double (triple?) check that and fix.
https://lerner.co.il/2019/01/18/beyond-the-hello-world-of-pythons-print-function/?share=facebook
CC-MAIN-2019-30
refinedweb
1,791
76.56
Odoo Help Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps: CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc. how to set a button click to call a menu item? i want to set a button click to invoke a menu ?that mean wen click on the button test then load the test.menu ..how can i done this? Hello Aneesh, Give menu action to the button. Ex:- <button name="%(sale.action_order)d" string="test" type="action" class="oe_highlight" /> When we click on this button, Sale order menu will open. Or Try This :- <button name="action_view_menu" string="test" type="object" class="oe_highlight" /> In Py :- @api.multi def action_view_menu(self): action = self.env.ref('sale.action_order) result = action.read()[0] return result Hope this works for you. Thanks, can u pls explain this code? When you click on the button, it refers to action of sale order and open the sale order. We know that with a menu an action is associated and based on that 'action' system performs the task. So for your requirement we can call it other way round and on button click we can return the appropriate action. For example, you can search in odoo code here: addons -> event -> models -> event.py : method name : action_event_registration_report Here it tries to search for an 'action' and return the 'action'. OR You can create the button of type 'action' Hope this helps !!. About This Community Odoo Training Center Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now
https://www.odoo.com/forum/help-1/question/how-to-set-a-button-click-to-call-a-menu-item-95163
CC-MAIN-2018-05
refinedweb
268
68.77
There_. struct SomethingInternal { int widget; short widgetFlags; char widgetLevel; char needs_more_cowbell; int needs_more_time; }; Bonus chatter: The application had an easy time messing with the internal array because the source code to the C runtime library is included with the compiler,_ member. I continue to be amazed at the level of effort Microsoft go to in order to accommodate other people's stupid design and implementation choices. I wish Microsoft would just start publishing compatibility issues and tell the developers to go do anatomically impossible things to themselves. Compatibility should be reserved for programs written properly, not poorly-written trash. It is this sort of thing which makes fruit-based operating systems seem more stable and better written, even when they aren't. The horror of MinGW piggybacking on MSVCRT instead of implementing its own Windows-compatible CRT is the reason one can't printf a long double in MinGW: MinGW uses 80-bit long doubles, while the CRT considers a long double the same as a double… @Anon: Even with a manifest explicitly specifying the execution level as asInvoker? Could you tell us what kind of application it was that it warranted this amount of effort from you side? External or internal? Maybe some nuclear plant controlling SW (well, on second thought, hopefully not ;) Just to confuse things further. Starting with Windows Server 2003, there are some supported side-by-side assemblies (msdn.microsoft.com/…/aa376609.aspx): – WinHTTP 5.1 – Microsoft Isolation Automation assemblies that enable the use of side-by-side assemblies with scripting. – Shell Common Controls version 6.0 (Comctl32.dll) – GDI Plus version 1.0 (GDIplus.dll) – Visual C++ Run-time Libraries version 6.0 They don't document the names of the assemblies, but they are around on MSDN: – Microsoft.Windows.WinHTTP (msdn.microsoft.com/…/aa384082.aspx) – Microsoft.Windows.Common-Controls (nobody knows where it came from; lost to the sands of time) – Microsoft.Windows.GdiPlus (no idea where i found that) – vcrt 6? Who knows If you do need to ship another version of the Visual C++ libraries, their side-by-side assembly identifiers are also documented (msdn.microsoft.com/…/ms235624.aspx): – Microsoft.VC90.ATL (Active Template Library) – Microsoft.VC90.CRT (C Runtime Library) – Microsoft.VC90.OpenMP (OpenMP Library) (i omitted the names of four other assemblies; so that people are not tempted to use them) @Anon — even today you will find questions on the official Visual C++ forums with programmers asking how they can link to MSVCRT.dll instead of the proper runtime for the current version of Visual C++. Some get fairly irate when told they shouldn't do it. It does seem like an obvious path if you don't want to use an installer to distribute your software. As I recall, DEC (Digital Equipment Corporation) chose the opposite route: VAX/VMS was the distribution channel for all of the language runtimes. This simplified life for the applications developers (presumably at the cost of dealing with DLL Hell). A friend who worked there told me that the OS engineers, in particular, thought this was a good idea, but they were afraid the product folks would try to undo the decision. To make it harder to undo, they wrote bits of the OS in each of the languages that DEC had compilers for: BLISS, C, FORTRAN, Pascal, etc. With the OS dependent on the runtimes for all of the languages, it became much harder for others to argue that the OS shouldn't include the runtimes. "There's the mistake. It is perfectly reasonable for the C library to be a platform standard library. The same is not true of C++." Why is C so special? Why can't I have the Pascal, or the Haskell runtime library to be a platform standard library? IIRC MinGW doesn't use MSVCRT.DLL because they don't know any better, but because linking with MSVCR71.DLL or MSVCR80.DLL or … and then publishing binary versions of MinGW (or GPL software compiled with MinGW) with the required "redistributable" DLLs would be a GPL violation. > fruit It's OK to say "Apple". @Joker_vD: C++ requires too much knowledge of class layout at compile time, meaning you can't muck around behind the scenes in the library without breaking some apps. This goes even for private members of the class – the compiler accounts for those during class compilation, so if the actual binary doesn't match the header precisely, <kaboom>. To anyone high enough up at MS to make the call: We all understand you can't just not put the compatibility stuff in place (people then claim you broke things on purpose). But please start naming and shaming the companies that do absurd things like the example given above. It's not an optimal solution, but perhaps a bit of 'hey, look how much they suck' pressure would get at least some companies to clean up their acts. As to source code: Releasing the source works if everyone is working hard toward making a stable working environment for the user. If some people are instead trying to do whatever they have to in order to get the code out the door tomorrow, it doesn't help. @John – on MinGW – is there any reason they can't write their own CRT? I imagine most of the libc should be useable (libc is LGPL), is there anything in MSVCRT that can't be replicated in a reasonable timeframe? Or is it just that no one's bothered to try? Off-topic question: why the umlaut on coördination? @Medinoc Indeed, that will cause it to fail silently when AppCompat tries to force elevation. "keeping one DLL compatible with all versions of Visual C++ was a maintenance nightmare" That's what came to mind when I learned about the WDF team's approach to UMDF / KDMF distribution. "Wel will make sure newer versions are compatible with all existing drivers." Good Luck! :-) [Ah, the "There is no acceptable way for me to do what I want, so I'm FORCED to do it in an unacceptable manner" argument. This is like "I was forced to park in a fire lane because there were no parking spaces left". -Raymond] The tools that you disparage for doing unacceptable things have greater reputation than all of MS. We on this blog laugh with you at the results of people doing unacceptable things and wondering why disaster strikes, but this time the answer must be make an acceptable way or deal with the consequences of not doing so. GCC was ported to target Windows because a cross-compiler must exist, and at the time of the port MS compilers sucked badly. Cygwin exists because the POSIX subsystem failed of its promise. > why the umlaut on coördination? So the two "o"s are pronounced individually rather than as a diphthong (like "cool"). Compare reënter. It is more usual to use a hyphen (re-enter) or just bleed the two words together and trust on the user being able to infer pronunciation from context (coordination) but that's not how Raymond rolls. Jeff: "ö" can be "o-umlaut" but also "o with a trema", indicating the vowel is pronounced unaltered and separate from the first one. So it is "co-ordination", and not "[cuurdinaishon]" or "[cohrdinaishon]" (sorry for not using IPA). @Jeff: From en.wikipedia.org/…/Diacritic: The main use of diacritical marks in the Latin script is to change the sound-value of the letter to which they are added. Examples from English are the diaereses in naïve and Noël, which show that the vowel with the diaeresis mark is pronounced separately from the preceding vowel; Raymond often uses the diacritic marks on English words like that, even though they are archaic in modern English and almost never used anymore. I think he explained why once, but I forget the exact reason. Well, looks like I was a couple of minutes too slow on my answer :) [As noted elsewhere, the correct solution is "Write and ship your own runtime library." Otherwise you may break at any future version of MSVCRT.DLL, since MSVCRT.DLL is not part of the API surface. -Raymond] GCC targets MSVCRT.DLL as it was in NT4 when it was part of the API surface. Unless this is to be revoked ex post facto then nothing breaks. @Mityador: "The 3rd party apps already depend (indirectly) on MSVCRT.DLL via other system DLLs (e.g. USER32.DLL, GDI32.DLL, COMCTL32.DLL etc.)." None of the DLLs you name import msvcrt.dll. Ugh! All of this angst and hand-wringing to justify or disparage the use of a system DLL! Do NOT use DLLs unless you MUST. Link your freakin' application against all libraries it uses so that none of this is relevant. Obligatory preemptive anti-snark: buh, buh, in Windows 95 days it was too memory intensive! Are we seriously still in a memory crunch? And seriously, with function-level linking, you pay only for what you use. Please! Stop the insanity. Link your freakin' apps fully. [Please! Stop the insanity. Link your freakin' apps fully. -Steve Wolf] Yes, so heartbleed-like vulnerabilities can stay in forever! You usually are pretty thorough about linking to previous relevant blog posts. But this time you forgot "party on". @Snark – Vendors had to issue patches for heart-bleed. No magical fix in some DLL works across the board.. :( DLLs only make sense where you want to supply hooks for dynamic behavior, you define it rigorously, and you work hard to ensure the interfaces are secure and cannot bust your runtime. Every other places, use a freakin' static link so that your app as-test is the one your customers actually run. I second this "Why is C so special? Why can't I have the Pascal, or the Haskell runtime library to be a platform standard library?" Everyone likes to play high and mighty until it comes to their language of choice or their own mistakes. Typical. Play by the same rules or be a hypocrite, your choice. Windows is Not *nix. [It was not part of the API surface in NT4 either. It just happened to be there, just like today. -Raymond] Fair enough. In that case, dropping the copy of MSVCRT.DLL from MSVC 4.2 in System32 if it's not there should be safe. Nitpick: MSVCRT.DLL did not exist when Win95 was released, as VC 4.2 did not exist. And even the current MSVCRT.DLL still have to support old apps that linked to it for backward compatiblity. "especially since it required the Windows team to do things like push a new version of MSVCRT.DLL to all downlevel platforms whenever a new version of Visual C/C++ came out. " I think that was a myth, unless there was some important bug in a new version of MSVCRT that needed fixing (eg the Microsoft Libraries Update) Of a cursory search of the main system DLLs (user32, advapi32, comctl32, kernel32, ntdll, gdi32) it seems only advapi32 links directly to MSVCRT the rest seem to distill down to ntdll which last I checked was the interface to the kernel. Thus… if Advapi internalizes its version of the CRT (NTDLL has a LOT of exported CRT functions… so it might be able to use those instead) MS could just get rid of MSVCRT… and IMHO: SHOULD to prevent just this sort of craziness. The fact that this is even a debate is fairly stupid… it's MS' operating system, if they say not to link against it… DON'T. @kantos: If MS had not once said to link against it the debate would not exist. @alegr1: Your premise on this is slightly incorrect: InstallShield elevates because it's manifested to be so in new versions and some features wouldn't work without elevation anyway in old versions. UAC-Aware applications are not subject to elevation based on name. E.g. you can manifest an installer named Setup.exe and it will install per-user no elevation if you do it right. . :(" Building your application as a single monstrous EXE that statically links in the C and C++ Runtimes does not mean that you can avoid that. There are video drivers, mouse drivers, network drivers, printer drivers, audio drivers, etc., that your application uses, and those involve DLLs too. These aren't provided as part of the OS. @Bryan W Try it. Add an as-invoker manifest to an application renamed "setup.exe" and see what happens. I have – it fails! @Yuhong Bao "And even the current MSVCRT.DLL still have to support old apps that linked to it for backward compatiblity." Yes, that's the point of the article. NO apps should be linking to it, so it SHOULDN'T have to support anything for backwards-compatibility that isn't an OS component, and OS components would be updated alongside it! @panzi: en.wikipedia.org/…/Libiberty @Anon, @Brian W: An MSDN blog that I can no longer find via Google said to fix the problem by shimming the application specific non installer before shipping it. The situation apparently is the auto-detect is so stupid that if it doesn't carry the manifest for the latest windows version it will auto-elevate regardless of manifest. This creates a nasty problem for Cygwin's "patch.exe" which cannot be renamed. It's really too bad the auto-elevate is too stupid to figure out a console program named patch.exe should be ignored as that name is ancient now. "on MinGW – is there any reason they can't write their own CRT?" Because it'd defeat the purpose of the "Min" in their name. No idea why someone can't make a "MediumGW" that ships something like a copy of the reactos msvcrt though. MinGW is working to deal with the issues that might arise from using msvcrt.dll. For example, newer versions of MinGW include their own `printf()` family of functions to deal with such things as the incompatible `long double` types and to support C99 format specs that aren't supported by MSVCRT.DLL. TL;DR version: %WINDIR%System32MSVCRT.DLL is the "Microsoft Windows OS C Language Standard Library". That the Windows OS C/C++ compiler shares a lot with the Microsoft C/C++ Optimizing Compiler shipped in Visual C++ (which in turn is shipped in Visual Studio) should not be confused with using the same runtime library. @Anon: You must be doing it wrong. I can successfully add manifest to file named setup.exe for which then no UAC pops up. > Compatibility should be reserved for programs written properly, not poorly-written trash. Yes, that's how it *should* be in a perfect world. End users should not be punished for the mistakes of bad developers. But, unfortunately, we do not live in a perfect world, and, as Raymond has explained time after time, that would break many old line-of-business applications, many of which are more than two decades old and have lost the source code (or the tools needed to re-build it). As for the fruit-named approach, as a computer collector, I find infuriating not being able to run some programs from, for example, 1987 in a computer made in 1994… because of not keeping backwards compatibility (and yes, I own several computers from that company in my collection, spanning two decades). On the other hand, in Windows, you are almost warrantied being able to run a 1985 executable in Windows 8.1 (at least, in the 32-bit version). @Jan Ringoš And as soon as a new Windows version (service pack, major release) is used, it will break. @Antonio 'Grijan' I agree, the Microsoft approach is generally better, but not in the specific case of when Stability, Security, and/or Sanity are sacrificed at the altar of Compatibility. My chief example of this: You can't write a Setup application named *setup*.exe that doesn't require Admin access to a machine — Windows will elevate it and, if you force Windows to *not* elevate your Setup application, it will fail silently. [ For example, if a new C++ language feature required a change to the ostream class, you had to be careful to design your change so that the class was still binary-compatible with the older version of the class. ] There's the mistake. It is perfectly reasonable for the C library to be a platform standard library. The same is not true of C++. @Medinoc: Last I checked you get your choice but the default is MSVCRT. The driving force is "Why the *** should I ship a C standard library. This should be a platform library like all other platforms." Especially given MS's colossal screw-ups in the packing methods of MSVC*.DLL in the past. @Joker_vD: Because the OS is written in C and because the C library provides binary compatibility (almost*) for free and because the contents of the standard library change so slowly. * The only exceptions are the getc and putc macros which means the format of FILE * can't change; but then again why would it ever change? @BrianW: [InstallShield elevates because it's manifested to be so in new versions and some features wouldn't work without elevation anyway in old versions.] Seriously? A glorified XML/table editor needs to run with administrator privileges? I second Joshua. Consider a non-Microsoft DLL as part of a non-Microsoft SDK for 3rd party application developers. For me, as an author of such SDK, it is a natural that you do not want your DLL to bloat apps of your customers. This implies: * You do not want to impose a dependency on MSVCRXXX.DLL (for whatever number XXX), because various customers use various MSVC versions. * You do not want to link C runtime statically. (consider the SDK may have many DLLs, you do not want plethora of C runtime instances in a process memory if it uses multiple of them). Furthermore consider you need to be compatible with all your customers, despite MSVC version they are using for building their apps. Hence you (as the SDK developer) have to be careful to not expose anything from C runtime on the SDK interface anyway. This involves things like: * C runtime resources allocated in the DLL (e.g. malloc()) must be released in the same DLL (free()). I.e. you cannot return malloc'ed memory and let the caller free it: you must free it in a function exported from your DLL. * Not using C/C++ runtime types (e.g. FILE*, std::string) in the public interface. I.e. no exported function takes that as a parameter and no function returns it. IMHO, sticking with MSVCRT.DLL (from the oldest Windows version supported by the SDK) is the most Right Thing (TM) for such use case. The 3rd party apps already depend (indirectly) on MSVCRT.DLL via other system DLLs (e.g. USER32.DLL, GDI32.DLL, COMCTL32.DLL etc.). So this way you do not bloat the app's memory space. You have just be compatible with the MSVCRT.DLL from the oldest Windows version supported by the SDK and not using the C++ stuff to avoid symbol mangling issues. (And of course: test, test and test once more, but that's a must-to-do for any SW development anyway, isn't it?) Nitpicking: MSVCRT.DLL doesn't actually contain ostream, or any C++ classes apart from the most basic runtime support. The legacy, non-templated (pre-STL) stream classes are in msvcirt.dll. Specific instantiations of std::basic_ostream (for char and unsigned short – VC6 has a typedef for wchar_t, not a real type) are in msvcp60.dll. These are all Windows components on Windows 7 – I think because Microsoft Management Console (for one) was originally written against MFC 6 for Windows 2000. Since anything actually written in VC6, using the Multithreaded DLL switch, will still be linking to these DLLs, they still have to be compatible with real VC6 code. @Joshua: Windows is not a *nix. The C runtime is not its lowest-level API. The Microsoft C runtime contains no calls to kernel mode. The lowest level it links to – in the VS6SP5 version I checked – is kernel32.dll, and that's true for all versions I have (everything from 6.0 to 12.0, barring 7.0) except for the latest version of 8.0 which for some reason is importing _getdrives from msvcrt.dll. If using the static multithreaded version of the runtime, you have to use _beginthread or _beginthreadex rather than Win32's CreateThread, so that the runtime is properly initialized for the new thread. Strictly speaking you should do it for the DLL version too, but the DLL version uses the callback to DllMain to initialize as a backstop. The current msvcrt.dll on Windows 7 SP1 has had its imports refactored so it now does take direct dependencies on kernelbase.dll, ntdll.dll and the API-MS-Win-XXX-L1-1-0 DLLs from the MinWin project. Windows CE (now called Windows Embedded Compact) does use a C runtime as its lowest-level API: coredll.dll has a mixture of C runtime APIs and Win32 APIs, with duplicated functions being removed. There seems no rhyme or reason to why a C API or a Win32 API was chosen in each case. This does lead to odd situations like the time() function not being available: you call GetSystemTime() and convert it yourself (that's a particularly horrible example as time.h *is* present, and it *does* declare time(), but the function is not present in any standard DLL). In the threading example, CreateThread is available but neither _beginthread or _beginthreadex is present. Each platform's coredll.dll is different, different static libraries and sometimes source code being linked into it at OS build time. >You can't write a Setup application named *setup*.exe that doesn't require Admin access to a machine InstallShield IDE always causes an elevation prompt, because of the magic word in its name. @Ray: [Because that's how I learned the word. -Raymond] Are you pronouncing "what" and "why" as "hwat" and "hwy"? @Joshua: "If MS had not once said to link against it the debate would not exist." The problem with that is that the only time Microsoft had said to link against it for end user programs was before they started with the individual naming of the CRT libraries. After that they told end users to link against the appropriately named libraries, or if you don't want to ship around a CRT library, link against the static version of the CRT. After actually using VS from .NET onwards, Microsoft has always had their developer tools link against the numbered version of the CRT. XP was also about the time that MSVCRT became a system component. The only more recent cases where developers could link against the system CRT was for driver development iirc, but you had to get the DDK/WDK to link against it, it was only ever intended for driver related utilities to an extent, and they revoked that starting with Windows 8. What's more, before Windows 8, the driver environment was completely separate. There was no integration into VS like there is these days. So you had to deliberately get the DDK/WDK, ignore Microsoft in regards to what to link against the system CRT, start of a separate driver build environment command prompt or set up VS to use these paths and then build. There was no way to accidentally link against it. For Windows 8, they have started to ship a static library for the MSVCRT dependent driver utilities and I have a feeling that this was due to the misuse of the system CRT import library. "XP was also about the time that MSVCRT became a system component." With Win2000 actually. Right, was one out. Was a bit unsure which was why I used about.:3 I just wish that Visual Studio provided better support for writing code that doesn't use the C runtime library at all. You can do it, but it isn't as straightforward as it could be – there are unexpected dependencies on it which require you to turn off some of the compiler's security features. (I suppose it would be possible to pull out those particular parts of the C runtime and compile them directly into your program, but you'd lose compatibility with future versions of Visual Studio and there might be legal issues.) @mikeb: no matter what they do, there's no way to tell what new issues might be introduced by a future version of msvcrt.dll. So if you want your application to be compatible with future versions of Windows, MinGW (in the default configuration) is not a good choice. @Joshua: note that the argument about backwards compatibility only applies to the 32-bit version. The 64-bit version has never been advertised as being suitable for third-party developers to use. @Medinoc I only once cross compiled a tiny shell program with MinGW so I'm not an expert on this, but I did use the option -liberty, which gave me the GNU (or C99?) printf. I think. I can't find *any* documentation on this, only Makefiles that use it. I don't even know how I know about this. Maybe some compiler error message told me about it? @Harry Johnston: Except that I think the original Platform SDK 64-bit compilers used it. "If your program requires the Visual C/C++ Run-Time library, then your program needs to install the appropriate version. (There are redistributable packages you can include with your application.)" Too bad if you have Visual Studio 2010 SP1 because the bootstrap package for the Visual C++ runtime has the wrong ProductId (it's a GUID) and download URL. The README contains instructions only to fix the download URL, and they're half wrong anyway. If you don't update the ProductId at the same time the installer just assumes the runtime isn't installed and tries to install it again. And again. And again. connect.microsoft.com/…/msdn-forum-vcredist-x86-bootstrapper-package-xml-content-wrong I'm sure Microsoft handles thousands of GUIDs correctly every product release, but the above issue and the time someone changed the interface IDs for some ADO components really screwed me over. support.microsoft.com/…/2517589 When a fire lane is full of parked cars, is it still a fire lane? (Is Heartbleed the one where web servers divulge 64k in response to existential queries?) Windows: Not a Microsoft Visual C/C++ Run-Time delivery channel… OR THE GREATEST MICROSOFT VISUAL C/C++ RUN-TIME DELIVERY CHANNEL EVER? I believe mingw used msvcrt.dll because it was the Microsoft C compiler's C runtime, and they wanted to use the same runtime. Microsoft's decision to change the C runtime DLL filename with every new compiler release came later, and mingw just kept using the C runtime from the older compiler. It might seem strange today, but think about it: the mingw people came from Unix-style operating systems, where all compilers share a common C library. It was natural for them to do the same on Windows, even more when Microsoft itself was seen doing the same thing (including system components using that common C library); they would see no reason to gratuitously implement a separate, potentially incompatible (think about passing FILE pointers between modules) C runtime. And as to why doesn't mingw create its own C runtime now… I believe it's because of backwards compatibility. Programs compiled with mingw expect that the C runtime is the C runtime from that old Microsoft C compiler, or new versions of it. If that is changed now, a program compiled with the old mingw loading a plugin compiled with the new mingw (or vice versa) could break, since there would be two incompatible runtimes loaded (and the program could expect to be able to for instance allocate memory in the plugin and free it in the main program). @anon: yep it works fine. Don't be surprised that using older versions and such doesn't work though. But yeah I've tested and seen it working fine. @alegr1: it's more complex than that. Some of the more esoteric likely less used features fail anymore. Can't really say if it's the way it is anymore but as long as com extraction exists you're probably looking at either some form of elevation or a portion of customers for whom it doesn't work. @joshua: on this blog of all things I would expect you to guess why there's more than one manifest version :-) "Why is C so special? Why can't I have the Pascal, or the Haskell runtime library to be a platform standard library?" I third this. Unlike say Haskell, you can actually write fully functional C programs on Win32 without using the C standard library, because: * The standard library is written in C, which means it's possible to rewrite the parts you need. * The Win32 API is a C API, which means you don't need a standard library written in another language to call it. I've done this as an experiment (not in production code). The Haskell standard libraries could also be written in Haskell, using compiler extensions (because you need to define things like integers). I don't know anything about Pascal. For Python or Lua or JavaScript it might be difficult, but you could statically link with the interpreter and a module like ctypes. Windows team could choose to rename its version to WINCRT.DLL and change Windows build system to use it (at least all low level components). Let Visual Studio own the MSVCRT.DLL. Very few people would link against an unknown new DLL.? I mean it would be silly to do it for every single little program, but if it is a product of a huge company like Oracle, Adobe, SAP etc., it might be easier to just give them a heads up "you seem to depend on undocumented internals, we'll break your code in 6 months". @Jason The problem is that there are still millions of users out there running non-updated versions of the code. And most vendors wouldn't update their old products to fix such an issue but only the current one (hey great way to get people to upgrade, when windows n+1 breaks the application!) So why not let people specify dependencies on MS-distributed components in a manifest embedded in the .exe so when the user double-clicks on it in Explorer, Explorer would parse that, check the needed components with the required versions are installed and if not, install them from Windows Update? Then that can be automatically filled in by Visual Studio when assembling the .exe. Or maybe Visual Studio could have an option to "export as installer for other people" that includes at least an installer for the runtime for people who don't have internet. @immibis: Free Pascal, for example, is entirely written in Pascal, so it is self-hosting. There's no msvcrt.dll in sight. Of course, it won't stop you from doing evil things like linking your program against msvcrt.dll and calling its functions, if that's your wish. msvcrt.dll was linked from Visual C 6 programs. Why should Microsoft want that programs compiled with Visual C become non-functional? What's so special in maintaining one compatible DLL? There are uncounted other DLL's that have to be maintained anyway. I really like msvcrt.dll existing in the system and I will keep producing the programs that depend on it as long as I can. @Cesar: The problem is that ever since the release of Visual Studio.NET in 2002, it has been made loud and clear that programmers mustn't use MSVCRT in applications. For the whole not seeing a reason to implement a separate CRT, well MSVCRT was only ever there originally as a way to make applications behave when it came to using MSVCRT. This was in response to the stability on Windows 95/98 where programs would overwrite MSVCRT that was in System/System32 and cause drivers to die or act weird because the version of MSVCRT was incompatible. After February 2002 when Visual Studio.NET was released, Microsoft has been quite clear that post VC98 compilers must not use MSVCRT for Windows software development*. After that point it was also obvious that they saw it mainly as a compatibility thing when they never updated the main entry points in the library to be more standards conformant and it also allowed them to cut down on things inside the library itself. Two things that I can refer to that help support this was that for the mingw usage of wcs* functions, there was a report on how they didn't work on Windows XP due to MSVCRT not containing those functions. Secondly, inside the CRT sources there are lots of cases where you see #ifndef _SYSCRT /* * Register __clean_type_info_names so that we clean up all the * type_info.names that are allocated */ atexit(__clean_type_info_names); #endif /* _SYSCRT */ So not only is MSVCRT not guaranteed to contain everything, but it is also not guaranteed to work correctly in all cases. So while this could have been a point of contention back in time, now days it is silly to discuss it. Microsoft has been clear on what MSVCRT is there for. @acq: I will assume that you meant your comment to be humourous and just remind you that reasoning like that is why Windows has its 64-bit components in SYSTEM32 and its 32-bit ones in SYSWOW64. Are we allowed to use CRTDLL.DLL as an alternative to MSVCRT.DLL? @Bryan W, Alegr1, Anon: I just tested asInvoker by building a simple program called TestSetup.exe (it just displayed a message box) with Visual Studio 2010 SP1 on Windows 7 from my UAC-enabled admin account. I got a weird hybrid result: asInvoker worked (I tested with CheckTokenMembership() with and without "run as administrator"). However, after my simple program exited (returning zero) when running non-elevated, I got a dialog box saying that maybe the install failed, and asked whether I wanted to run it again with some compatibility options enabled (and the option to run it again requires elevation). So Windows 7 still detected it as a setup program, but didn't prevent me from running it un-elevated. discontinued in VS2010? [It may be best for you, because you externalized part of the cost of supporting future versions of Windows. Now it's Windows's job to support your app, rather than vice versa. -Raymond] MS's own pickle. VC6 links against it by default. support.microsoft.com/…/259403 What's worse: not shipping MSVCRT.DLL or shipping the last redistributable version of what is now a "you shall not upgrade" system component? "The set of applications compiled with VC6 is relatively constant, not growing. Also, can you go talk to the people who say "Microsoft should tell these apps to screw off and not be held back with all this backward compatibility nonsense"? I can't really tell whose side everybody is on any more. -Raymond" Easy. If it doesn't affect me or programs I use then screw it, if it does affect, then you MUST support it. @medinoc: you have to include an extra manifest section for compatibility to eliminate that prompt. So you have the vista key but are missing the 7+ key :-) I can't recall exactly what you have to set up, but it's weird. @Raymond: the answer is everyone is on the side of what's most convenient for them at the moment. Obviously Microsoft should ship windows 9 no back compat edition and windows 9 full compat edition since that worked so well for ie7! /s >_more_time member. I guess that's a lesson the .NET team is about to learn. Thanks to reflection you don't even need to copy the declaration of the array! visualstudio.uservoice.com/…/4083118-allow-developers-to-step-through-net-framework-so This is just a consequence of a broken expectation. Because Windows actually *is* a delivery device for executable code. It has been quite a while since I plugged in a USB device or hooked up a new printer, etcetera, and Windows did not automatically install the device driver for the device. Pretty strange that it is capable of delivering non-Microsoft files but can't do the same for its own. The application manifest in VS2005+8 was a great opportunity to implement this. That it didn't happen is surely a core reason it was discontinued in VS2010. Great loss. [Also, can you go talk to the people who say "Microsoft should tell these apps to screw off and not be held back with all this backward compatibility nonsense"? I can't really tell whose side everybody is on any more. -Raymond] My position seems to be unique: A published API is forever. A published ABI is for as long as the platform lasts. He who depends on a bug deserves to be broken. He who depends on undocumented functions is asking for trouble. But even I cannot always escape doing something nasty because the work must get done and there's no good way to do it. I have to live with the fact I have to then fix it up with every version of Windows that comes out. Business cost of poor technology choices. "Supported" doesn't mean much when we can't even buy bugfixes. @Mike Dimmick: "None of the DLLs you name import msvcrt.dll." True. Mea culpa. But there are others, which do import it (for example UXTHEME.DLL — btw, imported by COMCTL32.DLL version 6). @Raymond: "How do you test on versions of Windows that don't exist yet? -Raymond" We don't as well as we would not if we link with other C runtime. Furthermore the SDK has its own docs, where we document supported system versions. So supporting future Windows versions is not contractual, and it also wouldn't even if we use other C runtime. Still, of course, we do our best to not have problems in the future. Furthermore I do believe Microsoft is sane company too: Although MSVCRT.DLL interface is not contractual, can you really imagine MS will remove it, rename it, or stop providing standard C functions in it? Arguably, if it really happens, Microsoft shall no more be Microsoft as this company is actually defined by the focus on the compatibility, as your own posts in this blog document so well. (Feel free to call me *** for relying on your work ;-) SW design is about trade-offs and in the use case discussed we evaluated this approach as best one, taking the risks into account. Believe me I would prefer if Microsoft provides better way for SDKs which do not want to exhibit the problems described in my previous comment. > So much for "All these compatibility problems would go away if you published the source code." Publishing the source code makes it easier to introduce compatibility problems, because it lays bare all the internal undocumented behaviors. A well-known example is the Linux-Version of Skype, which used undocumented Features of ALSA, and required X11-extensions without fallbacks. The problem could go away if *everyone* published their source code, as you could quickly produce a patch. Anyway, as it is part of Microsoft's business model to fix the bugs of other people, maybe that could even be an advantage :3 @MSVCRT.DLL Enthusiast: CRTDLL.DLL is even older (dates to NT 3.1 era I think). @Harry Johnston I used to do this with toy Win16 apps, where it was easier because the Win16 API included more CRT-like functions than the Win32 API does. (By "toy" I mean that the icon was normally the largest part.) If it's a compiler specific dll, the 64-bit version of msvcrt32.dll is obscene. @immibis: Windows is using the PASCAL calling convention for almost all APIs. Not the C calling convention. Thus Windows API surface is more tainted by PASCAL than by C. @Snark: "[Please! Stop the insanity. Link your freakin' apps fully. -Steve Wolf] Yes, so heartbleed-like vulnerabilities can stay in forever!" The first thing I do every time I create a new C/C++ project is to select static linking for Debug and Release. Not because I'm a unix zealot, but because distributing the runtime is a PITA, but more importantly, its installer extracts and leaves its "temporary" binary files in the root of the drive. This is such an ugly bug it makes me wanna cry. Naturally, I understand if you learned to spell with a diaeresis (just as I learned to spell in the American way), but it's not like the Ö is just as easy to type. Presumably you're pressing the Windows logo key + Spacebar every time you need to type it, in order to switch to something like the German keyboard, and then the same in order to switch back. Since the right thing in this case, as defined by descriptive lexicography, is easier to do than the wrong thing, aren't you trying to climb out of the "Pit of Success"? The more important question is, why do we need a needs_more_cowbell flag in the first place? Is it not always set to true? To solve this you need to add structure offset randomisation. Sure it will need compiler, linker, debugger and os changes. But lets see them figure out how to poke stuff then. @Boris: The US International keyboard is a lot easier. It turns " into a dead key such that " + o = ö. The only downside is writing actual quotation marks or apostrophes, since to do that you have to type " + [space]. For exactly this reason I dislike the US International layout, because the dead keys interfere with programming a lot. The X11 world has a much nicer variant called altgr-intl, which has no dead keys (ö is Right Alt + p, for example). I don't know if there's a way to use it in Windows. MNGoldenEagle: I don't mind learning a Serbocroatian keyboard layout in order to ensure that my Č, Ć, Đ, Š and Ž retain their diacritics, but that's because it isn't acceptable to leave them out in any but the most casual of contexts (such as instant messaging or informal emails). In this case, though, I don't quite see how Raymond's managed to retain the habit over the years, unless the resulting text looks subjectively incorrect. @MNGoldenEagle: It's easier to remember that ö is Alt+Num0246, and Ö is Alt+Num0214. I mean, everybody already has to memorize that the em-dash is Alt+Num0151, and the en-dash is Alt+Num0150, so two more combinations is no big deal… right? [It may be best for you, because you externalized part of the cost of supporting future versions of Windows. Now it's Windows's job to support your app, rather than vice versa. -Raymond] Actually, Microsoft chose to support these, and allow scope to creep, so Microsoft internalized the cost of supporting the external app. What's the business case for going to your boss and asking them to pay to maintain applications which Microsoft is currently maintaining for them at no cost? > ö Except commenters don't have the luxury of using HTML escape sequence in the comment box. (Though I suppose we could open a scratch HTML file.) How amusing. I quoted "> ö" (which I expected to include a semicolon) and now my (Raymond-edited) text shows "> ö" (which includes an umlaut.) Looks like there's a bug in Telligent HTML encoding; either my original plaintext wasn't HTML-encoded correctly originally, or Raymond's editing tool didn't HTML-encode it correctly when he added his own HTML. Looks like it's the former. Let's try this again: > ö @Boris, depending on the application, you can type Ctrl-: then O to get the O-with-diaresis. This generalizes to most (Western-language) common accented letters: Ctrl-~+n gives you n-with-a-tilde. (I happen to not be on a Windows machine right now so I can't demonstrate because I don't feel like looking up the HTML entities. @Maurits: well, now you broke it. Are you happy? @Jason: ?" If it's what I think Raymond seems to be hinting it is, then it's not just one product; this has actually shipped in many many applications, some of which are smaller applications from vendors which may no longer exist. @Rick C: to get ö to show up I had to type &ouml; @Maurits: But what did you type to get &ouml; ? Man, I hate quotations/escaping and especially, how many different schemes of those there are. Minicrt 4 L-iz-ife: "When a fire lane is full of parked cars, is it still a fire lane?" As one gentleman's (jerk's) Corvette can attest, yes! The fire engine will unhesitatingly ram the cars out of the way and the city will bill the owners for the damage. Ahem… "Games give you hand-eye coordination and spatial intelligence together with map-reading skills" "This gets even more complicated when the parent/child or owner/owned relationship crosses processes, because cross-process coordination is even harder than cross-thread coordination." "Since there is no coordination among the various applications, you're basically stuck playing a game of walls and ladders, hoping that your ladder is taller than everybody else's wall." "Like the adoption of a child, it's the sort of thing you should only be doing with the coordination of all three parties (the old parent, the new parent, and the child)." "Whenever there is a coordination problem, somebody says, 'Hey, let's create a process!'" "The effort required to fix the spelling was a bit more than usual, since the function was used by multiple teams, so there would have to be some coordination among the teams so everybody fixed their spelling at the same time." @Random User 29387 There is little more satisfying than knowing that firefighters and police will intentionally do as much damage as possible to a vehicle parked in a fire lane, except perhaps the knowledge that insurance won't pay for it. then you have strange firefighters – we learned that we *had* to do as least damage as possible given the constraints that the fire had to be put out (so if there's a way around the vehicle that isn't too much longer and doesn't damage it you have to take it). Of course you take the registration number and they then get a fine of 65€ and 1 point in their registration. Plus they have to pay for any damage that occured because they were in the fire lane, costs for towing them away, etc. But you as firefighter have the obligation to cause as less damage as possible, including to vehicles of idiots. out of curiosity, why aren't the various C runtime versions delivered through Windows update instead of requiring each application to embed the redist installer? Gregory: Are you asking why Windows Update isn't a Microsoft Visual C/C++ Run-Time delivery channel? Gabe: in other words, yes. It's so central in the Windows ecosystem I'm surprised developers' life isn't made easier (for those who link dynamically against the runtime). Same question could apply to DirectX RunTime. But maybe one would argue the list of runtimes would become so long it's not a sustainable position? Engywuck: I'm not 100% certain but I think the guy was not only in the lane, but also obstructing meaningful access to the fire plug. Either way, I'm satisfied with the explanation that different localities have different laws RE: liability of the fire dept, etc. we were especially told "don't do like in the movie when a car parks afront of a hydrant. If you have time to smash the windows you have time to put the firehous over or under the car" but ontopic: wsus delivers already .NET in the "features" section, other libraries could easily go there, too. Sure, .NET is needed for quite a few internal windows things instead of "only" third-party programs, but I wouldn't object of them going there :-) Engywuck: If a hose has too much of a bend or kink, it can decrease the flow too much. I think that typically they put the hose through the windows because that allows it to be straighter than going over, under, or around. I did recently see a photo where they had broken the windows to pass the hose through, only to find that there was still too much of a bend, and they had to pick up the car and move it a few inches over to get full pressure. But on topic: Gregory, I'm pretty sure that most would argue that Windows Update shouldn't be a delivery channel for anything besides updates. If you have some VC runtime that's been installed by a 3rd-party app, then WU should probably update it. I don't see why WU should be installing arbitrary software, though. @Gabe Microsoft Visual C++ Redistributables are, typically, "updates." They'd just fall under "other software" in Microsoft Update. A better question is "Why doesn't the redistributable installer simply come with all available versions of the redist, and why doesn't the new redist release with stripped-down versions of the old redist, to save space?" Did they fix the C stdlib to always work when the DLLs are copied beside the EXE yet? "I did recently see a photo where they had broken the windows to pass the hose through, only to find that there was still too much of a bend, and they had to pick up the car and move it a few inches over to get full pressure." Yes, that exact thing happened in Boston last week. I heard third-hand that the car was only 3 days old.
https://blogs.msdn.microsoft.com/oldnewthing/20140411-00/?p=1273
CC-MAIN-2017-34
refinedweb
8,449
62.78
Hey folks, I don't mean to beat a dead horse being that i have seen this discussed before, but here is my issue. I am having to merge two sets of property records, the records overlap for about 10 months worth, so i need to weed through them find the duplicate records, verify they are duplicates, and correct accordingly. I have seen code on here that will mark in a designate field all occurrences of a duplicate record with a designated string, however i have not been able to get that python script to work (4021 ArcGIS 10 Pre Release finding duplicates). So in the mean time i am left using Knowledge base solution 31854 which works great if my dupes came only in sets of 2. So any other ideas, or am i missing something here. And just a FYI, i am very green when it comes to Python and scripting in ArcGIS outside of Find Attribute Queries. Thanks As long as you have the tables joined together so that everything is one dataset... Calculate field, and choose the python parser and in the pre-logic: [HTML]uniqueList = [] def isDuplicate(inValue): if inValue in uniqueList: return 1 else: uniqueList.append(inValue) return 0[/HTML] then in the calculate field: [HTML]isDuplicate(!FIELD_NAME!)[/HTML] This sort of works for what i need it to do, i'll just have to add an additional step in the process to finalize verification of the records prior to removal.
https://community.esri.com/thread/50681-finding-duplicates
CC-MAIN-2018-43
refinedweb
247
64.44
Web Item A web item is a button or link that appears at the location you choose. Here are some things you can do with web items: Redirect to another location Invoke a script endpoint and run code, which can respond with: A flag A dialog A redirection to another page Examples Google Link Example A basic example of a web item is a link to Google at the top of the navigation bar. Fill out the web item form:You can understand the Section field’s values by reading the Atlassian web item documentation, or you can use the section finder tool.The Weight field determines what placement the web item is. If you set it to 1, the link becomes the first item on the left. Click Add to register the fragment. Go to the dashboard in a new tab, and see your new link. Click the link to go to Google. If you don’t change the key, the module from the first part of the tutorial will be overwritten. import com.onresolve.scriptrunner.runner.rest.common.CustomEndpointDelegate import groovy.json.JsonOutput import groovy.transform.BaseScript import javax.ws.rs.core.MultivaluedMap import javax.ws.rs.core.Response @BaseScript CustomEndpointDelegate delegate. Conditions must be written defensively. What is available in the context or jiraHelper map depends on the particular web section, and the page that it’s viewed on. For instance, a link in the top section ( system.top.navigation.bar) will never have access to the current issue. This differs from the Confluence behaviour, where it may or may not have access to additional items. If you are using a section like operations-top-level, you can assume you will always have the issue context variable defined.:Dialog { MultivaluedMap queryParams -> // get a reference to the current page... // def page = getPage...</p> <() }.$); Removing the dialog from the DOM when the dialog is hidden (for example when pressing the ESC key) is controlled by the data-aui-remove-on-hide attribute. Removing this attribute will hide the dialog rather than remove it when the dialog is hidden. In this case you will need to handle re-showing the dialog in your JavaScript code, the web item trigger will re-render a completely new dialog for you.() } Make sure to select Navigate to a link as the intention setting. Further examples Displaying a message if a page is publicly visible ( Atlassian Answers) Showing recent projects from a particular project category ( Atlassian Answers )
https://docs.adaptavist.com/sr4js/latest/features/fragments/custom-fragments/web-item
CC-MAIN-2021-10
refinedweb
413
57.27
Created on 2019-05-13 18:40 by gregory.p.smith, last changed 2019-11-07 17:48 by Marco Sulla. A Python pattern in code is to keep everything indented to look pretty while, yet when the triple quoted multiline string in question needs to not have leading whitespace, calling textwrap.dedent("""long multiline constant""") is a common pattern. rather than doing this computation at runtime, this is something that'd make sense to do at compilation time. A natural suggestion for this would be a new letter prefix for multiline string literals that triggers this. Probably not worth "wasting" a letter on this, so I'll understand if we reject the idea, but it'd be nice to have rather than importing textwrap and calling it all over the place just for this purpose. There are many workarounds but an actual syntax would enable writing code that looked like this: ```python class Castle: def __init__(self, name, lyrics=None): if not lyrics: lyrics = df"""\ We're knights of the round table We dance whene'er we're able We do routines and scenes With footwork impeccable. We dine well here in {name} We eat ham and jam and spam a lot. """ self._name = name self._lyrics = lyrics ``` Without generating a larger temporary always in memory string literal in the code object that gets converted at runtime to the desired dedented form via a textwrap.dedent() call. I chose "d" as the the letter to mean dedent. I don't have a strong preference if we ever do make this a feature. I agree that this is a recurring need and would be nice to have. +1 There's a long thread on something similar here: Carrying over into the following month: Here's an even older thread: In the more recent thread, I suggested that we give strings a dedent method. When called on a literal, the keyhole optimizer may do the dedent at compile time. Whether it does or not is a "quality of implementation" factor. The idea is to avoid the combinational explosion of yet another string prefix: urd'...' # unicode raw string dedent while still making string dedents easily discoverable, and with a sufficiently good interpreter, string literals will be dedented at compile time avoiding any runtime cost: Oh good, I thought this had come up before. Your method idea that could be optimized on literals makes a lot of sense, and is notably more readable than yet another letter prefix. Hi, I have been looking to get more acquainted with the peephole optimizer. Is it okay if I work on this? I'd say go for it. We can't guarantee we'll accept the feature yet, but I think the .dedent() method with an optimization pass approach is worthwhile making a proof of concept of regardless. For the record, I just came across this proposed feature for Java: Add text blocks to the Java language. A text block is a multi-line string literal that avoids the need for most escape sequences, automatically formats the string in predictable ways, and gives the developer control over format when desired. It seems to be similar to Python triple-quoted strings except that the compiler automatically dedents the string using a "re-indentation algorithm". (Which sounds to me similar to, if not identical, to that used by textwrap.) The JEP proposal says: A study of Google's large internal repository of Java source code showed that 98% of string literals, once converted to text blocks and formatted appropriately, would require removal of incidental white space. If Java introduced multi-line string solution without support for automatically removing incidental white space, then many developers would write a method to remove it themselves and/or lobby for the String class to include a removal method. which matches my own experience: *most* but not all of my indented triple-quotes strings start with incidental whitespace that I don't care about. But not quite all, so I think backwards compatibility requires that *by default* triple-quoted strings are not dedented. Note that there are a couple of major difference between the JEP proposal and this: - The JEP proposes to automatically dedent triple-quoted strings; this proposal requires an explicit call to .dedent(). - The JEP proposal allows the user to control the dedent by indenting, or not, the trailing end-quote; - however that means that in Java you won't be able to control the dedent if the string doesn't end with a final blank line; - Should the dedent method accept an optional int argument specifying the number of spaces to dedent by? (Defaulting to None, meaning "dedent by the common indent".) If so, that won't affect the compile-time optimization so long as the argument is a literal. - the JEP performs the dedent before backslash escapes are interpreted; in this proposal backslash escapes will occur before the dedent. The JEP also mentions considering multi-line string literals as Swift and Rust do them: I mention these for completeness, not to suggest them as alternatives. Thanks, it's actually good to see this being a feature accepted in other languages. Hi @steven.daprano, @gregory.p.smith. I added the first version of my PR for review. One issue with it is that in: def f(): return " foo".dedent() f will have both " foo" and "foo" in its constants even if the first is not used anymore. Removing it requires looping over the code once more while marking the constants seen in a set and I was not sure if this was ok. Perform the optimization at the AST level, not in the peepholer. > One issue with it is that in: > def f(): > return " foo".dedent() > f will have both " foo" and "foo" in its constants even if the first is not used anymore. That seems to be what happens with other folded constants: py> def f(): ... return 99.0 + 0.9 ... py> f.__code__.co_consts (None, 99.0, 0.9, 99.9) so I guess that this is okay for a first draft. One difference is that strings tend to be much larger than floats, so this will waste more memory. We ought to consider removing unused constants at some point. (But not me, sorry, I don't have enough C.) > Removing it requires looping over the code once more while marking > the constants seen in a set and I was not sure if this was ok. That should probably be a new issue. Serhiy's message crossed with mine -- you should probably listen to him over me :-) > Perform the optimization at the AST level, not in the peepholer. Thanks, this makes more sense. > Serhiy's message crossed with mine. And mine crossed with yours, sorry. I will update my PR shortly. Thanks @serhiy.storchaka, it's far easier to do here. I pushed the patch to the attached PR. Is there a reason the other optimisations in the Peephole optimizer are not done in the AST? The optimization that can be done in the AST is done in the AST. While. > While the string method works pretty well, I do not think this is the best way. Regardless of what we do for literals, a dedent() method will help for non-literals, so I think that this feature should go in even if we intend to change the default behaviour in the future: > 3.9. Implement "from __future__ import deindent". > 3.11. Emit a FutureWarning for multiline literals that will be changed by dedending if "from __future__ import deindent" is not specified. > 3.13. Make it the default behavior. And that gives us plenty of time to decide whether or not making it the default, rather than an explicit choice, is the right thing to do. Agreed, I'm in favor of going forward with this .dedent() optimization approach today. If we were to attempt a default indented multi-line str and bytes literal behavior change in the future (a much harder decision to make as it is a breaking change), that is its own issue and probably PEP worthy. I ? > It might be unclear for the following especially if `.dedent()` get > sold as zero-overhead at compile time. Oh, please, please, please PLEASE let's not over-sell this! There is no promise that dedent will be zero-overhead: it is a method, like any other method, which is called at runtime. Some implementations *might* *sometimes* be able to optimize that at compile-time, just as some implementations *might* *sometimes* be able to optimize away long complex arithmetic expressions and do them at compile time. Such constant-folding optimizations can only occur with literals, since arbitrary expressions aren't known at compile-time. F-strings aren't string literals, they are executable code and can run thngs like this: f"{'abc' if random.random() > 0.5 else 'xyz'}" So we don't know how many spaces each line begins with until after the f-string is evaluated: f"""{m:5d} {n:5d}""" Unless we over-sell the keyhole optimization part, there shouldn't be anything more confusing about dedent than this: x, X = 'spam', 'eggs' f"{x}".upper() # returns 'SPAM' not 'eggs' > Could it be made clearer with the peephole optimiser (and tested, I > don't believe it is now), that dedent applies after-formatting ? We should certainly make that clear that Personally, I think we should soft-sell on the compile-time optimization until such time that the Steering Council decides it should be a mandatory language feature. > Alternative modifications/suggestions/notes: > > - I can also see how having dedent applied **before** formatting > with f-string could be useful or less surprising ( a d"" prefix > could do that... just wondering what your actual goal is). I don't see how it will make any difference in the common case. And the idea here is to avoid yet another string prefix. > - Is this a supposed to deprecating textwrap.dedent ? I don't think so, but eventually it might. > Oh, please, please, please PLEASE let's not over-sell this! Sorry didn't wanted to give you a heart attack. The optimisation has been mentioned, and you never know what people get excited on. > Such constant-folding ... Well, in here we might get that, but I kind of want to see how this is taught or explain, what I want to avoid is tutorial or examples saying that `.dedent()` is "as if you hadn't put spaces in front". > I don't think so, but eventually it might. Ok, thanks. Again just being cautious, and I see this is targeted 3.9 so plenty of time. I believe this will be a net improvement on many codebases. Can we dedent docstring too? Is there any string like inspect.cleandoc(s) != inspect.cleandoc(s.dedent())? I think dedenting docstring content by default would be a great thing to do. But that's a separate issue, it isn't quite the same as .dedent() due to the first line. I filed to track that. We should consider dedicated syntax for compile-time dedenting: d"""\ This would be left aligned but this would only have four spaces And this would be left-justified. """ # Am not sure what to do about this last line Another option not using a new letter: A triple-backtick token. def foo(): value = ```this is a long multi line string i don't want indented. ``` A discuss thread was started so I reconnected it with this issue. See I think it would be better to use use backtick quotes for f-strings instead of the f prefix. This would stress the special nature of f-strings (they are not literals, but expressions). But there was strong opposition to using backticks anywhere in Python syntax. If I can say my two cents: 1. I preferred that the default behaviour of multi-line was to dedent. But breaking old code, even if for a little percentage of code, IMHO is never a good idea. Py2->Py3 should have proved it. 2. ``` remembers me too much the Markdown for add a code block, not a text block 3. yes, the new prefix is really useless, because it's significant only for multiline strings. Anyway, if this solution is accepted, I propose `t` for `trim`. Is there a reason folks are supporting a textwrap.dedent-like behavior over the generally cleaner inspect.cleandoc behavior? The main advantage to the latter being that it handles: '''First Second Third ''' just fine (removing the common indentation from Second/Third), and produces identical results with: ''' First Second Third ''' where textwrap.dedent behavior would leave the first string unmodified (because it removes the largest common indentation, and First has no leading indentation), and dedenting the second, but leaving a leading newline in place (where cleandoc removes it), that can only be avoided by using the typically discouraged line continuation character to make it: '''\ First Second Third ''' cleandoc behavior means the choice of whether the text begins and ends on the same line at the triple quote doesn't matter, and most use cases seem like they'd benefit from that flexibility. .cleandoc is _probably_ more of what people want than .dedent? I hadn't bothered to even try to pick between the two yet. Anyway there's something strange in string escaping and `inspect.cleandoc()`: >>> a = """ ... \nciao ... bello ... \ ciao ... """ >>> print(inspect.cleandoc(a)) ciao bello \ ciao >>> print("\ ciao") \ ciao I expected: >>> print(inspect.cleandoc(a)) ciao bello ciao >>> print("\ ciao") ciao Excuse me for the spam, but against make it the default behavior I have a simple consideration: what will expect a person that reads the code, that doesn't know Python? IMHO it expects that the string is *exactly* like it's written. The fact that it will be de-dented it's a bit surprising. For readability and for not breaking old code, I continue to be in favor of a letter before the multi-string. Maybe `d`, for de-dent, it's more appropriate than `t`, since it does not only trim the string. But probably there's a better solution than the letter. The user expects what they read in the documentation of what they learn in other programming languages. If we update the documentation their expectation will change. As for other programming languages, Bash has an option for stripping all leading tab characters from a here document, and in Julia triple-quoted strings are dedented (). Since Julia is a competitor of Python in science applications, I think that significant fraction of Python users expected Python triple-quoted strings be dedented too, especially if they are dedented by help() and other tools. Julia syntax looks well thought out, so I suggest to borrow it. When Python started to emulate the other languages? Who cares about what other languages do? Python uses `raise` instead of `throw`, even if `throw` is much more popular in the most used languages, only because `raise` in English has more sense. And IMHO a newbie that see a multi-string in the code does not read the documentation. It's evident that is a multi-string. And it expects that it acts as in English or any other written language, that is the text is *that* one that (s)he read. On the contrary, if (s)he reads d""" Marco Sulla """ maybe (s)he thinks "this must be something different", and read the docs.
https://bugs.python.org/issue36906
CC-MAIN-2019-47
refinedweb
2,575
62.88
Talk:Religious Right Note: This is taken from a paper User:Researcher wrote about the religious right for a Master's level Poli Sci course. He will come back and edit it more later, but feel free to work on it and fix it up some. I also have a ton of references, also to be added later. Probably after workResearcher 16:02, 25 September 2007 (EDT) - I just copyedited it to be more of an RW joynt; if Researcher prefers we could move it to the essay namespace. I wish he'd left us those references :( Also, I think the article title should be "Religious right", there's no reason to capitalize "right" (and I uncapped it throughout the article). human 20:29, 11 May 2008 (EDT) - I'll try to get those for you soon. (It's on a saved hard drive somewhere.) Researcher 14:42, 13 May 2008 (EDT) - Oh hey, cool, hi. I thought you were on sabbatical or something. human 19:52, 13 May 2008 (EDT) - I've been really freaking busy, and don't really have time to devote to this website right now. (And that looks like it may be permanent, actually...) but I've not forgotten about everyone. I haven't yet found that; if you want to move it to essay until I find the original, with all of the citations, feel free. Researcher 17:17, 25 May 2008 (EDT) Grr, argh[edit] OK, the former roommate who has the hard drive hasn't been very forthcoming, and it has a LOT of my grad school work on it. (Including a lengthy paper on the causes of "covenant marriage" legislation that could also be useful to this site.) I'm still working on getting it. Researcher 18:01, 25 November 2008 (EST) Where is this about? Are Benny XVI and Ian Paisley also not of the religious right? — Unsigned, by: 82.198.250.66 / talk / contribs 16:26, 3 February 2010 (UTC) - This paper was based explicitly on the American Religious Right, as a collection of interest groups. It was part of some research I did while working on my first Master's. Researcher (talk) 16:33, 3 February 2010 (UTC) Not to be confused with the (ir)religious left or with the (ir)religious wrong? 212.85.6.26 (talk) 18:33, 7 June 2011 (UTC) Recent Events[edit] Given Judge Moore's return to the national spotlight with this shameful episode in Alabama, shouldn't this section be updated to reflect it? Jwebb (talk) 12:52, 17 February 2015 (UTC) Ann Coulter and Ted Nugent[edit] Why the heck were they removed from the list? Putin? Really?[edit] Characterizing Vladimir Putin as the Russian equivalent of U.S. Religious Right seems a bit off. For example, Putin has actually spoken against the attempts to outlaw abortions (e.g.). Also, Putin has always been very apprehensive when having been asked about his personal religious views. As far as I know, he has even refused to explicitly state whether he is a member of the Orthodox Church or whether he believes in God (he dodged the question in 2007 TIME interview). Of course, he is certainly a religious conservative (or feigning to be one) but of very different breed than the typical American "Religious Right" political figures who are vocal about their Christian beliefs and invoke Jesus, Bible and Christianity in every sentence and issue. 188.238.77.71 (talk) 23:36, 5 February 2019 (UTC)
https://rationalwiki.org/wiki/Talk:Religious_Right
CC-MAIN-2021-49
refinedweb
585
70.63
Hello all, I am relatively new to programming in general - the last formal object oriented programming class I took was my freshman year of college (my jargon may not be accurate). So please, bear with me. If this question should be asked in a different area (such as the C# forum, please let me know). Basically, the premise is this: in one solution I have two projects, a Windows Form Application and a Web Application. My Windows Form Application will be a simple GUI (it will get more complicated later but I wanted to started more simply to start) with a label prompting the user to input some text, a TextBox for the user to input the text, and a Submit button. Once the Submit button is pressed I want to pass whatever was typed into the TextBox to appear in a TextBox on a given webpage (this webpage will be part of a Web Application that already exists but for now I am just using a local host for debugging and getting concepts down). I have already designed the form for the Windows Form Application and designed the web page (again simple with a label stating "Text Entered from GUI:" and a TextBox). So now I'm stuck. I've tried a couple of different things and tried searching for a similar problems but no such luck. I thought that I could implement a "using" namespace with the name of my Windows Form project (in the aspx.cs page) but when I run, it doesn't recognize the method I use...so I tried putting the method directly in the .aspx page but it doesn't like the namespace I've given (asked if I was missing an assembly reference...which I am not...). I feel like I am making this more difficult than it needs to be and I am not sure where to go from here. If someone needs to look at my code I will post it - I would post it now but it is a bit of a hassle. The computer I am programming on is not allowed to be hooked up to the Internet, nor am I allowed to use devices such as thumb drives, so I will have to type it in by hand. However, I am willing to do this if it means I can get some answers!! Again, I am here to learn and seek advice so any help would be GREATLY appreciated! Also, a speedy response is ideal! Oh! I am using Visual Studio 2012, .NET Framework 4.5 and my Windows Form Application is written in C#. Web applications aren't really designed to be programmatically driven by outside programs. It can be done via the UI but it isn't all that reliable and other alternatives to posting to the UI are preferred. A more preferred way to access the web site is if it exposes any web service or web api interfaces. With this approach, in your windows app, you would write to the webservice (or webapi) method and it would store the data for the web site to access. So, in this approach, you aren't actually writing to the web page per se. In order to do this, the web site has to expose an interface (svc or api) that allows you to write to it. If you are coding the web site, then this isn't really a problem to add to an existing web site. On the other hand, if you are connecting to someone else's website, they are going to have to make an interface available. My Code Guru Articles View Tag Cloud Forum Rules
http://forums.codeguru.com/showthread.php?545971-Make-TxtChanged-fire-on-any-key&goto=nextoldest
CC-MAIN-2016-07
refinedweb
614
69.31
django-dbsettings 0.10.0 Application settings whose values can be updated while a project is up and running. be edited at run-time using the provided editor, and all Python code in your application that uses the setting will receive the updated value. Requirements * Possibly version below 1.2 will work too, but not tested.', ... ) If your Django project utilizes sites framework, all setting would be related to some site. If sites are not present, settings won’t be connected to any site (and sites framework is no longer required since 0.8.1). You can force to do (not) use sites via DBSETTINGS_USE_SITES = True / False configuration variable (put it in project’s settings.py). By default, values stored in database are limited to 255 characters per setting. You can change this limit with DBSETTINGS_VALUE_LENGTH configuration variable. If you change this value after migrations were run, you need to manually alter the dbsettings_setting table schema., FastCGI or WSGI, run multiple processes, which some backends don’t fully support. When using the simple or locmem backends, updates to your settings won’t be reflected immediately in all workers, causing your application to ignore the new changes. No other backends exhibit this behavior, but since simple is the default, make sure to specify a proper backend when moving to a production environment. Alternatively you can disable caching of settings by setting DBSETTINGS_USE_CACHE = False in settings.py. Beware though: every access of any setting will result in database hit.(default='SiteMail'). The widget used for a value can be overriden using the widget keyword. For example: payment_instructions = dbsettings.StringValue( help_text="Printed on every invoice.", default="Payment to Example XYZ\nBank name here\nAccount: 0123456\nSort: 01-02-03", widget=forms.Textarea ) or manage.py migrate: 'site_settings' and 'app just added to the project and the ImageLimits were added earlier and already set via editor. >>> from myproject.myapp import models # EmailOptions are not defined >>> models.email.enabled False >>> models.email.sender >>> models.email.subject 'SiteMail' # Since default was defined #]) Settings can be not only read, but also written. The admin editor is more user-friendly, but in case code need to change something: from myproject.myapp.models import Image def low_disk_space(): Image.limits.maximum_width = Image.limits.maximum_height = 200 Every write is immediately commited to the database and proper cache key is deleted. was set to 5 in the editor, the following calculation would be valid: >>> 5.00 * myapp.taxes.sales_tax 0.25 PositiveIntegerValue Similar to IntegerValue, but limited to positive values and 0. StringValue Presents a standard input, accepting any text string up to 255 (or DBSETTINGS_VALUE_LENGTH). ImageValue (requires PIL or Pillow imaging library to work) Allows to upload image and view its preview. ImageValue has optional upload_to keyword, which specify path (relative to MEDIA_ROOT), where uploaded images will be stored. If keyword is not present, files will be saved directly under MEDIA_ROOT. PasswordValue Presents a standard password input. Retain old setting value if not changed./migrate,.10.0 (25/09/2016) - Added compatibility with Django 1.10 - 0.9.3 (02/06/2016) - Fixed (hopefully for good) problem with ImageValue in Python 3 (thanks rolexCoder) - 0.9.2 (01/05/2016) - Fixed bug when saving non-required settings - Fixed problem with ImageValue in Python 3 (thanks rolexCoder) - 0.9.1 (10/01/2016) - Fixed Sites app being optional (thanks rolexCoder) - 0.9.0 (25/12/2015) - Added compatibility with Django 1.9 (thanks Alonso) - Dropped compatibility with Django 1.4, 1.5, 1.6 - 0.8.2 (17/09/2015) - Added migrations to distro - Add configuration option to change max length of setting values from 255 to whatever - Add configuration option to disable caching (thanks nwaxiomatic) - Fixed PercentValue rendering (thanks last-partizan) - 0.8.1 (21/06/2015) - Made django.contrib.sites framework dependency optional - Added migration for app - 0.8.0 (16/04/2015) - Switched to using django.utils.six instead of standalone six. - Added compatibility with Django 1.8 - Dropped compatibility with Django 1.3 - 0.7.4 (24/03/2015) - Added default values for fields. - Fixed Python 3.3 compatibility - Added creation of folders with ImageValue - 0.7.3, 0.7.2 - pypi problems - 0.7.1 (11/03/2015) - Fixed pypi distribution. - 0.7 (06/07/2014) - Added PasswordValue - Added compatibility with Django 1.6 and 1.7. - 0.6 (16/09/2013) - Added compatibility with Django 1.5 and python3, dropped support for Django 1.2. - Fixed permissions: added permission for editing non-model (module-level) settings - Make PIL/Pillow not required in setup.py - - Author: Jacek Tomaszewski - License: BSD - Categories - Package Index Owner: zlorf - DOAP record: django-dbsettings-0.10.0.xml
https://pypi.python.org/pypi/django-dbsettings
CC-MAIN-2016-50
refinedweb
776
51.75
In part 3 of my Python 2.7 Tutorial, I explain how to use the Dictionary, Print method and how to work with String methods. If you haven’t seen part 1 or 2 definitely look at them first or you’ll be very confused Python 2.7 Tutorial Part 1 and Python 2.7 Tutorial Part 2. All of the code I use in these tutorials follow the video and can be used however you’d like. If you have any questions or comments leave them below. Here is the Code for this Python Tutorial #! /usr/bin/python import math # Formatting output with the print function strName = ‘Bob’ floatAge = 35.4 charSex = ‘M’ intKids = 2 boolMarried = True print ‘%s is %f years old’ % (strName, floatAge) print ‘Sex: %c’ % (charSex) print ‘He has %d kids and said it\’s %s he is married’ % (intKids,boolMarried) print ‘%s is %.1f years old’ % (strName, floatAge) # Formatting Output Further print ‘%.15f’ %(math.pi) print ‘%20f’ %(math.pi) print ‘%20.15f’ %(math.pi) print ‘%-25.15f is the value of pi’ %(math.pi) precisionPi = int(raw_input(“How precise should pi be: “)) print ‘PI = %.*f’ % (precisionPi, math.pi) # A Bunch of String Methods bigString = ‘Here is a long string that I will be messing with’ print bigString[1:20:2] print bigString.find(‘string’) print bigString.find(‘massive’) print bigString.count(‘e’) print bigString.count(‘e’, 4) print bigString.count(‘e’, 0, 20) copyStr = tuple(bigString) print copyStr print ”.join(copyStr) print ‘, ‘.join(copyStr) print bigString.lower() print bigString.upper() print bigString.replace(‘long’,’small’) print bigString.split(‘ ‘) randomWhite = ‘ This string has random white space ‘ print randomWhite.strip()
http://www.newthinktank.com/2010/10/python-2-7-tutorial-pt-3/
CC-MAIN-2019-43
refinedweb
273
80.07
A Django settings file contains all the configuration of your Django installation. This document explains how settings work and which settings are available... django-adminutility. A Django settings file doesn’t have to define any settings if it doesn’t need to. Each setting has a sensible default value. These defaults live in the module. There’s an easy way to view which of your settings deviate from the default settings. The command python manage.py diffsettings displays differences between the current settings file and Django’s default settings. For more, see the diffsettings documentation.. You shouldn’t alter settings in your applications at runtime. For example, don’t do this in a view: from django.conf import settings settings.DEBUG = True # Don't do this! The only place you should assign to settings is in a settings. For a full list of available settings, see the settings reference.. DJANGO_SETTINGS_MODULE¶: Example: from django.conf import settings settings.configure(DEBUG=True) documentation of TIME_ZONE for why this would normally occur). It’s assumed that you’re already in full control of your environment in these cases.. configure()or DJANGO_SETTINGS_MODULE Contains the complete list of core and contrib app settings.
https://django.readthedocs.io/en/2.2.x/topics/settings.html
CC-MAIN-2021-49
refinedweb
198
53.88
Feature #13303 String#any? as !String#empty? Updated by matz (Yukihiro Matsumoto) about 3 years ago - Status changed from Assigned to Feedback Use-case? Matz. Updated by herwinw (Herwin Quarantainenet) about 3 years ago and understand there's Array#any?. This is a misconception, Array#any? does not check if the array is empty, but if there is a true-ish value in the array: irb(main):001:0> [false, nil].any? => false This is documented by Enumerable#any?: "If the block is not given, Ruby adds an implicit block of { |obj| obj } that will cause any? to return true if at least one of the collection members is not false or nil." Beside that, I don't think String#any? is a sensible method name to check if a string is non-empty. Updated by shevegen (Robert A. Heiler) about 3 years ago Actually the name .nonempty? is easier to understand than .any? in this context, or non-empty strings. I think the only problem is that "nonempty" reads very ... strangely. I can not come up with a good name either though. .non_empty? May seem obvious but I am not sure either there since it is quite long. I think that nonempty? or non_empty? is better than any? in this context though. Ignoring the ruby parser, I guess this here would be one of the shortest, somewhat natural way to query and ask on an object: object, are you not empty object not empty? I guess the most natural ruby way would still be object.not_empty? object.non_empty? Or perhaps we can ask any container/object if it has at least one entry. :\ object.at_the_least_one_entry? The last one is a bit awful though - now .non_empty? or .non_empty? or .not_empty? would look nicer. :))) Updated by naruse (Yui NARUSE) about 3 years ago matz (Yukihiro Matsumoto) wrote: Use-case? For example if h and val = h["value"] and val != "" Updated by duerst (Martin Dürst) about 3 years ago any? would definitely be the wrong name, because for Arrays, [].any? is always true. Of the names proposed so far, I think not_empty? looks best. An alternative may be unempty?, but that may sound decidedly unenglish :-). Another may be any_chars?, which would be colloquially correct, but still has the problem that it works differently from a simple any?. Updated by rosenfeld (Rodrigo Rosenfeld Rosas) about 3 years ago Maybe String#filled? or String#filled_in? ? Updated by mame (Yusuke Endoh) about 3 years ago duerst (Martin Dürst) wrote: [].any? is always true. No, it is always false. I agree that String#any? is a bad name for the behavior, anyway. I think that what Naruse-san really wants is, still, Object#present?. if h and val = h["value"] and val != "" if h and h["value"].present? Updated by stomar (Marcus Stollsteimer) about 3 years ago mame (Yusuke Endoh) wrote: if h and h["value"].present? I think foo.present? semantically should be the same as !foo.nil? ("is the object present?" = "does the object exist?"), which probably wouldn't make much sense as a method on objects other than booleans. Also: String#filled?: is "x" a "full" string? ... String#any_chars?: sounds like there also might be e.g. String#any_bytes? String#not_empty? or String#non_empty? sounds best so far, IMHO (with "not_empty?" maybe easier to remember esp. for non-native speakers, "!" = "not"). Updated by MSP-Greg (Greg L) about 3 years ago My vote for is for not needed, with second choice of not_empty?. 1) neg - I don't believe it's always necessary to have pairs of logical attributes/properties, as it certainly clutters up the namespace. 2) pos - Ruby already supports if / unless (we'll consider that not common) 3) pos - It makes for somewhat clearer code when a multi-criteria logical statement does not require the ! operator. Conversely, all coders should immediately consider a ! a not... So, I don't know if it's really needed... Updated by naruse (Yui NARUSE) almost 3 years ago I want to use this with &. Therefore String#empty? is not suitable. It must returns false if it is empty. Note that String#present? is also no good because ActiveSupport's present? returns false if its all content are space. Updated by shyouhei (Shyouhei Urabe) almost 3 years ago possible name of this method: - #present? is NG because that conflicts with ActiveSupport (AS's #present? have different semantics than what is discussed here). - #empty? is NG because the OP wants to use it in conjunction with &. - #nonempty? or #non_empty? - #notempty? or #not_empty? - There has never been a core method that starts with "not-" Any other ideas? Updated by MSP-Greg (Greg L) almost 3 years ago shyouhei (Shyouhei Urabe) wrote: Any other ideas? Assuming we want to stay away from prefixed or concatenated names, I might suggest - #content? Updated by MSP-Greg (Greg L) almost 3 years ago After some more thought (and the desire for a method name that could be used with other objects), I think #each? might work for many objects, including those that inherit/include Enumerable. Simply defined, each? returns true if an #each block will be performed at least once. Nothing about the values, just their existence. It's also rather short... Updated by sawa (Tsuyoshi Sawada) about 1 year ago I came up with the method name: solid? Also available in: Atom PDF
https://bugs.ruby-lang.org/issues/13303
CC-MAIN-2020-16
refinedweb
893
77.94
Important: Please read the Qt Code of Conduct - Signal/Slot newbie Hi, I just made my first application in QT (with QT5, QT Creator and QT Quick) and I've got the exe running and everything, but being a newbie and not used to neither OOP nor QML I feel a bit insecure. The program has worked as expected the last 50 times but at some point earlier on, it gave some weird unexpected results. It would feel better if I felt sure I knew what I was doing, and/or had a way of testing it in more detail. My code: #ifndef MYFILE_ #define MYFILE_ #include <QObject> class MyHandling : public QObject { Q_OBJECT public slots: QString handleMyFile(bool Selection1, bool Selection2, QString inputFileName); signals: void valueChanged(void); }; #endif //----------- //main.qml: import QtQuick 2.1 import QtQuick.Controls 1.1 import QtQuick.Layouts 1.1 import QtQuick.Dialogs 1.0 Rectangle { x: 0 width: 500 height: 370 color: "#d7dee0" opacity: 1 Item { id: item // width: 100; height: 100 signal valueChanged() } Button { id: myButton x: 402 y: 236 width: 76 height: 57 text: qsTr("MyButton") z: 5 onClicked: { textError.text = MyHdlObject.handleMyFile(Selection1.checked, Selection2.checked, inputFileName.text, outputFileName.text) item.valueChanged() } } /* Some code */ } //--------------- //main.cpp: #include <QtGui/QGuiApplication> #include "qtquick2applicationviewer.h" #include "MyHandling.h" #include <QFile> #include <QQmlContext> //setContextProperty QString MyHandling::handleMyFile(bool Selection1, bool Selection2, QString inputFileName, QString outputFileName) { /* Some code */ } int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QObject *item; QtQuick2ApplicationViewer viewer; viewer.rootContext()->setContextProperty("MyHdlObject", new MyHandling()); viewer.setMainQmlFile(QStringLiteral("qml/MyApp/main.qml")); viewer.showExpanded(); item = (QObject *) viewer.rootObject(); //Point A MyHandling sh1; QObject::connect(item, SIGNAL(valueChanged()), &sh1, SLOT(handleMyFile())); //Point B return app.exec(); } @ I have one very specific question: If i delete the text between "Point A" and "Point B" it still works just as well as with it. But I thought that part was vital for the signal/slot stuff. I deleted it as a test expecting it to fail then. Or does it perhaps just work less reliably with that part deleted? The only thing that happens is that I get a warning that "item" isn't used. Another question is: Is there a way you can recommend for testing the signal transfers between QML and C++, to make sure it works reliably? Obviously my idea to delete the whole signal/slot part expecting communication to die, is not a good test at all. And a general question is if my communication between C++ and QML seems to be doing what it should? I read several posts on similar subjects, especially those with example code, but for some reason none of those examples work (no matter if posted on qt-project, stackoverflow or Nokias site), I'm guessing it is due to changes in QT parts or something. You are handling the file in QML, explicitly: @ textError.text = MyHdlObject.handleMyFile(Selection1.checked, Selection2.checked, inputFileName.text, outputFileName.text) @ That is why it works. It uses the object you create in your main C++ file: @ viewer.rootContext()->setContextProperty("MyHdlObject", new MyHandling()); @ The other, created on a stack, is not used by the engine at all: you create it later and don't assign it to the root context. Since you are a newbie, I'll also give you some advice: @ QString handleMyFile(bool Selection1, bool Selection2, const QString &inputFileName); signals: void valueChanged() const; @ Pass all Qt classes (especially containers, QString, QByteArray, etc.) as const references: this way it's faster and less memory-consuming (as Implicit Sharing kicks in). Always define singals as const: they always are const, and it allows some further optimisations when you declare them as such. Thanks. Regarding stack etc I understand what you are saying, I suppose, but I wouldn't know what to change exactly. Haven't come across any description of stack usage when reading about QT/QML/C++ but I'm guessing you're talking about function call parameters since these AFAIK are on the stack and signals & slots are actually functions. But specific help on what to change would be helpful. I read various examples and tutorials etc. "This": doesn't say much about the QML syntax. "This": (which has errors if I try to build & run it) doesn't even use ::connect. It uses e g Q_INVOKABLE (which I would have expected I might have use for) which the other example doesn't. Seems to be some options here. Thanks for the advice on speed impact. I have seen others use const for parameters before, didn't know why, I'm guessing it tells the compiler that they are pointers whose value won't change? I suppose that means I could/should add const also for the return value? I haven't seen anyone else using const for signals though. I don't want to flood you by details. The interaction between C++, meta object system and QML is deep and complicated, especially for a newcomer. I suggest you to take it easy and try to develop some training projects step by step, to gradually get the idea about the whole system. [quote]Regarding stack etc I understand what you are saying, I suppose, but I wouldn’t know what to change exactly[/quote] Remove those lines (86-88) completely, you do not need them. What you do there is create a new object that is completely separate from the one you create in line 81. They don't know about each other, and neither does the QML engine. Don't focus on the "stack" word: the situation would have been exactly the same if you created it as pointer (with "new") there. [quote]I read various examples and tutorials etc. [...] doesn’t even use ::connect[/quote] Meta object system is really powerful, QML uses it everywhere. Here is the difference: - when you run, in your QML/JS code, this expression: MyHdlObject.handleMyFile(...) you are actually invoking a function (handleMyFile) from object you have added as a root context property (MyHdlObject, added in line 81 of C++ code). To do that, this method has to be marked as Q_INVOKABLE or be a slot (all slots are invokable through meta object system) - when you connect a signal to a slot (does not matter where: C++, JavaScript, QML) you do not invoke any function yourself. Meta object system will invoke the slot after your application emits the signal: and only then [quote]I haven’t seen anyone else using const for signals though.[/quote] I'm going through the documentation now and it seems that signals are ot being marked as const there. I believe this to be a bug. If you don't mark a signal as const, the compiler will not allow you to emit it in a const function. And in general, it is good practice to mark all functions that can be const as const: this keyword - as you correctly assume - tells the compiler "this stuff should not change the state of the current object". This way it achieves 2 goals: on one hand the compiler will throw an error if you accidentally try to change the state inside a const function, and on the other - it allows the compiler to optimize the code more aggressively (at least in theory). Thanks for all the input. I suppose you are saying that at this stage I might as well delete the signal/slot part. Actually I don't mind doing that as long as it still works reliably.. It seems to work reliably 99 times out of 100 but sometimes strange things happen. If you say I haven't caused this myself by bad coding then I would suspect the Qt environment, since I usually run it under Qt Creator (ctrl-R) and I've seen some quirks in Qt Creator both during debugging,linking and running which usually disappears after some things like restarting, cleaning, rebuildng etc. (BTW since a week I can't open QML files graphically in Qt Creator an it's not just my project but also e g the examples so I think I'll have to reinstall it again, so it doesn't seem to be bug free). I have two goals with this: One is to get it to work (it is not just for test, I intend to use this code for a fun shareware application), the other is to try Qt for the first time. I suppose that if I want to do more projects in Qt which use the Quick part, I should read up on the basics then. [quote author="DavidGGG" date="1393168856". [/quote] Both ways are valid, fully supported and "official", don't worry :)
https://forum.qt.io/topic/38066/signal-slot-newbie
CC-MAIN-2022-05
refinedweb
1,446
61.06
Walkthrough: Creating a Wizard In Visual Studio 2013, add-ins are deprecated. We recommend that you upgrade your add-ins to VSPackage extensions. For more information about how to upgrade, see How to: Convert an Add-in to a VSPackage. kinds kind how to create wizards targeted to Visual C++, see Designing a Wizard and Creating a Custom Wizard. .gif?cs-save-lang=1&cs-lang=vb) This picture shows a panel of the Add-In Wizard, a new-project type of wizard that box. The following demonstrates how to create a basic wizard and optionally give it a custom icon. To create a basic wizard in Visual Basic and Visual C# Run Visual Studio as an Administrator. Registering the wizard requires updating the registry, so it needs this privilege. Create a new Class Library project named MyNewWizard. Add references to EnvDTE and EnvDTE80 to the project. To do this, right-click the project and click Add, Reference. On the .NET tab of the Reference dialog box, and System.Runtime.InteropServices. using System.Runtime.InteropServices; [ComVisible(true)] [Guid("20184B81-7C38-4E02-A1E3-8D564EEC2D25"), ProgId("MyNewWizard.Class1")]; using System.Runtime.InteropServices;. Right-click your project in Solution Explorer and click Properties to open the Project Properties page, click the Build tab, and then check the Register for COM interop box at the bottom of the page. In the AssemblyInfo.cs file, find the ComVisible attribute and set it to true. Build the project to create the class library .dll by clicking Build Solution on the Build menu. Create a .vsz text file for the wizard named MyNewWizard.vsz. To do this, make a copy of an existing .vsz file, such as any of those located at <Visual Studio Install Directory>\VC#\CSharpProjectItems\Windows Forms, and rename it "MyNewWizard.vsz". A .vsz file is a text file that enables Visual Studio to recognize the wizard and display it in the New Project or Add New Item dialog box. The Wizard parameter should be set to the progID (Project.Classname) of the project or the GUID. For more information, see Configuring .Vsz Files to Start Wizards. Replace the contents of MyNewWizard.vsz with the following: Save the new .vsz file in the directory where you want the wizard to appear. For this example, we want the wizard to appear in the Add New Item dialog box for Visual Basic projects, so save the .vsz file in the following directory: <Visual Studio Install Directory>\VB\VBProjectItems. Exit Visual Studio and then restart it. This forces Visual Studio to read the new .vsz file. Create a new Visual Basic project, such as a Windows Application project. Right-click the project, point to Add,.
http://msdn.microsoft.com/en-us/library/7k3w6w59.aspx?cs-save-lang=1&cs-lang=vb
CC-MAIN-2014-52
refinedweb
448
59.9
Tried to get it to run on my own and then typed in Zed’s and still getting the same error Traceback (most recent call last): File “ex43.py”, line 258, in a_game.play() File “ex43.py”, line 24, in play next_scene_name = current_scene.enter() AttributeError: ‘NoneType’ object has no attribute ‘enter’ from sys import exit from random import randint from textwrap import dedent class Scene(object): def enter(self): print("This scene is not yet configured.") print("Subclass it. You kinda suck at this." "\"Mocking Stiffled Laughter\"" "Such a luser." "You're worse than your Dad's jokes." "I have a small kitten tha's better at this." "Your Mom would be proud....if she were smarter." ] def enter(self): print(Death.quips[randint(0, len(self.quips)-1)]) exit(1) class CentralCorridor(Scene): def enter(self): print(dedent(""" The Gothons of the Planet Percal #25 have invaded your shup and destroyed your entire crew. You are the lst surviving member and your last mission is to get the nuetron destruct bomb from the Weapons Armory, put it in the bridge, and blow up the ship(""" Quick on the draw you yank out your blaster and fire it at the Gothon. His clown costume is flowing and moving around his body, which throws off your aim. Your laser hits his costume but misses him entirely. This completely ruins his brand new costume his mother bought him, which makes him fly into an insane rage and blast you repeatedly in the face until you are dead. Then he eats you. """)) return 'death' elif action == "dodge!" or "dodge" or "acrobatics": print(dedent(""". """)) return 'death' elif action == "tell a joke" or "preform(comedy)" or "act stupid": print(dedent(""". """)) return 'laser_weapon_armory' else: print("DOES NOT COMPUTE!") return 'central_corridor' class LaserWeaponArmory(Scene): def enter(self): print(dedent(""" = f"{randint(1,9)}{randint(1,9)}{randint(1,9)}" guess = input("[keypad]> ") guesses = 0 while guess != code and guesses < 10: print("BZZZZZEDDD!") guesses += 1 guess = input("keypad> ") if guess == code: print(dedent(""" The container clicks open and the seal breaks, letting gas out. You grab the neutron bomb and run as fast as you can to the bridge where you must place it in the right spot. """)) return 'the_bridge' else: print(dedent(""" The lock buzzes one last time and then you hear a sickening melting sound as the mechanism is fused together. You decide to sit there, and finally the Gothons blow up the ship from their ship and you die. """)) return 'death' class TheBridge(Scene): def enter(self): print(dedent(""" = input("> ") if action == "throw the bomb": print(dedent(""" In a panic you throw the bomb at the group of Gothons and make a leap for the door. Right as you drop it a Gothon shoots you right in the back killing you. As you die you see another Gothon frantically try to disarm the bomb. You die knowing they will probably blow up when it goes off. """)) return 'death' elif action == "slowly place the bomb": print(dedent(""". """)) return 'escape_pod' else: print("DOES NOT COMPUTE!") return 'the_bridge' class EscapePod(Scene): def enter(self): print(ded = input("[pod #]> ") if int(guess) !=good_pod: print(dedent(""" You jump into pod {guess} and hit the eject button. The pod escapes out into the void of space, then implodes as the hull ruptures, crushing your body into jam jelly. """)) return 'death' else: print(dedent(""" You jump into pod {guess}(Scene): def enter(self): print("You won!()
https://forum.learncodethehardway.com/t/cant-get-ex43-py-to-run/3193
CC-MAIN-2022-40
refinedweb
574
74.69
@org.junit.Test public void should_$name$() { $END$ } Make sure to check the Shorted FQ names box when creating this template. When you type "should" (the abbreviation), this will add the necessary import org.junit.Test; statement at the top of the file, and this code: @Test public void should_() { } It is thanks to the Shorten FQ names option that @org.junit.Test is reduced to simply @Test. The $name$ variable is irrelevant, it could be named something else. The purpose of that variable is that when the template is inserted in the class, the cursor will be placed in the position of $name$, asking you to enter something. After you entered a value for $name$ (effectively the name of the test method), the cursor will finally jump to $END$, a built-in variable, so that you can carry on and implement the test case.
https://riptutorial.com/intellij-idea/example/9047/add-a-test-method-easily
CC-MAIN-2021-49
refinedweb
145
68.5
Setting Up the Data Profiling Task Before you can review a profile of the source data, the first step is to set up and run the Data Profiling task. You create this task inside an Integration Services package. To configure the Data Profiling task, you use the Data Profiling Task Editor. This editor enables you to select where to output the profiles, and which profiles to compute. After you set up the task, you run the package to compute the data profiles. The Data Profiling task only configures the profiles and creates the output file that contains the computed profiles. To review this output file, you must use the Data Profile Viewer, a stand-alone viewer program. Because you must view the output separately, you might use the Data Profiling task in a package that contains no other tasks. However, you do not have to use the Data Profiling task as the only task in a package. If you want to perform data profiling in the workflow or data flow of a more complex package, you have the following options: To implement conditional logic that is based on the task's output file, in the control flow of the package, put a Script task after the Data Profiling task. You can then use this Script task to query the output file. To profile data in the data flow after the data has been loaded and transformed, you have to save the changed data temporarily to a SQL Server table. Then, you can profile the saved data. For more information, see Using the Data Profiling Task in Package Workflow. After the Data Profiling task is in a package, you must set up the output for the profiles that the task will compute. To set up the output for the profiles, you use the General page of the Data Profiling Task Editor. In addition to specifying the destination for the output, the General page also offers you the ability to perform a quick profile of the data. When you select Quick Profile, the Data Profiling task profiles a table or view by using some or all the default profiles with their default settings. For more information, see Data Profiling Task Editor (General Page) and Single Table Quick Profile Form (Data Profiling Task). After you have set up the output file, you have to select which data profiles to compute. The Data Profiling Task can compute eight different data profiles. Five of these profiles analyze individual columns, and the remaining three analyze multiple columns or relationships between columns and tables. In a single Data Profiling task, you can compute multiple profiles for multiple columns or combinations of columns in multiple tables or views. The following table describes the reports that each of these profiles computes and the data types for which the profile is valid. To select which profiles to compute, you use the Profile Requests page of the Data Profiling Task Editor. For more information, see Data Profiling Task Editor (Profile Requests Page). On the Profile Request page, you also specify the data source and configure the data profiles. When you configure the task, think about the following information: To simplify configuration and make it easier to discover characteristics of unfamiliar data, you can use the wildcard, (*), in place of an individual column name. If you use this wildcard, the task will profile every column that has an appropriate data type, which in turn can slow down processing. When the selected table or view is empty, the Data Profiling task does not compute any profiles. When all the values in the selected column are null, the Data Profiling task computes only the Column Null Ratio Profile. It does not compute the Column Length Distribution Profile, Column Pattern Profile, Column Statistics Profile, or Column Value Distribution Profile for the empty column. Each of the available data profiles has its own configuration options. For more information about those options,) After you have set up the Data Profiling task, you can run the task. The task then computes the data profiles and outputs this information in XML format to a file or a package variable. The structure of this XML follows the DataProfile.xsd schema. You can open the schema in Microsoft Visual Studio or another schema editor, in an XML editor, or in a text editor such as Notepad. This schema for data quality information could be useful for the following purposes: To exchange data quality information within and across organizations. To build custom tools that work with data quality information. The target namespace is identified in the schema as.
http://technet.microsoft.com/en-us/library/bb895322(v=sql.105).aspx
CC-MAIN-2014-15
refinedweb
766
52.09
Hello, So I make an instance of a display object defined in an external .swf that has a TextField. I set that TextField to a new format using setTextFormat(format) and then defaultTextFormat = format. When I set the TextField's htmlText property, the defaultTextFormat is suddenly reset to what it was originally. So something like: var view:MovieClip = new externalDefinition(); var label:TextField = view.label; trace(label.defaultTextFormat.fontName) // Arial var format:TextFormat = label.getTextFormat(); format.fontName = "Century Gothic"; label.setTextFormat(format); label.defaultTextFormat = format; trace(label.defaultTextFormat.fontName) // Century Gothic trace(label.htmlText) // <TEXTFORMAT LEADING="-1"><P ALIGN="LEFT"><FONT FACE="Century Gothic" SIZE="18" COLOR="#271F60" LETTERSPACING="0" KERNING="1">label</FONT></P></TEXTFORMAT> label.htmlText = "<b>Hello!</b>" trace(label.defaultTextFormat.fontName) // Arial trace(label.htmlText); // <TEXTFORMAT LEADING="-1"><P ALIGN="LEFT"><FONT FACE="Arial" SIZE="18" COLOR="#271F60" LETTERSPACING="0" KERNING="0"><B>Hello!</B></FONT></P></TEXTFORMAT> So why does it do this? I understand why setting htmlText might reset the formatting to the default formatting but why does it change defaultTextFormat? Why doesn't it use the defaultTextFormat formatting I changed? Why does it use the original formatting the text field had when it was defined in asset library? How can I tell flash to use my formatting when I change htmlText? Where does it keep the original information stored and how does it revert back to it? Thanks, Erik It does seem to revert to the prior default when setting htmlText - I quickly duplicate this problem. However, it seems to revert to the font the TextField was set to in the .FLA. Is there any reason you are trying to change this at runtime? Maybe you can just switch the font in the external .swf file since this does seem to be a Flash Player bug? Alternatively - just update the TextFormat whenever you set the htmlText property (that's a pain, I know - but just make a function to update the text and it won't be that bad) With that code you should get a bunch of errors. Neither TextFormat nor DefaultTextFormat has a Property fontName only Font has a property fontName. Hello, I quickly scetched up an example. Yes, I mean font property. Sorry. I didn't compile the example, I am using it to demonstrate the problem I am having (partly to make it clear, partly because I was developing on a different computer and could not copy/paste). It seems that Nabren has confirmed the issue however. And no, I cannot change the font in the .fla, I need to set it at runtime. And yes, I know I can change the font back afterwards, but that is a terrible solution. It is a large framework I am working on and affects many assets and it would be terrible to require anyone who uses the framework to do this themselves. If there is no other way I might have to some kind of scheme for doing this automatically, but I would like to avoid this. I want to know why it reverts the TextField property and if there is any way that I can prevent it from doing so in the first place. Where is the original font even stored in the TextField? How does it even know what the original font is? If it is somehow possible to change the original data at runtime then that would be very good. One more thing, I cannot use StyleSheets for these textfields easily. Maybe if there is no other solution I could try to refactor things and get this to work but right now it won't. So my question is specifically about setting the htmlText property in conjunction with defaultTextFormat. Thanks According to the API this behaviour is -sad for you, I know- intended, thats at least what I read from this warning in the documentation: Use the TextField.defaultTextFormat property to apply formatting BEFORE you add text to the TextField, and the setTextFormat() method to add formatting AFTER you add text to the TextField. Maybe the adding/changing of text triggers the reset and the loosing of your defaultTextFormat. Maybe somehow you can empty the Textfield, store its content in a var, set the defaultTextFormat, set it to htmlText, and when you`re done fill the htmlText with your var? I've read that and I am pretty sure that is not what is meant in the documentation. They mean, if you change defaultTextFormat, then any new text added after it is set uses the defaultTextFormat, however text already set does not use it. If you use setTextFormat, current text is set to that new format, but any text added later still uses defaultTextFormat. Basically setTextFormat is a one time thing, it applies to text that is currently in the TextField, and defaultTextFormat is, as the name implies, the default text formatting for any new text added. That is what that warning is saying, and yes, that is intended behavior. But that is not the problem for me. I am appliyng the defaultTextFormat before I am changing the text, not after I am changing the text. However defaultTextFormat is being reset on the condition a) htmlText is used and b) the TextField came from a symbol in Flash Professional layout. I think this is a bug and unrelated to that warning. I am always weary of calling things a bug in Flash but that appears to be what this is. :/ Thanks I tested this and can`t reproduce your problem: import flash.text.TextField; import flash.text.TextFormat; var tf:TextField = new TextField(); addChild(tf); //These two are Times New Roman (The system default) tf.text = "HELLO WORLD"; tf.htmlText = "<b>HELLO WORLD</b>"; //All the following stay Arial, it never reverts back to Times New Roman var arial:TextFormat = new TextFormat("Arial"); tf.defaultTextFormat = arial; tf.text = "HELLO WORLD"; tf.htmlText = "<b>HELLO WORLD</b>" //According to you at this point it should reset to Times New Roman, but it never does tf.setTextFormat(tf.defaultTextFormat); What should I change to see the "wrong" defaultTextFormat resetting? It seems the TextField must be created in the timeline - not ActionScript - for this bug to happen. It happens when you are using a TextField that is part of an exported library symbol from Flash Professional. If you want to reproduce the problem, you must create a new FLA file in Flash Professional. Make a library symbol. Add a TextField inside that library symbol. Give the text field an instance name like 'label', and some text. I am using _sans as the font face. Export the library symbol for actionscript in the symbol properties, give it a class name like "LabelExample". In the file's Publish Settings, set it to publish a .swc file. Publish it. Now include the .swc file in a new project. You should be able to make an instance of LabelExample. Make a new instance, like: var clip:MovieClip = new LabelExample(); var textField:TextField = clip.label; Now apply a new defaultTextField to this text field. It will work as long as you only change the text property. Then try to change the htmlText property. Unlike a normal new instance of TextField, which will continue to apply your defaultTextFormat formatting to the text, even when htmlText is set, it will reset your defaultTextFormat to whatever it was originally when the symbol was published, and not use the defaultTextFormat you set. I don't have any idea why it would do this, it is inconsistent with how a TextField normally behaves and by all indication is supposed to behave. I believe this is a bug in the Flash framework. :/ Thanks
http://forums.adobe.com/thread/1152689
CC-MAIN-2014-10
refinedweb
1,281
65.42
IMPORTANT Generic methods with generic params cannot be used in Source XML as in-rule methods or rule actions. Use plain .Net class(es) if your source object declares generic methods. The source object classes topic demonstrates how easy it is to use any existing or newly declared public .NET class as a source object for your business rules, but sometimes you need finer control over your source objects. This is where Source XML plays a major role. As soon as Rule Editor receives the type of the source object, it reflects and validates it. The result is an XML document known as Source XML. Rule Editor uses that document to hold information about your source object. You can create such a document manually and pass it to Rule Editor as its source object. There are several reasons why you would want to do this: You can create Source XML in one of two ways: If you already have a .NET class that you'd like to use as a template for your Source XML, then simply register Rule Editor on a test web page, set the SourceType property of the RuleEditor class to the type of your template class as shown here, run that page in the debugger, and extract the Source XML into a string variable by calling RuleEditor's GetSourceXml() method. Edit that XML document as needed, validate the result against its schema, and save it in your file system or database. Then reuse it with Rule Editor as shown below. // Extract the XML string from the sourceXml variable and edit it... string sourceXml = ruleEditor.GetSourceXml(); // ... then store the resulting XML as a file... YourStorage.SaveSourceXmlAs("C:\MySourceXml.config", sourceXml); // ... or as XML type in database YourStorage.SaveSourceXmlInDatabase(sourceXml); Another way to generate Source XML is to create it manually from scratch against its schema IMPORTANT! As of version 3.0, Rule Editor employs schema versioning for rules and source objects by specifying different namespace URLs for different versions. You can load an existing Source XML document into Rule Editor as its source object by setting the value of either the RuleEditor.SourceXmlFile or RuleEditor.SourceXml property. (See the topic on RuleEditor class for details.) string sourceXmlString = YourStorage.GetSourceXmlSomehow(); System.Xml.XmlDocument source = new XmlDocument(); source.Load(sourceXmlString); CodeEffects.Rule.Web.RuleEditor editor = new RuleEditor("divRuleEditor") { SourceXml = source }; Obviously, different source objects use different Source XML documents. In multilingual applications, the use of Source XML is the only way to set different display names for rule fields, in-rule methods and actions based on the user's culture or preference.
https://codeeffects.com/Doc/Business-Rule-Source-Object-Xml
CC-MAIN-2021-31
refinedweb
433
64.61
Store.Open method [The Open method is available for use in the operating systems specified in the Requirements section. Instead, use the X509Store Class in the System.Security.Cryptography.X509Certificates namespace.] The Open method opens a specified certificate store. By default, the CAPICOM_CURRENT_USER_STORE location and CAPICOM_MY_STORE store are opened as read-only. Syntax Store.Open( _ [ ByVal StoreLocation ], _ [ ByVal StoreName ], _ [ ByVal OpenMode ] _ ) Parameters StoreLocation [in, optional] A value of the CAPICOM_STORE_LOCATION enumeration that indicates the location of the store to be opened. The default value is CAPICOM_CURRENT_USER_STORE. This parameter can be one of the following values. StoreName [in, optional] A string that contains the name of the system certificate store to be opened. The default value is CAPICOM_MY_STORE. If the store is opened from a web script, the backslash (\) character is not allowed in the name. In addition to stores defined by the system, user-defined stores can be opened. This parameter can be a user-defined store or one of the following system certificate stores. OpenMode [in, optional] A value of the CAPICOM_STORE_OPEN_MODE enumeration that indicates the open mode of the store. The default value is CAPICOM_STORE_OPEN_READ_ONLY. If the store is opened from a web script, this value is forced to CAPICOM_STORE_OPEN_EXISTING_ONLY. This parameter can be one of the following values. The following flags can be combined with the values in the previous table by using a logical-OR operation. Stores in some locations can be opened only in read-only mode. These include all stores in CAPICOM_LOCAL_MACHINE_STORE for which the user does not have write permissions. Attempts to open a store as a read/write store without proper access and permissions will result in the failure of the Open method. Active Directory stores can be opened as a read/write store without failure of the Open method, but changes to the store will not be persisted. Return value This method does not return a value. Remarks If this method is called on a SmartCard store, additional SmartCard user interfaces may be invoked. Important When this method is called from a web script, the script needs to access digital certificates on the local computer. If you allow the script to access your digital certificates, the website from which the script is run will also gain access to any personal information stored in the certificates. The first time this method is called from a particular domain, a dialog box is generated in which the user must indicate whether access to the certificates should be allowed. Stores opened from a web script automatically force the CAPICOM_STORE_OPEN_EXISTING_ONLY flag. If StoreLocation is CAPICOM_SMART_CARD_USER_STORE, StoreName is ignored. In this case, CAPICOM reads all certificates from all available readers that contain a smart card. Requirements See also
https://docs.microsoft.com/en-us/windows/win32/seccrypto/store-open
CC-MAIN-2019-35
refinedweb
455
56.45
An instance of the Response class represents the data to be sent in response to a web request. Response is provided by the google.appengine.ext.webapp module. - Introduction - Response() - Class methods: - Instance variables: - Instance methods: Introduction When the webapp framework calls a request handler method, the handler instance's response member is initialized with an empty Response instance. The handler method prepares the response by manipulating the Response instance, such as by writing body data to the out member or setting headers on the headers member. import datetime from google.appengine.ext import webapp class MyRequestHandler(webapp.RequestHandler): def get(self): self.response.out.write("<html><body>") self.response.out.write("<p>Welcome to the Internet!</p>") self.response.out.write("</body></html>") expires_date = datetime.datetime.utcnow() + datetime.timedelta(365) expires_str = expires_date.strftime("%d %b %Y %H:%M:%S GMT") self.response.headers.add_header("Expires", expires_str) webapp sends the response when the handler method returns. The content of the response is the final state of the Response object when the method returns. Note: Manipulating the object in the handler method does not communicate any data to the user. In particular, this means that webapp cannot send data to the browser then perform additional logic, as in a streaming application. (App Engine applications cannot stream data to the browser, with or without webapp.) By default, responses use a HTTP status code of 200 ("OK"). To change the status code, the application uses the set_status() method. See also the RequestHandler object's error() method for a convenient way to set error codes. If the response does not specify a character set in the Content-Type header, the character set for the response is set to UTF-8 automatically. Constructor The constructor of the Response class is defined as followed: - class Response() An outgoing response. Typically, the WSGIApplication instantiates a RequestHandler and initializes it with a Response object with default values. Class Methods The Response class provides the following class methods: - Response.http_status_message(code) Returns the default HTTP status message for a given HTTP status code. Arguments - code - The HTTP status code. Instance Variables An instance of the Response class has the following variable members: - out An instance of the StringIO class that contains the body text of the response. The contents of this object are sent as the body of the response when the request handler method returns. - headers An instance of the wsgiref.headers.Headers class that contains the headers of the response. The contents of this object are sent as the headers of the response when the request handler method returns. For security reasons, some response headers cannot be modified by the application. See Responses. Instance Methods An instance of the Response class has the following methods: - set_status(code,message=None) Sets the HTTP status code, and optional message for the response. Arguments - code - The HTTP status code to use for the response. - The HTTP status message to use for the response. If none is given, use the default from the HTTP/1.1 specification. - clear() Clears all data written to the output stream (out). - wsgi_write(start_response) Writes the response using WSGI semantics. Typically, an application does not call this directly. Instead, webapp calls this to write the response when the request handler method returns. Arguments - start_response - A WSGI-compatible start_responsefunction.
https://cloud.google.com/appengine/docs/python/tools/webapp/responseclass
CC-MAIN-2015-40
refinedweb
552
50.33
Scala is a general-purpose, high-level, multi-paradigm programming language. It is a pure object-oriented programming language which also provides support to the functional programming approach. Scala programs can convert to bytecodes and can run on the JVM(Java Virtual Machine). Scala stands for Scalable language. Scala doesn’t provide any support for .Net Framework. Scala was designed by the Martin Odersky, professor of programming methods at École Polytechnique Fédérale de Lausanne (EPFL) in Switzerland and a German computer scientist. Scala was first released publicly in 2004 on the Java platform as its first version. In June 2004. The latest version of scala is 2.12.6 which released on 27-Apr-2018. Topics: - Features and Application - Installation Guide - Run Scala Code - Variables - Operators - Decision Making - Loops - Arrays - Strings - Functions Scala has many reasons for being popular and in demand. Few of the reasons are mentioned below: - Object- Oriented: Every value in Scala is an object so it is a purely object-oriented programming language. The behavior and type of objects are depicted by the classes and traits in Scala. - Functional: It is also a functional programming language as every function is a value and every value is an object. It provides the support for the high-order functions, nested functions, anonymous functions etc. - Statically Typed: The process of verifying and enforcing the constraints of types is done at compile time in Scala. Unlike other statically typed programming languages like C++, C etc., Scala doesn’t expect the redundant type of information from the user. In most cases, the user has no need to specify a type. - Extensible: New language constructs can be added to Scala in form of libraries. Scala is designed to interpolate with the JRE(Java Runtime Environment). - Concurrent & Synchronize Processing: Scala allows the user to write the codes in an immutable manner that makes it easy to aplly the parallelism(Synchronize) and concurrency. Application area Scala is a very compatible language and thus can very easily be installed into the Windows and the Unix operating systems both very easily. Since Scala is a lot similar to other widely used languages syntactically, it is easier to code and learn in Scala. scala programs can be written on any plain text editor like notepad, notepad++, or anything of that sort. One can also use an online IDE for writing Scala codes or can even install one on their system to make it more feasible to write these codes because IDEs provide a lot of features like intuitive code editor, debugger, compiler, etc. To begin with, writing Scala Codes and performing various intriguing and useful operations, one must have scala installed on their system. This can be done by following the step by step instructions provided below: - Verifying Java Packages The first thing we need to have is a Java Software Development Kit(SDK) installed on the computer. We need to verify this SDK packages and if not installed then install them. - Now install Scala We are done with installing the java now let’s install the scala packages. The best option to download these packeges is to download from the official site only: The packages in the link above is the approximately of 100MB storage. Once the packages are downloaded then open the downloaded .msi file. - Testing and Running the Scala Commands Open the command prompt now and type in the following codes. C:\Users\Your_PC_username>scala We will receive an output as shown below: Output of the command. Let’s consider a simple Hello World Program. Output: Hello, World! Generally, there are two ways to Run a Scala program- - Using Online IDEs: We can use various online IDEs which can be used to run Scala programs without installing. - Using Command-Line: We can also use command line options to run a Scala program. Below steps demonstrate how to run a Scala program on Command line in Windows/Unix Operating System: Open Commandline and then to compile the code type scala Hello.scala. If your code has no error then it will execute properly and output will be displayed. Fundamentals of Scala Variables are simply a storage location. Every variable is known by its name and stores some known and unknown piece of information known as value. In Scala there are two types of variable: - Mutable Variables: These variables are those variables which allow us to change a value after the declaration of a variable. Mutable variables are defined by using the “var” keyword. - Immutable Variables: These variables are those variables which do not allow you to change a value after the declaration of a variable. Immutable variables are defined by using the “val” keyword. Example: // Mutable Variable var name: String = "geekforgeeks"; // Immutable Variable val name: String = "geekforgeeks"; To know more about Scala Variables refer – Variables in Scala, Scope of Variable in Scala. An operator is a symbol that represents an operation to be performed with one or more operand. Operators allow us to perform different kinds of operations on operands. There are different types of operators used in Scala as follows: Example : Addition is: 14 Subtraction is: 6 Equal To Operator is False Logical Or of a || b = true Bitwise AND: 0 Addition Assignment Operator: () Decision Making in programming is similar to decision making in real life. Scala uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program. Decision Making Statements in Scala : - If - If – else - Nested – If - if – elsif ladder Example 1: To illustrate use of if and if-else Even Number Sudo Placement Example 2: To illustrate the use of Nested-if Number is divisible by 2 and 5 To know more about Decision Making please refer to Decision making in Scala Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. Loops make the programmer’s task simpler. Scala provides the different types of loop to handle the condition based situation in the program. The loops in Scala are : - for loopchevron_rightfilter_noneOutput: Value of y is: 1 Value of y is: 2 Value of y is: 3 Value of y is: 4 - While loopchevron_rightfilter_noneOutput: Value of x: 1 Value of x: 2 Value of x: 3 Value of x: 4 - do-while loopchevron_rightfilter_noneOutput: 10 9 8 7 6 5 4 3 2 1 To know more about Loops please refer to Loops in Scala Array is a special kind of collection in scala. it is a fixed size data structure that stores elements of the same data type. It is a collection of mutable values. Below is the syntax. Syntax : var arrayname = new Array[datatype](size) It will create an array of integers which contains the value 40, 55, 63, 17 and many more. Belowb is the syntax to access a single element of an array. number(0) It will produce the output as 40. Iterating through an Array: second element of an array is: geeks To know more about arrays please refer to Arrays in Scala A string is a sequence of characters. In Scala, objects of String are immutable which means a constant and cannot be changed once created. In Scala a String type is specified before meeting the string literal. but when the compiler meet to a string literal and creates a string object str. Syntax : var str = "Hello! GFG" or val str = "Hello! GFG" var str: String = "Hello! GFG" or val str: String = "Hello! GFG" Hello! GFG GeeksforGeeks. String 1:Welcome! GeeksforGeeks String 2: to Portal New String :Welcome! GeeksforGeeks to Portal This is the tutorial of Scala language on GFG portal To know more about Strings please refer to Strings in Scala A function is a collection of statements that perform a certain task. Scala is assumed as functional programming language so these play an important role. It makes easier to debug and modify the code. Scala functions are first class values. Below is the syntax of Scala Functions. Syntax: def function_name ([parameter_list]) : [return_type] = { // function body } def keyword is used to declare a function in Scala.) Output : Sum is: 8 Anonymous Functions in Scala : In Scala, An anonymous function is also known as a function literal. A function which does not contain a name is known as an anonymous function. Syntax : (z:Int, y:Int)=> z*y Or (_:Int)*(_Int) Output : Geeks12Geeks GeeksforGeeks Scala Nested Functions: A function definition inside an another function is known as Nested Function. In Scala, we can define functions inside a function and functions defined inside other functions are called nested or local functions. Syntax : def FunctionName1( perameter1, peramete2, ..) = { def FunctionName2() = { // code } } Output: Min and Max from 5, 7 Max is: 7 Min is: 5 Currying Functions in Scala : Currying in Scala is simply a technique or a process of transforming a function. This function takes multiple arguments into a function that takes single argument. Syntax : def function name(argument1, argument2) = operation Output: 39. OOPs Concepts: Creation of a Class and an Object: Classes and Objects are basic concepts of Object Oriented Programming which revolve around the real-life entities. A class is a user-defined blueprint or prototype from which objects are created. Name of the company : Apple Total number of Smartphone generation: 16 Traits are like interfaces in Java. But they are more powerful than the interface in Java because in the traits you are allowed to implement the members. Traits can have methods(both abstract and non-abstract), and fields as its members. Creating a trait – Output : Pet: Dog Pet_color: White Pet_name: Dollar To know more about Traits please refer to Traits in Scala Regular Expressions explain a common pattern utilized to match a series of input data so, it is helpful in Pattern Matching in numerous programming languages. In Scala Regular Expressions are generally termed as Scala Regex. Output : Some(GeeksforGeeks) To know more about tuple please refer to Regular Expressions in Scala. An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time. These events change the flow control of the program in execution. In scala, All exceptions are unchecked. there is no concept of checked exception Scala facilitates a great deal of flexibility in terms of the ability to choose whether to catch an exception. The Throwing Exceptions : Output : You are eligible for internship Try-Catch Exceptions : Output : Arithmetic Exception occurred. File Handling is a way to store the fetched information in a file. Scala provides packages from which we can create, open, read and write the files. For writing to a file in scala we borrow java.io._ from Java because we don’t have a class to write into a file, in the Scala standard library. We could also import java.io.File and java.io.PrintWriter. - Creating a new file : - java.io.File defines classes and interfaces for the JVM access files, file systems and attributes. - File(String pathname) converts theparameter string to abstract path name, creating a new file instance. - Writing to the file : java.io.PrintWriter includes all the printing methods included in PrintStream. Below is the implementation for creating a new file and writing into it.chevron_rightfilter_none - Reading a File : Below is the example to reading a file.chevron_rightfilter_none To know more about various different File Handling, please refer to File Handling in Scala A list is a collection which contains immutable data. List represents linked list in Scala. The Scala List class holds a sequenced, linear list of items. Lists are immutable whereas arrays are mutable in Scala. In a Scala list, each element must be of the same type. list is defined under scala.collection.immutable package. Syntax : val variable_name: List[type] = List(item1, item2, item3) or val variable_name = List(item1, item2, item3) Create and initialize Scala List Example : Output : List 1: List(Geeks, GFG, GeeksforGeeks, Geek123) List 2: C C# Java Scala PHP Ruby To know more about List please refer to List in Scala. Map is a collection of key-value pairs. In other words, it is similar to dictionary. Keys are always unique while values need not be unique. In order to use mutable Map, we must import scala.collection.mutable.Map class explicitly. Creating a map and accessing the value Example : Output : 30 To know more about Map please refer to Map in Scala. An iterator is a way to access elements of a collection one-by-one. It resembles to a collection in terms of syntax but works differently in terms of functionality. To access elements we can make use of hasNext() to check if there are elements available and next() to print the next element. Syntax: val v = Iterator(5, 1, 2, 3, 6, 4) //checking for availability of next element while(v.hasNext) //printing the element println(v.next) Example : Output: 5 1 2 3 6 4 To know more about tuple please refer to Iterators in Scala. A set is a collection which only contains unique items. The uniqueness of a set are defined by the == method of the type that set holds. If you try to add a duplicate item in the set, then set quietly discard your request. Syntax : // Immutable set val variable_name: Set[type] = Set(item1, item2, item3) or val variable_name = Set(item1, item2, item3) // Mutable Set var variable_name: Set[type] = Set(item1, item2, item3) or var variable_name = Set(item1, item2, item3) Creating and initializing Immutable set Example : Output : Set 1: Set(Geeks, GFG, GeeksforGeeks, Geek123) Set 2: Scala C# Ruby PHP C Java Creating and initializing mutable set Example : Output : Set 1: Set(Geeks, GFG, GeeksforGeeks, Geek123) Set 2: 10 100000 10000 1000 100 To know more about Set please refer to Set in Scala | Set-1 and Set in Scala | Set-2. Tuple is a collection of elements. Tuples are heterogeneous data structures, i.e., is they can store elements of different data types. A tuple is immutable, unlike an array in scala which is mutable. Creating a tuple and accessing an element Example : Output : 15 chandan true To know more about tuple please refer to tuple in Scala. Recommended Posts: - Scala Char to(end: Char, step: Char) method with example - Scala Int to(end: int, step: int) method with example - Scala Float to(end: Float, step: Float) method with example - Scala Int until(end: Int, step: Int) method with example - Scala Float until(end: Float, step: Float) method with example -.
https://www.geeksforgeeks.org/scala-tutorial-learn-scala-with-step-by-step-guide/?ref=rp
CC-MAIN-2020-45
refinedweb
2,429
63.09
On Jan 17, 2008 1:54 PM, Mel <mwilson at the-wire.com> wrote: > > test(a) (along with def test(x)) takes the object named 'a' in the > current namespace and binds it with the name 'x' in function test's > local namespace. So, inside test, the name 'x' starts by referring to > the list that contains [1,2,3]. But the only use test makes of the > name 'x' is to re-bind it to a new list [4,5,6]. Exiting test, the > local namespace is thrown away. > Hi, Yes I know it pretty well now, but thanks for the pointer. What I asked is that, if we re-write that code with perl or C, we'll get different results.
https://mail.python.org/pipermail/python-list/2008-January/511221.html
CC-MAIN-2014-15
refinedweb
123
89.38
Load the State from the Session To make our login information persist we need to store and load it from the browser session. There are a few different ways we can do this, using Cookies or Local Storage. Thankfully the AWS Amplify does this for us automatically and we just need to read from it and load it into our application state. Amplify gives us a way to get the current user session using the Auth.currentSession() method. It returns a promise that resolves to the session object (if there is one). Load User Session Let’s load this when our app loads. We are going to do this in componentDidMount. Since Auth.currentSession() returns a promise, it means that we need to ensure that the rest of our app is only ready to go after this has been loaded. To do this, let’s add a flag to our src/App.js state called isAuthenticating. The initial state in our constructor should look like the following. this.state = { isAuthenticated: false, isAuthenticating: true }; Let’s include the Auth module by adding the following to the header of src/App.js. import { Auth } from "aws-amplify"; Now to load the user session we’ll add the following to our src/App.js below our constructor method. async componentDidMount() { try { if (await Auth.currentSession()) { this.userHasAuthenticated(true); } } catch(e) { if (e !== 'No current user') { alert(e); } } this.setState({ isAuthenticating: false }); } All this does is check if a session object is returned. If so, then it updates the isAuthenticating flag once the process is complete. Also, the Auth.currentSession() method throws an error No current user if nobody is currently logged in. We don’t want to show this error to users when they load up our app and are not signed in. Render When the State Is Ready Since loading the user session is an asynchronous process, we want to ensure that our app does not change states when it first loads. To do this we’ll hold off rendering our app till isAuthenticating is false. We’ll conditionally render our app based on the isAuthenticating flag. Our render method in src/App.js should be as follows. render() { const childProps = { isAuthenticated: this.state.isAuthenticated, userHasAuthenticated: this.userHasAuthenticated }; return ( !this.state.isAuthenticating && <div className="App container"> <Navbar fluid collapseOnSelect> <Navbar.Header> <Navbar.Brand> <Link to="/">Scratch</Link> </Navbar.Brand> <Navbar.Toggle /> </Navbar.Header> <Navbar.Collapse> <Nav pullRight> {this.state.isAuthenticated ? <NavItem onClick={this.handleLogout}>Logout</NavItem> : <Fragment> <LinkContainer to="/signup"> <NavItem>Signup</NavItem> </LinkContainer> <LinkContainer to="/login"> <NavItem>Login</NavItem> </LinkContainer> </Fragment> } </Nav> </Navbar.Collapse> </Navbar> <Routes childProps={childProps} /> </div> ); } Now if you head over to your browser and refresh the page, you should see that a user is logged in. Unfortunately, when we hit Logout and refresh the page; we are still logged in. To fix this we are going to clear the session on logout next. 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
https://branchv21--serverless-stack.netlify.app/chapters/load-the-state-from-the-session.html
CC-MAIN-2022-33
refinedweb
514
67.65
Skip to 0 minutes and 1 secondThis week, we're going to extended an existing class. But it's also perfectly normal to write your own classes and then extend them. We're just going to test this class out first. So create a new Trinket. If you're using a text editor, create a new file called character test . py. Copy the code from this link and save it as character . py. If you're using a text editor, make sure this file is in the same folder as all of your previous code. Skip to 0 minutes and 29 secondsThis is the character class, which we've written for you. You can see from looking at the code that to create a character object, we must provide two arguments to the constructor, the character's name, and a description of the character. Go back to your test file. Inside this file, create a character object. Skip to 0 minutes and 55 secondsCall the method describe on the object you created to show the character's description on the screen. Save and run your programme, and you should see the description of the character you just created. Extending an existing class This week we’re going to extend an existing class. This means we will create another class which uses the functionality of the existing class, but also adds to or overwrites some of it. It’s also perfectly normal to write your own classes and then extend them. If you are using a text editor, copy the code from this script, and paste and save it as a new file named character.py in the folder containing all your earlier code. If you are using Trinket, start a new trinket and create a character.py file to store the code, but keep the main.py file as well. The code is the Character class which we have written for you – if you have a look at it, you should recognize some familiar things. You’ll see that to create a Character object, the constructor needs two parameters – the character’s name, and a description of the character: def __init__(self, char_name, char_description): self.name = char_name self.description = char_description self.conversation = None If you are using a text editor, create a new Python file and save it as character_test.py in the folder with your other code. If you are using Trinket, put this code inside the main.py file in the new trinket. Inside this file, create a character object. from character import Character dave = Character("Dave", "A smelly zombie") Call the method describe on the object you created to show the character’s description on the screen. dave.describe() Save and run your program. You should see the description of the character you just created: Dave is here! A smelly zombie Challenge - Examine the Characterclass inside character.py to find the name of the method which sets the conversation attribute - Add code to main.py to call this method and give Dave a line of dialogue - Add code to main.py to call a different method which talks to Dave So far, so good – we can use this code as the basis for our characters. However, not every character in the game will have the same characteristics. Some will be friends and some will be enemies, and they may behave differently. © CC BY-SA 4.0
https://www.futurelearn.com/courses/object-oriented-principles/1/steps/229231
CC-MAIN-2018-51
refinedweb
569
74.69
#include <hallo.h> Joey Hess wrote on Wed Mar 27, 2002 um 02:21:49PM: > > "fine-configured". Only essential things are configured to get the > > package into the "configured" state. For all fine configuration, the > > user can invoke a frontend (GUI/TUI with list selection, or CLI like > > dpkg-reconfigure) and manage the rest. > > man debconf No. The examples in the Tutorial are the only good explanaition about how to use Priorities. Though, I will modify my suggestion: - I would like to see a method do distinguish between answered and supressed questions (default answers) - I would like to store data about answered/unanswered questions somewhere - I would like to have templates with substitution fields. BTW, why not use gettext for templates? >. OTOH the language can be set while locales are configured, so the few steps between initial reboot and locales configuration has to be non-localised. Gruss/Regards, Eduard. -- > Der Thread kann beginnen. könntest du eventuell das "Dr." entfernen ? das macht so einen auf rangfolge... und wir wissen ja, daß hier ist anarchie mit mir als oberstem anarchen. [Adrian Knoth] -- To UNSUBSCRIBE, email to debian-devel-request@lists.debian.org with a subject of "unsubscribe". Trouble? Contact listmaster@lists.debian.org
https://lists.debian.org/debian-devel/2002/03/msg02215.html
CC-MAIN-2019-22
refinedweb
201
58.18
Forum Index Hi folks Settling down to write my first app but have come to a grinding halt. This is my first system-level language so I'm afraid I'll be asking some naïve questions. All I'm trying to do is read a text file with Windows line endings into an array for line-by-line processing. The relevant function appears to be std.stdio.File.byLine. The default isn't breaking the lines properly, so I have to pass in the line ending. But the signature has me baffled:? The examples are unenlightening as they only show the default case, so any help would be much appreciated. Any wider tips on how to read these cryptic signatures would be a bonus! On Thursday, 15 July 2021 at 18:08:45 UTC, Scotpip wrote: Sorry I'm on mobile right now so can't help much, but if you're a beginner, please read the book "programming in D" by Ali Cehreli. If you just want to learn about files for now, visit this link, it contains a chapter of his book(regrettably it doesn't cover your exact usecase but maybe readln might work out for you) readln On Thursday, 15 July 2021 at 18:36:30 UTC, Tejas wrote: Thanks - I'm aware of the book - it's what gave me the confidence to have a go at D - but as you say it doesn't cover this use-case. I also have the old Alexandrescu book but it doesn't cover this either. I'm new to systems work, but I'm not new to programming - I wrote my first programme on punch cards... I must have learned a dozen languages over the years, but this signature is the most cryptic I've ever encountered. Maybe if you're a C++ maven it makes sense, but it's pretty opaque to anyone else. When the examples are thin it really does make it hard for people trying to work their way into the community. So specific help on the issue of understanding this signature and reading in a Windows text file would still be very much appreciated. On Thu, Jul 15, 2021 at 06:08:45PM +0000, Scotpip via Digitalmars-d-learn wrote: [...] > ``` >? First, notice that there are two sets of parentheses in the above quoted declarations. The first set are compile-time parameters (template parameters), while the second are runtime parameters. `Terminator` and `Char` are listed as compile-time parameters, meaning that they are types specified by the caller, so there is no definition for them -- the caller defines what they will be. (More on this later.) Secondly, note the order of parameters in the second set of parentheses: `keepTerminator` first, then `terminator`. This is why your example above doesn't compile: you're trying to specify a terminator where the function expects a KeepTerminator parameter. Now, a fully-specified invocation of byLine would specify both compile-time and runtime parameters, e.g.: auto r = File(...) .byLine!(string,char)(Yes.KeepTerminator, "\r\n"); In this case, Terminator == string, Char == char. But generally, the D compiler is pretty good at inferring types for you automatically, so in this case, since the runtime parameters already adequately imply what the compile-time arguments will be, so you could just leave them out and write simply: auto r = File(...) .byLine(Yes.KeepTerminator, "\r\n"); > The examples are unenlightening as they only show the default case, so any help would be much appreciated. Any wider tips on how to read these cryptic signatures would be a bonus! Please file a bug against the documentation about this. Examples should cover not only the default case, but should also illustrate how to use non-default values. This is a shortcoming in the documentation. T -- MS Windows: 64-bit rehash of 32-bit extensions and a graphical shell for a 16-bit patch to an 8-bit operating system originally coded for a 4-bit microprocessor, written by a 2-bit company that can't stand 1-bit of competition. To specify the line ending, it appears to be asking for a type "Terminator" which I can't find in the library. Terminator appears a few times in the signature. The first appearance, in byLine(Terminator, ...)(...), is a template parameter. So Terminator is whatever you want that otherwise works. byLine(Terminator, ...)(...) Doing the obvious doesn't work: The first parameter is the keepTerminator flag. That wysiwyg string is four bytes long and includes the literal slashes. $ rdmd --eval '`\r\n`.representation.writeln' [92, 114, 92, 110] Here's a simple dos2unix: import std.stdio, std.typecons; void main() { foreach (line; stdin.byLine!(string, char)(No.keepTerminator, "\r\n")) writeln(line); } The !(string, char) isn't necessary in the last example, but that's how you'd provide it. Usage: $ echo -ne "hi\r\nthere\r\n" | dmd -run dosin|od -c 0000000 h i \n t h e r e \n 0000011 Outstanding answers, folks. This is a great community! If I ever manage to get on top of this cussed language, I hope to reciprocate by posting some material aimed at newbies coming from areas like line-of-business with scripting languages, which is where I've done most of my coding. This is a different world. Even though this is a learner's forum, it's clear that most of the people taking up D have a strong background in gnarly systems languages like C++. The on-ramp for people like me is pretty steep. I'm not whinging - given the lack of corporate backing it's pretty amazing how mature this language has become - and I'm very aware of the huge and selfless investment the developers have made. But it's definitely more intimidating to tackle D than one of the more trendy languages like Go or Julia where there are plentiful learning resources.. So thanks again - without this kind of support it would be pretty much impossible for newbies like me to get up to speed. On Thu, Jul 15, 2021 at 08:24:57PM +0000, Scotpip via Digitalmars-d-learn wrote: [...] >. [...] My personal favorite approach to D template functions is to not think of them as templates in the first place, but rather as functions with *compile-time* parameters (in addition to the usual runtime parameters). I.e., parameters that get baked in at compile-time. Since the parameters are processed at compile-time, they can do a more than the usual runtime parameters can, such as receiving types and aliases and other such things that only exist at compile-time. The function can then act on these arguments at compile-time to adapt itself to the task thus specified, without incurring the runtime overhead of a runtime check. T -- There are two ways to write error-free programs; only the third one works. On Thursday, 15 July 2021 at 21:23:58 UTC, H. S. Teoh wrote: My personal favorite approach to D template functions is to not think of them as templates in the first place, but rather as functions with compile-time parameters (in addition to the usual runtime parameters). Thanks - that does seem like a helpful analogy. D's generics look pretty powerful to people like me who have only encountered them in Java and C#. I'm not writing libraries so I probably don't need to get too deep into the weeds, but they are clearly one of the standout features and well worth digging into!
https://forum.dlang.org/thread/layjvvjmxgaglizavnhg@forum.dlang.org
CC-MAIN-2021-39
refinedweb
1,256
62.07
Socialwg/2015-11-24-minutes Contents 24, cwebber2 - Regrets Chair - tantek - Scribe - Rob_Sanderson, azaroth Contents - Topics - Summary of Action Items - Summary of Resolutions <tantek> trackbot, start meeting <trackbot> Meeting: Social Web Working Group Teleconference <trackbot> Date: 24 November 2015 <ben_thatmustbeme> there are only 5 people dialed in <scribe> ScribeNick: azaroth <ben_thatmustbeme> azaroth++ <scribe> Scribe: Rob_Sanderson <Loqi> azaroth has 1 karma <tantek> scribe: azaroth <tantek> <cwebber2> whoops, calling in! Tantek: Approval of minutes. Last week's called cancelled, so the week before. <wilkie> +1 <ben_thatmustbeme> +1 Tantek: +1s? +1 scribe: Resolved ... Next on the agenda, next week we'll be meeting face to face in San Francisco <tantek> scribe: Dec 1,2 at Mozilla San Francisco ... Enter on the first floor and will get a badge and directions ... Calling out the required reading section. Everyone who's participating is expected to read it ... We'll discuss those docs directly, and will not summarize them <tantek> <cwebber2> I just got in scribe: If there's anything you want to resolve / approve / etc, then please read them first ... We'll be linking them up soon ... (Or anyone else can too) ... Questions? ... Will try to be on IRC, but of course have Thanksgiving Thursday/Friday ... So those two days probably not, so any questions please send them in sooner rather than later <wilkie> I am flying Thanksgiving night to SF. thank goodness for cheap flights. Technical items for discussion <cwebber2> thanks aaronpk <tantek> Tantek: James sent his regrets, so propose we defer discussion of AS items until the F2F ... If there's specific items that people here think they can make progress on without James, please say? ... Any items we can move forward on? ... tumbleweed ... <cwebber2> :) Tantek: Silence as acceptance to defer <melvster> was there anything in the queue from last time? Tantek: Please Q+ anything that comes up. Most were in the queue from last time. <tantek> Federation protocol: Webmention ready as editor's draft Tantek: Next area ... aaronpk has added WebMention. aaronpk: We've talked about WebMention in the past. A few of us have been working on cleaning it up to share with the group ... We have a draft that should be sufficient as an ED for the group <aaronpk> aaronpk: Nothing new from the specification side, but the document is new ... A start towards the federation protocol ... It's not tied to microformats, though most implementations use them at the moment ... should be applicable to other types of documents as well ... Any questions? Tantek: Thanks for getting this into ED state, really appreciate that. ... Lots of time spent on AS as the most mature doc we had coming in. WebMention explicitly mentioned as input in the charter, so good to make progress in multiple areas ... We can just go ahead and accept it as ED, but a spearate step to publish as FPWD <cwebber2> ... (should we be submitting activitypump to editor's draft status?) Tantek: Want to ask those on the call if there's objections? Or questions? <melvster> webmention is stated as a *possible* input as is linked data platform azaroth: Where to send feedback on the doc? github issues? aaronpk: Thinking about it :) I like using github for questions, nice threaded view. Will get back to you on that Tantek: Looking at the header at the top, I see a wiki for open issues. ... I share the question, and that gh issues could be considered <ben_thatmustbeme> aaronpk, i'd agree, that github usually works well Tantek: I created an issues only gh for post-type discovery draft, that could be something to consider <wilkie> there are two places I see mentioned: aaronpk: Should I make it in the socialWG account? tantek: Yes, that seems the best <tantek> tantek: As an example ^^ the post type discovery spec aaronpk: I'd be happy to do that azaroth: No problem :) <tantek> ack <Zakim> tantek, you wanted to ask How soon can Webmention editor's draft be ready for FPWD? tantek: Looks fairly spec like, what do you need to be ready for FPWD? What are you blocked on, or is it ready? aaronpk: From my perspective it's functional enough to push forwards, however I'd love to get feedback ... Make sure it's clear enough from an implementation perspective ... Also just more technical clean up to move things around, but mostly just removing / reorienting text <ben_thatmustbeme> would that be after accepting as editor's draft though? tantek: Would like to add to required reading <cwebber2> no objections, but tantek: it looks like it's been through a lot of iterations, we can approve at the f2f ... objections? <bengo> +1 to required reading <wilkie> that sounds good to read it for the f2f cwebber2: No objections, wondering whether it makes sense to do the same for activity pump? tantek: To be clear, which area of the charter do you think activity pump comes in? cwebber2: Under social api and federation api tantek: I think that's something we should add. I see no problem adding. Did you have something ready? <Loqi> Tantekelik made 1 edit to Socialwg/2015-12-01 tantek: a separate topic <cwebber2> sorry tantek: Adding to agenda. <cwebber2> I did mean to queue it for the next topic but wasn't sure how to do that <cwebber2> in this queue <cwebber2> ;p <cwebber2> done <cwebber2> ++ to webmention tantek: Did you have a question about webmention? ... No other questions, move on to next item. <melvster> I dont like the idea of source and target variables flying around without namespaces ... id look at semantic pingback : <melvster> in general I see this as a non starter <tantek> Social API: Micropub for consideration as editor's draft (Aaron) Social API - micropub tantek: Another one for aaronpk <kevinmarks> melvster: it's a defined endpoint; it doesn't need namespaces <aaronpk> (please save the arguments about webmention for later, that's not the topic of the call) tantek: Noting that micropub wasn't in the initial list of docs when we started the WG, so a bit different context, but provide details for why it should be considered aaronpk: Going through a lot of iterations based on feedback from the group ... It's not as mature as webmention, so not ready as ED. Proposal is to consider it as such, knowing that we'll continue to work on it and it'll evolve much more than webmention <aaronpk> aaronpk: Link ^^ ... The text needs work, lots of cleanup needed before anyone should read through it <bengo> Other links that have been mentioned: aaronpk: I'll send a note when it's ready to look at ... any questions about it? tantek: What is the specific proposal? ... Want it considered as ED for the group? aaronpk: That's correct ... I think it fulfils the API part of the charter as a self contained building block ... goes along side webmention but not coupled to any particular aspects <tantek> PROPOSED: Accept Micropub as an editor's draft for the Social Web WG as part of the Social API section of the charter <melvster> pointer? Arnaud: I'm a bit confused. I don't see how the document compares to what Amy has been putting together? <tantek> +1 to Arnaud's question aaronpk: This is mostly just existing micropub, but goal is to reconcile with what Amy has been doing ... to make it work with what we've been working with collectively Arnaud: But if it was a rec, we wouldn't need Amy's document? <bengo> bigbluehat I think <rhiaro_> aaronpk: Can we combine them into the same proposal? <bigbluehat> bengo: thanks! aaronpk: Amy is here? tantek: We had that doc accepted as ED from Amy <rhiaro_> Mine is an outline with potential spaces for the pieces. Happy to see it dissolve if other modular things can take its place rhiaro_: What I wrote was an outline of the different pieces ... would like to see them replaced by individual specs ... if there's anything left, then we can spec those later <wilkie> I was assuming amy's document should supersede any other federation api document <kevinmarks> Amy's doc refences micropub already rhiaro_: So if the doc disappeared to be replaced, that would be fine <kevinmarks> Creating content Sandro: Which piece of your doc does this replace? Amy: Creating content sandro: so long as it's one section, that makes sense <bengo> azaroth If SocialAPI is editor's draft, should it be listed here? If so, are any other ED missing? rhiaro_: micropub is creating content, webmention is mentioning <kevinmarks> tantek: Amy's doc on the required reading list ... also an ED for the WG. My preference would be to see both docs move forwards. Premature to say one could replace the other ... Trust that the editors of the docs will work together to explain the relationships ... an action on both? ... That something that rhiaro_ and aaronpk can take on? Both: Yes happy to do that tantek: Lets make an action then <kevinmarks> Amy's draft already does mention it <rhiaro_> melvster: since semantic pingback defines source and target, you could default to that namespace if you wanted to namespace received webmentions yourself ACTION rhiaro_ to explain relationship to aaronpk's document <trackbot> Error finding 'rhiaro_'. You can review and register nicknames at <>. ACTION rhiaro to explain relationship to aaronpk's document <trackbot> Created ACTION-74 - Explain relationship to aaronpk's document [on Amy Guy - due 2015-12-01]. ACTION aaronpk to explain relationship to rhiaro's document <trackbot> Created ACTION-75 - Explain relationship to rhiaro's document [on Aaron Parecki - due 2015-12-01]. <tantek> PROPOSED: Accept Micropub as an editor's draft for the Social Web WG as part of the Social API section of the charter tantek: Not seeing any questions .... <Loqi> Tantekelik made 1 edit to Socialwg/2015-11-24 <Loqi> Tantekelik made 1 edit to Socialwg/2015-12-01 Arnaud: I think it's premature before we understand how they relate ... I'd like the decision to be deferred tantek: I think Amy and aaronpk answered that? aaronpk: We accepted we'd clarify, but it hasn't yet been clarified Arnaud: Exactly :) <kevinmarks> it's already clear in Amy's draft, just needs backref in micropub tantek: Your preference is to wait for that <bigbluehat> +1 to clarity Arnaud: Indeed <melvster> +1 clarify tantek: aaronpk are you okay with that? +1 to clarify first <wilkie> I agree with that tantek: Amy? rhiaro: A process question, can someone point me to ED definition? <cwebber2> yes please re: editor's draft rhiaro: not even a commitment to publishing tantek: Your understanding is correct <cwebber2> okay, if that's true, then I think activitypump is ready for editor's draft tantek: a new doc that has not been mentioned in the charter, so we need to explicitly accept it or not ... my understanding from Arnaud is that before deciding he would need to know the relationship. I think that's a reasonable request <bengo> rhiaro "Working Groups and Interest Groups may make available "Editor's drafts". Editor's drafts have no official standing whatsoever, and do not necessarily imply consensus of a Working Group or Interest Group, nor are their contents endorsed in any way by W3C." tantek: so no argument regarding next steps <rhiaro_> thanks bengo Arnaud: For the record, I don't vote in WGs that I chair, so feel free to ignore if you want. I'd answer Amy's question a little differently, when we accept it as ED it's the first step on putting it in REC track ... no guarantee that any document gets there, but it's an important first step sandro: I think it makes sense for aaron to write a proposal in the syntax and style of a draft for what could go in creating content section ... if the WG accepts the proposal, then that could go in to be a spec, but we haven't started looking at it at all ... labeling it as ED would communicate that we had decided to go in that direction ... so better to call it a proposal ... no decision here, just communication issues tantek: I didn't hear from aaron or anyone an assertion of direction. Can raise for the WG? <rhiaro_> Good to maintain a coherant front as a WG :) sandro: Could be okay with ED if it's clearly labeled as not necessarily the direction of WG arnaud: what gain? tantek: WG is working on it ... I think the direction concern is valid sandro: Important part is feedback from the group that we would like a solid proposal <bengo> Might as well wait until after F2F to dub new EDs sandro: no pun intended :) <kevinmarks> micropun <bigbluehat> micropun++ <aaronpk> sandro: "It's good to have the activity pumping away at making a solid micropub proposal" #PUNINTENDED <Loqi> micropun has 1 karma <rhiaro_> "I think it's good to have the activity pumping away to have a solid micropub spec" tantek: Aaron you have a request for next steps. Arnaud's request reasonable. Clarity of direction from Sandro <rhiaro_> For the record. aaronpk: Should I label the page as a proposal? tantek: Its your draft, so long as you don't claim it from the WG. aaronpk: Can we clarify sandro's request? tantek: that the draft explicitly state it's not implying a direction, it's one approach but not claiming a specific direction sandro: So long as it doesn't go on WG list of EDs tantek: But to get it on the list, it shouldn't imply direction Arnaud: On the wiki page, we should have a section for proposals, not items the WG is working on <melvster> arnaud++ tantek: We have a list of things the group is working on <Loqi> arnaud has 28 karma <sandro> +1 put it on a list of proposals, not as a list of drafts tantek: will add that section to the home page +1 to list of proposals <melvster> +1 list of proposals Tantek: By that request, you're saying we should list micropub as a proposal Arnaud: I think that's reasonable to do ... that seems the case, there's a proposal that we can acknowledge tantek: Sandro? sandro: Yep tantek: Okay, great. ACTION tantek to add proposal section to social web WG page, with micropub as first entry <trackbot> Created ACTION-76 - Add proposal section to social web wg page, with micropub as first entry [on Tantek Çelik - due 2015-12-01]. <ben_thatmustbeme> micropub.net Tantek: Can you put the URL? micropub.net? ... Thank you ... No one on the queue ... any other questions? <melvster> please could additions to proposals list also be announced publicly? Tantek: We agreed to list as a proposal. Aaron, do you intend to discuss at the F2F? aaronpk: That'd be great if we have time for that tantek: Objections to adding micropub to required readings? sandro: How long to read? <cwebber2> everyone should be reading these specs anay <cwebber2> anyway aaronpk: I don't know 15 minutes? The syntax part is the important part sandro: Can we say that on the reading list? <wilkie> yeah, it should be expected to read these possible apis <kevinmarks> can we read AS2 in 15 minutes? tantek: Other questions? <melvster> -1 there's dozens of specs to read ACTION tantek to add micropub to required reading list <melvster> add to proposals, not required reading <trackbot> Created ACTION-77 - Add micropub to required reading list [on Tantek Çelik - due 2015-12-01]. <cwebber2> I think most of the problems in the group comes from people objecting to things without actually having read the spec they're objecting to <melvster> -1 <cwebber2> +1 <cwebber2> +1 to reading :P <bengo> +1 to reading <melvster> add to proposals not required reading, announce publically <Arnaud> I find this document (micropub) confusing <kevinmarks> the reason micropub is so long is that it has a list of implemntations in it <tantek> q <Arnaud> the structure isn't obvious tantek: No other questions, moving on <bigbluehat> aaronpk: kevinmarks: maybe the list of implementations could be moved to an appendix? Activity Pump for consideration at F2F <tantek> Activity Pump for consideration at F2f (cwebber) <aaronpk> yes, i still have lots of cleanup on the micropub one. webmention was in better shape :) <Arnaud> aaronpk, I think some section numbers would go a long way cwebber: Didn't mean to interupt earlier. Would like people to read the Acitivty Pump spec for the F2F <aaronpk> Arnaud, any examples of specs with section numbers in that format? cwebber: some areas that could do with review, but areas that we haven't come to consensus on ... Structure is pretty well understood ... Prior version has multiple implementations, could fulfil social and federation APIs <Arnaud> respec would take care of that for you automatically <rhiaro_> The prior version being pump.io? <kevinmarks> the wiki version has a toc and numbers cwebber: So would like consideration towards both of those areas ... Amy has been helping to reshape the docs to make them clearer ... As is, I think it's readable enough for the F2F <kevinmarks> so that is easier to read that the moment, arnaud tantek: Link please? sandro: How long? cwebber: I don;t think it'll take that long. 15-20 minutes probably? <rhiaro_> It doesn't take logn to read, but it took me a couple of days of concentrating to really understand it <cwebber2> <kevinmarks> if you start here tantek: Thank you Chris. Proposal is to discuss at F2F. And thus add to required reading. cwebber2: Yes adding to required. Would like to have it move forwards in the same way as micropub etc tantek: Not one of the documents in the charter, so would take the same route. Need to agree as a group to take it on as ED as the next step, after people have read and discussed ... soonest would be at teh F2F. cwebber2: That sounds good tantek: WebMention is a bit different, as it's in the charter ... F2F can hopefully discuss whether to publish as FPWD <melvster> no, webmention is mentioned as a *possible input* in the charter nothing more tantek: Propose to accept Pump as required reading? <wilkie> +1 tantek: Objections? <cwebber2> +1 unsurprisingly :) <aaronpk> +1 <sandro> +1 assuming 20 minutes <ben_thatmustbeme> +1 <tsyesika> +1 (also unsuprisingly) +1 <Arnaud> kevinmarks, thanks ACTION tantek to add Activity Pump to the list of required reading for F2F <trackbot> Created ACTION-78 - Add activity pump to the list of required reading for f2f [on Tantek Çelik - due 2015-12-01]. <Arnaud> (ref micropub wiki) <Loqi> Tantekelik made 1 edit to Socialwg <Loqi> Tantekelik made 2 edits to Socialwg/2015-12-01 <Loqi> Kmarks2 made 1 edit to Socialwg/2015-12-01 <cwebber2> yeah I think that's right tantek: Should add it to the proposals section too ACTION tantek to add activity pump to proposals section of the home page <trackbot> Created ACTION-79 - Add activity pump to proposals section of the home page [on Tantek Çelik - due 2015-12-01]. <sandro> sorry, have to step away. see you all in SF tantek: Okay, that brings us to open issues catch all section ... Looking at the tracker ... separation of concerns issue? <tantek> issue 45 <tantek> issue-46 <trackbot> issue-46 -- AS2.0 tries to address some Social API responsibilities -- raised <trackbot> tantek: Raised by Elf, are you on the call? ... Not on the call, so moving on. <tantek> issue-40 <trackbot> issue-40 -- Deprecate the "Post" activity -- pending review <trackbot> tantek: Next is pending review, #40 ... Item we think is completed. WG to accept that it has been completed. Raised by james ... Don't think he needs to be here ... Already resolved it. Any objections to closing? <cwebber2> wait tantek: Chris? <cwebber2> okay <cwebber2> no objections <cwebber2> was verifying <cwebber2> +1 <tantek> trackbot, close issue-40 tantek: Closing. Pending review actions, we have none. So end of the tracking issues section. Next Telco Tantek: Next telco is the 8th, with Arnaud as the chair ... Next meeting is next week, the F2F. ... Everyone remember to do your required reading, which we added a bunch of things to ... See you all next week <cwebber2> bye! <tantek> <wilkie> cool. thanks! Adjourned <tantek> trackbot, end meeting
https://www.w3.org/wiki/Socialwg/2015-11-24-minutes
CC-MAIN-2017-30
refinedweb
3,377
61.87
Chat room Open up the chat room example in the Arduino IDE under File > Examples > Pozyx > chat_room. This example requires two or more pozyx shields and an equal number of Arduino's. In this example, it will be possible to chat wirelessly with all pozyx devices in range. Below is a figure of two devices talking. To run this demo, make sure that the serial monitor runs at 115200 baud with "both NL & CR" enabled. Interpreting the LEDs: When this program is running, the Rx LED should be blinking, indicating that the Pozyx shield is listening for incoming data. Also LED1 should be blinking at a low frequency to indicate that the pozyx system is working properly. When this LED stops blinking, something went wrong. Finally, the TX led will blink shortly whenever you transmit a message. The Arduino code explained The Arduino sketch code begins as follows: #include <Pozyx.h> #include <Pozyx_definitions.h> #include <Wire.h> uint16_t source_id; // the network id of this device uint16_t destination_id = 0; // the destination network id. 0 means the message is broadcasted to every device in range String inputString = ""; // a string to hold incoming data boolean stringComplete = false; // whether the string is complete It can be seen that the sketch requires two pozyx files: "Pozyx.h" and "Pozyx_definitions.h" which contains the Pozyx Arduino library,and the "Wire.h" file for the I2C. After that, there are a number of global variables defined. Next, we look at the setup() function. This function runs only once when the Arduino starts up. void setup(){ Serial.begin(115200); // initialize Pozyx if(! Pozyx.begin(false, MODE_INTERRUPT, POZYX_INT_MASK_RX_DATA, 0)){ Serial.println("ERROR: Unable to connect to POZYX shield"); Serial.println("Reset required"); abort(); } // read the network id of this device Pozyx.regRead(POZYX_NETWORK_ID, (uint8_t*)&source_id, 2); // reserve 100 bytes for the inputString: inputString.reserve(100); Serial.println("--- Pozyx Chat started ---"); } From the code it can be seen that the Serial port is used at 115200 baud (~= bits per second). The other parameters for the serial port are default, i.e., 8bits, no parity, 1 stop bit. Next, the Pozyx device is initialized. The Pozyx.begin(boolean print_result, int mode, int interrupts, int interrupt_pin) function takes up to 4 parameters. This function checks that the Pozyx device is present and working correctly. The first parameter indicates if we want debug information printed out, the second describes the mode: MODE_POLLING or MODE_INTERRUPT. Using the polling mode, the Arduino will constantly poll (ask) the Pozyx shield if anything happened. Alternatively, the interrupt mode configures the pozyx device to give an interrupt signal every time an event has occured (this is the preferred way). Th events that should trigger in interrupt are configured by the interrupts parameter (more information about interrupts here). Lastly, with interrupt_pin it is possible to select between the two possible interrupt pins (digital pin 2 or 3 on the arduino). Here, the pozyx device is configured such that it doesn't output debug data, and that it uses interrupt using interrupt pin 0. With POZYX_INT_MASK_RX_DATA interrupts will be triggered each time wireless data is received. Next, the setup function reads out the 16 bit network id of the pozyx shield (this is the hexadecimal number printed on the label), and stores it in the global variable source_id. Notice that the regRead function works with bytes, so we indicate that we want to read 2 bytes starting from the register address POZYX_NETWORK_ID and store those to bytes in the byte pointer. Finally, 100 bytes are reserved for the input string. The code for the main loop is listed below: void loop(){ // check if we received a newline character and if so, broadcast the inputString. if(stringComplete){ Serial.print("Ox"); Serial.print(source_id, HEX); Serial.print(": "); Serial.println(inputString); int length = inputString.length(); uint8_t buffer[length]; inputString.getBytes(buffer, length); // write the message to the transmit (TX) buffer int status = Pozyx.writeTXBufferData(buffer, length); // broadcast the contents of the TX buffer status = Pozyx.sendTXBufferData(destination_id); inputString = ""; stringComplete = false; } // we wait up to 50ms to see if we have received an incoming message (if so we receive an RX_DATA interrupt) if(Pozyx.waitForFlag(POZYX_INT_STATUS_RX_DATA,50)) { // we have received a message! uint8_t length = 0; uint16_t messenger = 0x00; delay(1); // Let's read out some information about the message (i.e., how many bytes did we receive and who sent the message) Pozyx.getLastDataLength(&length); Pozyx.getLastNetworkId(&messenger); char data[length]; // read the contents of the receive (RX) buffer, this is the message that was sent to this device Pozyx.readRXBufferData((uint8_t *) data, length); Serial.print("Ox"); Serial.print(messenger, HEX); Serial.print(": "); Serial.println(data); } } In the main loop, the system waits for any of the following two events: - The user has written some text and pressed enter which is checked by the if-statement if(stringComplete). When this happened, the program will show the text in the user terminal and broadcast the text. The text is broadcasted using the following two statements: Pozyx.writeTXBufferData(buffer, length);, which puts the data in a transmit buffer, ready for transmission, and Pozyx.sendTXBufferData(destination_id);to acutally transmit the data to the device with the give destination_id. In this example, destination_idis set to 0, meaning that the message is broadcasted (everyone will receive it). - The Pozyx device has received a wireless message. This is checked by Pozyx.waitForFlag(POZYX_INT_STATUS_RX_DATA,50). The waitForFlagwaits for the RX_DATA interrupt for a maximum of 50ms. If the interrupt happened, the function returns success. At this point, the length of the message, and the network id of the device sending the message is obtained using Pozyx.getLastDataLength(&length); Pozyx.getLastNetworkId(&messenger);. On the Pozyx device, the content of the received message is stored in the RX buffer. This content can be read using Pozyx.readRXBufferData((uint8_t *) data, length);. This concludes the last example that is included in the Pozyx Arduino Library. Make sure to check out our Tutorials section where we will regularly post some new tutorials. If you have any requests for tutorials or if you have a tutorial of your own, please send us a message at info@pozyx.io.
https://www.pozyx.io/Documentation/Tutorials/chat_room
CC-MAIN-2017-22
refinedweb
1,021
58.18
Subject: Re: [boost] [uuid] Interface From: Scott McMurray (me22.ca+boost_at_[hidden]) Date: 2008-12-18 20:51:54 On Thu, Dec 18, 2008 at 13:37, Andy Tompkins <atompkins_at_[hidden]> wrote: > > Your right! Hmm. I want to be able to use lexical_cast as above, but I > also don't want a default constructor. > I think I will optionally include/exclude the default constructor with a > #define. And I think a more explicit way to convert a string > representation of a uuid to a uuid should be included. Something like > the following: > > template <typename ch, typename char_traits, typename allocator> > uuid from_string(std::basic_string<ch, char_traits, allocator> const& > s); > uuid from_string(const char* name); > uuid from_string(const wchar_t* name); > As far as I'm concerned, the "explicit way to convert a string representation of a uuid to a uuid" is spelled lexical_cast<uuid>. I really dislike the idea of some idiom that's not used anywhere else. > > class string_generator //not a good name > { > I have to say, this seems really silly. >> > // valid expression >> > // generator() - result type must be convertible to a uuid >> > template <typename Generator> >> > explicit uuid(Generator & generator); >> > >> >> Does this use the Concept defined at the end? > > Yes. > What's the result_type needed for? It seems strange to not allow a uuid(*)() to be a UUIDGenerator. Perhaps you can say "where result_type is some unspecified type with an implicit conversion to uuid", not not require it as a typedef? Though I'm still not convinced that the constructor is worth bothering with. >> >> On the assumption that an MD5 version would be a reasonable extension, >> what about templating this on the hasher, defaulting to the sha1 one? >> >> That way both the defaults would have the <>, for consistency >> (random_generator<> and name_based_generator<>). > > Good idea. But there is no md5 implementation in boost, and I'm not > planning to write one (unless there is significant demand). > I wouldn't expect you too, but I can foresee a boost.message_hash library in the future, at which point it ought to be simple to make a name_based_generator<md5>. Would be a reasonable thing for someone else to contribute, too, if they needed it. > > Good point. Maybe just random_based_generator and version_random_based. > Still a touch long-winded, but I can't think of anything better. > > This function will treat the stream a sequence of bytes and will have > the > same effect as using the ByteInputIterator version on the stream. So > each wchar_t will be treated as sizeof(wchar_t) bytes. > I think that should be up to the user. Otherwise endianness and wchar_t size differences mean it's not going to generate consistent UUIDs (such as between window's UCS-2 wchar_t and linux's UTF-32, iirc). I think it'd be better to force the user to choose between casting to char*, converting to UTF-8, using a casting_iterator, or whatever other method they like, and just allowing the 1-byte versions. > >> Would it worth be adding one for message UUID generators too? > > What do you mean by message uuid generators? > Name-Based (Oor maybe Consistent) UUID Generator constructor: Generator(uuid uuid_namespace) creation: result_type operator(ByteIteratorRange) creation: result_type operator(ByteIterator begin, ByteIterator end) ... or something like that. Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2008/12/146262.php
CC-MAIN-2019-13
refinedweb
552
56.35
Can't get the idea of StdinWrite By kcvinu, in AutoIt General Help and Support Recommended Posts Similar Content - - mojomatt Question regarding StdinWrite and Stdoutread… Here’s my setup… I’m opening a powershell session using the AutoIT Run function with the $STDIN_CHILD and $STDOUT_CHILD optional flags. I’m then sending a command using the STDINWRITE function to connect to a remote server which is a long distance away and it takes a “long” time to return results. I’m then trying to read the STDOUT stream. After this there are other STDINWRITE statements that I need to make so the STREAM hasn’t closed at this point. My question is this…How do I know for sure when all the data has been returned from the remote. - By TheDcoder Hello , I am trying simulate user input in console apps, so far this is what I have tried: #include <AutoItConstants.au3> #include <MsgBoxConstants.au3> Example() Func Example() Local $iPID = Run("test.bat", "", @SW_HIDE, $STDIN_CHILD + $STDOUT_CHILD) StdinWrite($iPID, "Banana") Local $sOutput = "" ; Store the output of StdoutRead to a variable. While 1 $sOutput &= StdoutRead($iPID) ; Read the Stdout stream of the PID returned by Run. If @error Then ; Exit the loop if the process closes or StdoutRead returns an error. ExitLoop EndIf WEnd MsgBox($MB_SYSTEMMODAL, "", "The output string is: " & @CRLF & $sOutput) EndFunc ;==>Example Code for test.bat: @echo off set /p var = "Input Var: " echo This is the var: %var% I can't write "Banana" when the the bat script prompts for input , I can't find any solution on the WWW for this... Thanks in Advance, TD -
https://www.autoitscript.com/forum/topic/178346-cant-get-the-idea-of-stdinwrite/?tab=comments
CC-MAIN-2019-39
refinedweb
266
61.87
From: Bulygin, Sergey (Bulygin_at_[hidden]) Date: 2005-08-29 02:55:52 Evaluating Boost.Typeof library with MSVC 7.1 compiler. Since this compiler has native typeof trick, BOOST_TYPEOF and BOOST_AUTO work fine by default. But with regard to future upgrade to MSVC 8.0, I want to have my TYPEOF-related code portable, i.e. registering all those user types for proper TYPEOF emulation. When I "#define BOOST_TYPEOF_COMPLIANT", nothing happens and the code proceeds working even without registering my types. I would expect BOOST_TYPEOF_COMPLIANT definition to cause compiler errors for not registered types. Here's the code snippet that I am trying to compile: #include <boost/typeof/typeof.hpp> #define BOOST_TYPEOF_COMPLIANT struct X {}; template<typename A, bool B> struct Y {}; typedef std::pair<X, Y<int, true> > Pair_t; Pair_t a; BOOST_AUTO(b, a); BOOST_AUTO(pp, Pair_t()); What do I miss here? Thank you, Sergey Bulygin Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net
https://lists.boost.org/boost-users/2005/08/13626.php
CC-MAIN-2021-49
refinedweb
173
53.17
patterns & practices and pontification So I'm back from a four day camping holiday at Cannon Beach in Oregon. Camping is always lots of fun, but at the end it's always nice to get back to a world where you don't have to worry so much about mosquitoes, sand, airbeds and that ever-so-long walk in the dark from the tent to the amenities block. Camping also means a welcome break from e-mail, but now that I'm back home I've been spending some time going through it to get ready for the week ahead. Since this was a long weekend in the United States, my e-mail pile was much smaller than usual - but there were still a few things to deal with, including the increasingly common questions "when can I get a drop of Enterprise Library for .NET 2.0", or occasionally "can I have this now please?". Unfortunately I can't answer the first question, and while I can answer the second, most people don't like the answer :-). However I do realize that I owe everyone a better explanation on what is going on, hence this blog post. The best way to start is to give a refresher course on the purpose of patterns & practices guidance. Essentially, our role is to help customers fill the "gap" between what the platform makes very easy, and what customers try to do with the platform. This gap is not new, not specific to the Microsoft platform, and most likely will never disappear (although it does change over time). For example, when a new version of a development platform (such as .NET) comes out, it will offer better support for certain scenarios that used to require lots of custom code. However, history has shown that there’s always more to do, and customers will start to push the boundaries by moving into higher value scenarios that nobody could have predicted. So as soon as parts of the gap are obliterated by advances in the platform, new, "higher level" gaps start appearing in different places. Another important property of p&p guidance is that we don't fill the gap with whatever we feel like - we place a lot of importance on demonstrating the best practices of the platform. For code-based guidance such as Enterprise Library, we know that developers won't just use the code as-is, they will also extend the code, learn design techniques from it and copy parts of it into their own projects. So while there are many times when developers choose to rely on nasty hacks or techniques left over from older platform versions, we try really, really hard not to do this for p&p guidance. So, after this long and winding prologue, what's up with Enterprise Library for .NET Framework 2.0 and Visual Studio 2005? The short answer is that it's taking us longer than expected to get a useful preview build - but you probably already know that since I have previously set expectations that we would have a preview available around now. So let me explain what is making this hard. Remember I summarized the guidance creating process with figuring out "what is the gap" and "what do we fill it with?". This is much, much more than taking the first release of Enterprise Library, recompiling it in Visual Studio 2005 and fixing the handful of breaking changes. .NET 2.0 and VS2005 both include some significant improvements which change both sides of our "equation". First, let's look at the nature of the "gap" in .NET 2.0. Certain things which were quite tricky to do in .NET 1.1 (which led to the application blocks and Enterprise Library) are much simpler using just the platform. For example, you can now read and write configuration using the System.Configuration namespaces; ADO.NET lets you manage connections in configuration and provides base classes that are common across different managed providers; and ASP.NET extensively uses the familiar "factories and providers" patterns for security and other useful functionality. So many - but not all - of the key requirements addressed by Enterprise Library have become addressed by the new platform. This means that the gap is getting smaller in one dimension. But is it growing in another dimension? Remember I said that as the platform advances, customers tend to push the limits and create new gaps. This will probably happen for .NET 2.0 - but it is too early to predict what this will look like. As a result, for the first release of Enterprise Library for .NET 2.0 we will assume that the important customer scenarios are the same as what we support in our current release. When we learn what this new gap looks like, we will plan how our guidance can help fill it. Next, let's look at what we fill the (remaining) gap with. While there are places where the gap looks pretty similar in .NET 1.1 and .NET 2.0, the new platform includes some new building blocks that change the way that good solutions are built. This includes small but significant cross-cutting features like generics and partial classes, as well as more substantial improvements in individual feature areas such as configuration or security. For example, ASP.NET 2.0 contains some new providers for security features such as authentication and roles, while it has less to say about other security features such as authorization. If we moved the entire Security Application Block forward in its current form, it would likely overlap with these new features and provide an inconsistent approach for coding and configuration. Not only would this be poor guidance, it would likely confuse people who tried to mix Enterprise Library's security techniques with the new platform functionality. So it's taking us some time to reconcile our requirements with the platform's improved capabilities. Now while this is making our lives a bit complicated, this is actually exactly what we want to happen. Whenever we kick off a new project, we include a "deprecation plan", which specifies how and when the capabilities will be absorbed into the platform. Being part of the platform means better integration, tooling and support, and also frees up the p&p team to focus on the latest, greatest challenges. I can already hear you asking "what does this mean for backward compatibility?". Unfortunately it's too early to say much (since we don't know enough yet), but we understand how painful breaking changes are. Our goal is to protect your business logic as much as we can from breaking changes, as long as we are demonstrating best practices on the use of the platform. Most likely, some parts of the new Enterprise Library will appear almost identical to the original version at the public API level, while others will need to change more substantially (in which case we will publish migration guidance - from previous blocks to the .NET Framework 2.0 or from a previous block to a new block). We plan on sharing more about the shape of each of the updated blocks on the community site, so stay tuned. Finally, I can hear you saying "OK that makes sense - and I'm glad I'm not you - but what am I supposed to do in the meantime? I'm already using .NET 2.0 beta 2 now!" (should I have considered a career as a psychic? :-). We originally considered doing a minimalist port of Enterprise Library (recompiling and fixing the breaking changes), but decided it would be better to wait until we have something that is more representative of our planned direction. We know that other people have undertaken a similar porting effort (one example, that we haven't reviewed, is here) - but we were concerned about a p&p branded version of the same as this doesn't represent true "guidance" for .NET 2.0. However, since our version is taking longer than expected to get ready, we are reconsidering our position on this. Over the next couple of weeks we expect to learn enough to make some firmer commitments. Sorry for the long post - but I hope this helps explain our current situation. If not, you can always go camping. This posting is provided "AS IS" with no warranties, and confers no rights.
http://blogs.msdn.com/tomholl/archive/2005/05/31/423655.aspx
crawl-002
refinedweb
1,400
60.65
Hello everyone. I am trying to teach myself the very basics of the Brian neuron simulator before attempting to modeling realistic networks. Any of you guys know how to use it? Specifically, the first exercise I am attempting is: dx/dt = 1 + x - y - x^2 - x^3 dy/dt = eps(-1 + (1 - 4alpha)x + 4xy) where x is voltage, y is a response variable, eps is small, and alpha is a parameter to be experimented with. Here is my attempted code thus far: from brian import * eps = 0.0001 alpha = 0.5 equs = Equations(''' dV/dt = (1 + V - y - V**2 - V**3) dy/dt = eps*(-1 + (1 - 4*alpha)*V + 4*V*y) ''') G = NeuronGroup(N=1, model=equs) M = StateMonitor(G, 'V', record=0) run(50*msecond) plot(M.times/ms, M[0]) xLabel('t') yLabel('V') show() This produced the following, and rather expected, error: [code] raise TypeError, "Invalid equation string: " + line TypeError: Invalid equation string: dV/dt = (1 + V - y - V2 - V3)[/code] I have studied the Brian documentation and tutorials, but as it's a pretty new project, there's not always much on the subject for us rookie programmers. Specifically, I have three questions about this: How do I get the equations into Brian? I keep getting a dimension mismatch, which makes sense considering that V and V^2, for example, are clearly not the same units. But how do I resolve this? Should I, for instance, write the V^2 part as "V**2/mV"? What about the 4Vy term? How do I plot V vs y? The Brian tutorial is very clear how to plot V vs. t, but not V vs. y (or vice versa). Are there some highly-trafficked Brian forums out there, or is that allowed to be discussed here? Thanks!
https://www.daniweb.com/programming/software-development/threads/474924/help-with-brian-neuron-simulator-basics
CC-MAIN-2022-33
refinedweb
303
64.2
Background In a previous post I wrote about comparing Django’s Q object instances. The original code was Python 2 with unittest and was due for an update. The previous issue with comparing Django’s Q objects remains the same: Django’s Q object does not implement __cmp__ and neither does Node which it extends (Node is in the django.utils.tree module). Unfortunately, that means that comparison of Q objects that are equal fails. A simple Python 3 solution The following is a Python 3.6 assertion helper for use with pytest that uses the original strategy of comparing the string versions of the Q objects. from django.db.models import Q def assert_q_equal(left, right): """ Test two Q objects for equality. Does is not match commutative. Args: left (Q) right (Q) Raises: AssertionError: When - * `left` or `right` are not an instance of `Q` * `left` and `right` are not considered equal. """ assert isinstance(left, Q), f'{left.__class__} is not subclass of Q' assert isinstance(right, Q), f'{right.__class__} is not subclass of Q' assert str(left) == str(right), f'Q{left} != Q{right}' This time the helper is just a function rather than a mixin for unittest.TestCase. isinstance is used for comparison so that any instance of a class derived from Q can also be matched. The assertions have secondary expressions in the form of f-strings to give helpful output without raising a custom assertion. When two Q instances do not match, pytest shows the following output: ______________________ ==================== The important thing is to adjust your assertion helpers to best fit the needs of your test suite and team.
https://jamescooke.info/comparing-django-q-objects-in-python-3-with-pytest.html
CC-MAIN-2021-17
refinedweb
273
64
If you're a spreadsheet ninja, I can only assume you'll want to start your Jupyter/Python/Pandas journey by importing a CSV into your Jupyter notebook. Let me just say that this is very easy to do, and I'm excited to show you. Hit that easy button and let's do it! Table of Contents: Getting started Imports Read CSV Do something to the CSV Export CSV Step 1: Getting started First, you'll need to be set up with Python, Pandas, and Jupyter notebooks. If you aren't, please start here Step 2: Imports Next, you'll set up a notebook with the necessary imports: import pandas as pd Pandas is literally all you need for this operation, and it is often imported as pd. You'll use pd as a prefix for pandas operations. This is what your notebook should look like: Step 3: Read CSV Next, you'll simply ask Pandas to read_csv, and then assign your spreadsheet a variable name. Sorta like this: variable_name = pd.read_csv(‘file path') The read_csv is a Pandas method that allows a user to create a Pandas Dataframe from a local CSV. You can read more about the operation here at, where you can find all the Pandas documentation you'll ever want. Remember, we use the prefix pd to run any pandas operations: spreadsheet = pd.read_csv('/Users/davidallen/Downloads/file_name.csv') But first, we'll need a CSV to read! Let's use something from kaggle.com. I think this Healthy Lifestyle Cities Report is interesting, so let's use that one. If you don't have a Kaggle account, go ahead and register. It's a worthwhile site to know about. Loads of datasets to peruse. Then, just hit the download button to grab all the project resources. Open the zip file and you'll find your CSV in your downloads folder (or where ever your downloads go). Make note of the location and filename. Now, let's import that CSV! spreadsheet = pd.read_csv('/Users/davidallen/Downloads/healthy_lifestyle_city_2021.csv') You can use the tilda (~) and then a backslash(/) in front of “Desktop” or “Documents” or “Downloads” before hitting “tab” to get some autocomplete help with the file path. It should look like this before you hit tab: spreadsheet = pd.read_csv('~/Desktop') spreadsheet = pd.read_csv('~/Downloads') spreadsheet = pd.read_csv('~/Documents') And then your computer should autocomplete the path for you, like this: spreadsheet = pd.read_csv('/Users/davidallen/Desktop/') spreadsheet = pd.read_csv('/Users/davidallen/Downloads/') spreadsheet = pd.read_csv('/Users/davidallen/Documents/') Then, just start typing out the file name and hit “tab” again to autofill the rest of the path. See it in action: Step 4: Do something to the CSV Now that we've loaded our CSV into our notebook, it's time to do something with the CSV. First, let's just take a look at the first 5 rows with a very popular command: head() . spreadsheet.head() This will show the first 5 rows (including column headers) of our DataFrame. You can use the tab again to autocomplete the name of your variable spreadsheet Just start typing spread and then hit tab. Looks like this: Very quickly, let's just sort the DataFrame by Sunshine hours(City), assign the sorted result to a new variable, and then we'll export this new CSV. We'll assign the sorted DataFrame to a new variable df df = spreadsheet.sort_values('Sunshine hours(City)',ascending=False) .sort_values() does exactly what it sounds like. Just pass in the column name (or column names), and then specify whether or not you want to sort ascending or not. Setting ascending=False will sort the DataFrame in a descending manner. Cool. Next, we'll complete the tutorial by exporting the sorted CSV. Step 5: Export the CSV Exporting is as simple as importing. Just use the pandas DataFrame method to_csv to save your df to local storage: df.to_csv('/Users/davidallen/Desktop/new_csv.csv') Easy! Just imagine the possibilities.
https://plainenglish.io/blog/how-to-import-a-csv-into-a-jupyter-notebook-with-python-and-pandas
CC-MAIN-2022-40
refinedweb
666
65.62
We're going to create a very simple object class that will print a "Hello" message to the screen when called. This class will have two different methods that will do the same thing, though we'll vary the messages they print a bit so that we can see which one is doing the work. Here's our class: (download HelloClass.Java) public class HelloClass{ /** * sayHello() prints "Hello!" to the Java console output. */ public void sayHello(){ System.out.println("Hello!\n"); } /** * doHello() prints "Hello, hello!" to the Java console output. * It's static, so you don't need to instatiate a HelloClass * object to use it. */ public static void doHello(){ System.out.println("Hello, hello!\n"); } } // End of HelloClass The two methods we have to print messages are sayHello() and doHello(). To use sayHello(), we need to have a HelloClass object created, then call that object's sayHello() method. doHello(), however, is a static method. This means is belongs to the class, not to any object of the class. So we can use it without any HelloClass objects being created first. Here's a class that uses these methods as described: (download UseHello.java) public class UseHello{ public static void main(String[] arg){ // We can use doHello() without a HelloClass object: HelloClass.doHello(); // call the HelloClass's doHello() method. // But we need to create a HelloClass object to use sayHello(): HelloClass hello=new HelloClass(); hello.sayHello(); // call hello's sayHello() method. } } // End of UseHello. If we try to call sayHello() without first creating a HelloClass object, like this: HelloClass.sayHello(); then we'll get the dreaded "calling a non-static method from a static context" error message. That's letting you know that you need to instantiate (or create) a HelloClass object first, then tell that object to call its method. Static methods are useful for things like general arithmetic and calculation or other methods that might be used in a way where state information is unimportant. But beware, it's easy to create static methods when what's really wanted is an object that does what you want. Files available for download through:.
http://beginwithjava.blogspot.com/2011/05/your-own-java-classes.html
CC-MAIN-2018-39
refinedweb
354
67.76
original in es Angel Lopez es to en Javier Palacios Angel is finishing his studies of Computer Engineering. Now he is working as teacher for Sun Microsystems, teaching Solaris and network administration. Recently has published as a co-author with Ra-Ma the book entitled Internet protocols. Design and implementation on Unix systems. His main interests are network, security, systems/networks unix programming and, very recently, Linux kernel hacking is reducing his time for sleep ;) This article attempts to be an introduction to multicast technologies on TCP/IP networks. It deals with the theoretic concepts of multicast communication, and details the Linux API that we can use for programming multicast applications. The kernel functions implementing this technology are also shown, to complete the global view of the multicast support under Linux. The article finishes with a simple C example on socket programming, where the creation of a multicast application is illustrated. When you try to reach a host (interface) within a network, you can use three different kinds of address: Multicast addresses are useful when the information receiver is not only one host, and we do not want to produce a network broadcast. This scenario is typical in those situations that require the sending of multimedia information (real-time audio or video, for example) to some hosts. Thinking in bandwidth terms, these cases are not the best for a unicast send to every client which wants to receive the multimedia emission. Neither is a broadcast the best solution, mainly if any of the clients are located out of the local subnet which origins the emission. As the reader will probably know, the IP address space is distributed in three groups of classes of addresses. A, B and C address classes. There is a fourth class (D) reserved for multicast address. IPv4 addresses between 224.0.0.0 and 239.255.255.255 belong to D class. The 4 most significant bits of the IP address allow values between 224 and 239. The other 28 bits, less significant, are reserved for the multicast group identifier, as shown in the figure below: At the network level, the IPv4 multicast addresses should be mapped over the physical addresses of the type of network where we are working. If we work with an unicast network address, we should get the associated physical addresses using the ARP protocol. In the case of multicast addresses, ARP is not usable, and the physical address must be retrieved in a different way. There are some RFC documents dealing with the method to perform this mapping: There are some special multicast IPv4 addresses: The table below shows the full multicast address space, with the usual names for each address range and their associated TTL's (time to live counter in ip packet). Under multicast IPv4, the TTL has double meaning. As the reader probably nows, it controls the life-time of a datagram in the network to prevent any infinite loop in case of misconfigured routing tables. Working with multicast, the TTL value defines also the scope of the datagram, i. e., how far it will travel in the network. This allows a scope definition based on the datagram category. Within a LAN, a network interface on a host will send to the upper layers all those packets that need to go to the host as destination. These packet will be those where the destination address are the interface physical addresses or those with a broadcast destination address. If the host has joined to a multicast group, the network interface will recognize also those packets destined to that group: all those with a destination address corresponding to the multicast group with host membership. Therefore, if the host interface has the physical address 80:C0:F6:A0:4A:B1 and has joined the multicast group 224.0.1.10, the packets that will be recognized as belonging to the host will be those with one of the next destination address: The routers also sent IGMP messages to the group 224.0.0.1 requesting every host information about the groups they are subscribed to. A host, after receiving such a message, sets a counter to a random value, and will reply when the counter goes to zero. This prevents all hosts replying at the same time, producing a network overload. When the host replies, it sends the message to the multicast address of the group and every other host with group membership will see the reply, and will not reply itself, as long as one subscribed host is enough for the subnet router to deal with multicast messages for that group. If all hosts subscribed to a group have resigned, no one will reply, and the router will decide that no host is actually interested in such a group, and will finish the routing of the corresponding messages into the subnet. Another option implemented with IGMPv2, is the communication of the resign coming from the host, sending a message to address 224.0.0.2. With previous experience in sockets programming, the reader will only find five new socket operations to deal with multicast options. Functions setsockopt() and getsockopt() will be used to establish or read the values of these five options. The table below shows the available options for multicast, with their managed data types and a brief description: The ip_mreq struct is defined in the header file <linux/in.h> as described below: struct ip_mreq { struct in_addr imr_multiaddr; /* IP multicast address of group */ struct in_addr imr_interface; /* local IP address of interface */ };And the multicast options in that file are: #define IP_MULTICAST_IF 32 #define IP_MULTICAST_TTL 33 #define IP_MULTICAST_LOOP 34 #define IP_ADD_MEMBERSHIP 35 #define IP_DROP_MEMBERSHIP 36 A process can join to a multicast group sending this option over a socket with the function setsockopt(). The parameter is a ip_mreq struct. The first structure field, imr_multiaddr, contains the multicast address we want join to. The second field, imr_interface, contains the IPv4 address of the interface we will use. Using this option a process can resign from a multicast group. The fields of the ip_mreq struct are used in the same manner as in the previous case. This option allows us to fix the network interface that the socket will use to sent the multicast messages. The interface will be given in the ip_mreq as in the previous cases. Establishes the TTL (Time To Live) for the datagrams with the multicast messages sent using the socket. Default value is 1, meaning that the datagram will not go beyond the local subnet. When a process sends a message for a multicast group, it will receive the messages if his interface is joined to the group, in the same way that it will be received if its origin is any other place in the network. This option allows to activate or deactivate this behavior. To test the ideas shown in this article, we will show a simple example, where there is a process that submits messages to a multicast group, and some processes associated to this group are receiving the messages, showing them on the screen. The next code implements a server sending to the multicast group 224.0.1.1 everything going through its standard input. As can be seen, there is no need of any special action to sent information to a multicast group. The destination group addresses are enough. Loopback and TTL options could be changed, if their default values were not appropriate for the application under development. The standard input is sent to multicast group 224.0.1.1 #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <stdio.h> #define MAXBUF 256 #define PUERTO 5000 #define GRUPO "224.0.1.1" int main(void) { int s; struct sockaddr_in srv;; } while (fgets(buf, MAXBUF, stdin)) { if (sendto(s, buf, strlen(buf), 0, (struct sockaddr *)&srv, sizeof(srv)) < 0) { perror("recvfrom"); } else { fprintf(stdout, "Enviado a %s: %s\n", GRUPO, buf); } } } The code below is the client side, which receives the information submitted to the multicast group by the server. The received messages are shown on standard output. The only peculiarity of this code is the establishment of the IP_ADD_MEMBERSHIP option. The remaining code is the standard one for a process which needs to receive UDP messages. #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #define MAXBUF 256 #define PUERTO 5000 #define GRUPO "224.0.1.1" int main(void) { int s, n, r; struct sockaddr_in srv, cli; struct ip_mreq mreq;; } if (bind(s, (struct sockaddr *)&srv, sizeof(srv)) < 0) { perror("bind"); return 1; } if (inet_aton(GRUPO, &mreq.imr_multiaddr) < 0) { perror("inet_aton"); return 1; } mreq.imr_interface.s_addr = htonl(INADDR_ANY); if (setsockopt(s,IPPROTO_IP,IP_ADD_MEMBERSHIP,&mreq,sizeof(mreq)) < 0) { perror("setsockopt"); return 1; } n = sizeof(cli); while (1) { if ((r = recvfrom(s, buf, MAXBUF, 0, (struct sockaddr *) &cli, &n)) < 0) { perror("recvfrom"); } else { buf[r] = 0; fprintf(stdout, "Mensaje desde %s: %s\n", inet_ntoa(cli.sin_addr), buf); } } } As we showed above, when a process wants to join a multicast group, it uses the setsockopt() function to establish the option IP_ADD_MEMBERSHIP at the IP level. The actual implementation for this function can be found on /usr/src/linux/net/ipv4/ip_sockglue.c. The code executed within the function to set this option or the IP_DROP_MEMBERSHIP one is: struct ip_mreqn mreq; if (optlen < sizeof(struct ip_mreq)) return -EINVAL; if (optlen >= sizeof(struct ip_mreqn)) { if(copy_from_user(&mreq,optval,sizeof(mreq))) return -EFAULT; } else { memset(&mreq, 0, sizeof(mreq)); if (copy_from_user(&mreq,optval,sizeof(struct ip_mreq))) return -EFAULT; } if (optname == IP_ADD_MEMBERSHIP) return ip_mc_join_group(sk,&mreq); else return ip_mc_leave_group(sk,&mreq); The very first lines of code check that the input parameter, the ip_mreq struct, has a correct length, and it is possible to copy it from user to kernel areas. Once we get the parameter value, the function ip_mc_join_group() is called to join a multicast group, or ip_mc_leave_group() if we want to resign. The code for these functions is found at /usr/src/linux/net/ipv4/igmp.c. To join a group, the source code is commented below: int ip_mc_join_group(struct sock *sk , struct ip_mreqn *imr) { int err; u32 addr = imr->imr_multiaddr.s_addr; struct ip_mc_socklist, *iml, *i; struct in_device *in_dev; int count = 0; At the very beginning we check, using the MULTICAST macro, that the group address are within the ranges reserved for multicast addresses. It´s enough to check that the most significant byte on the IP address is set to 224. if (!MULTICAST(addr)) return -EINVAL; rtnl_shlock(); After the verification, a network interface is set up to deal with the multicast group. If it is not possible to be accessed by an index to the interface, as should be under IPv6, the function ip_mc_find_dev() is called to find the device associated to a specified IP address. We will assume for the remaining of the article that this is the case, because we are working under IPv4. If the address were INADDR_ANY, the kernel should find itself the network interface, reading the routing table to choose the better interface taking into account the group address and the definition of the routing tables. if (!imr->imr_ifindex) in_dev = ip_mc_find_dev(imr); else in_dev = inetdev_by_index(imr->imr_ifindex); if (!in_dev) { iml = NULL; err = -ENODEV; goto done; } Then we reserve memory for a ip_mc_socklist struct, and each group address and interface associated to the socket are compared. If any entry previously associated to the socket matches, we jump out of the function, because it does not make sense to do a double association to a group and interface. If the network interface addresses were not INADDR_ANY, the corresponding counter is incremented before the function ends. iml = (struct ip_mc_socklist *)sock_kmalloc(sk, sizeof(*iml), GFP_KERNEL); err = -EADDRINUSE; for (i=sk->ip_mc_list; i; i=i->next) { if (memcmp(&i->multi, imr, sizeof(*imr)) == 0) { /* New style additions are reference counted */ if (imr->imr_address.s_addr == 0) { i->count++; err = 0; } goto done; } count++; } err = -ENOBUFS; if (iml == NULL || count >= sysctl_igmp_max_memberships) goto done; If we arrive at this point, this means that a new socket will be linked to a new group so a new entry must be created and linked to the list of groups belonging to the socket. The memory was reserved in advance, and we only need to set the correct values for the various fields of the involved structures. memcpy(&iml->multi,imr, sizeof(*imr)); iml->next = sk->ip_mc_list; iml->count = 1; sk->ip_mc_list = iml; ip_mc_inc_group(in_dev,addr); iml = NULL; err = 0; done: rtnl_shunlock(); if (iml) sock_kfree_s(sk, iml, sizeof(*iml)); return err; } The function ip_mc_leave_group() is in charge to resign from a multicast group, and is much simpler than the previous function. It takes the interface addresses and the group, and searches them among the entries related to the actual socket. Once they have been found, the number of references is decremented, as there is one less process associated to the group. If the new value is zero, the counter itself is deleted. int ip_mc_leave_group(struct sock *sk, struct ip_mreqn *imr) { struct ip_mc_socklist *iml, **imlp; for (imlp=&sk->ip_mc_list;(iml=*imlp)!=NULL; imlp=&iml->next) { if (iml->multi.imr_multiaddr.s_addr==imr->imr_multiaddr.s_addr && iml->multi.imr_address.s_addr==imr->imr_address.s_addr && (!imr->imr_ifindex || iml->multi.imr_ifindex==imr->imr_ifindex)) { struct in_device *in_dev; if (--iml->count) return 0; *imlp = iml->next; synchronize_bh(); in_dev = inetdev_by_index(iml->multi.imr_ifindex); if (in_dev) ip_mc_dec_group(in_dev, imr->imr_multiaddr.s_addr); sock_kfree_s(sk, iml, sizeof(*iml)); return 0; } } return -EADDRNOTAVAIL; } The other multicast options that we listed above are very simple, because they just set some values in the data fields of the internal structure that is associated to the socket we are working with. These assignments are performed directly by the function ip_setsockopt().
http://www.linuxfocus.org/English/January2001/article144.meta.shtml
CC-MAIN-2016-36
refinedweb
2,295
51.89
Chris Brody created CB-623: ------------------------------ Summary: Logger functionality separated from (debug) console Key: CB-623 URL: Project: Apache Callback Issue Type: Improvement Components: CordovaJS, Docs, iOS Affects Versions: 1.6.1 Environment: In discussion from CB-611 it is a bad idea to mix logger level functionality with HTML5 console log Reporter: Chris Brody Assignee: Filip Maj Fix For: Master After a long discussion with Patrick Mueller in CB-611 it is now clear to me that it is a bad idea to mix extra logger level functionality with {{console}} log functionality. The existing {{console}} object (or {{window.console}} which is equivalent) was already emulating the HTML API for console.log, however some changes that only work in the iOS version are adding extra functions that are not HTML compatible. So if users start writing code that uses extra functions in the {{console}} or {{window.console}} namespace that code will start throwing exceptions if ported or reused in a pure HTML(5) application. Patrick Mueller proposed an excellent idea in CB-611 to add a new Javascript object like {{cordova.logger}} to put the functionality related to logging. The primary purpose should be for plugin authors to log things that may be important for debugging applications. So the {{console}} (or {{window.console}}) object can be remain with a fully HTML-compliant API. Also, I think there is some agreement that having a built-in plugin called "Debug Console" (with the space in the middle) should be fixed (CB-611/CB-617). Patrick Mueller suggested that we call the plugin something like "Logger" and I really like that idea. It is positioning a lower-level logging facility, that can be called by a higher-level {{console}} API implementation. I hereby leave this issue together with CB-611 as well as CB-617 CB-618 CB-619 open for discussion. -- This message is automatically generated by JIRA. If you think it was sent incorrectly, please contact your JIRA administrators: For more information on JIRA, see:
http://mail-archives.apache.org/mod_mbox/incubator-callback-dev/201205.mbox/%3C595072481.15361.1335913732505.JavaMail.tomcat@hel.zones.apache.org%3E
CC-MAIN-2015-27
refinedweb
333
54.02
An Approach to Pluggable Griffon Applications If I were someone evaluating the existing Swing desktop frameworks, I wouldn't hesitate to choose the NetBeans Platform over Griffon or Spring RCP—for one very specific reason: any application built atop the NetBeans Platform is inherently extensible. John O'Conner's definition of extensibility applies here: "An extensible application is one that you can extend easily without modifying its original code base." In this sense, a plugin is not what Grails understands a plugin to be. A Grails plugin is applicable to a developer making use of the Grails framework. For example, the Grails Wicket plugin lets users of Grails incorporate Wicket view technology into the development of a Grails application. I imagine that the Griffon creators have the same definition of "plugin" in mind. Plugins for users of a framework are incredibly useful—users of Grails and, at some point, Griffon, are not limited to the original code that the Grails (and Griffon) creators originally provided, nor do they need to wait for the next release of the framework before making use of their favorite technology in combination with Grails (or Griffon). They're able to create a plugin that extends the Grails (or Griffon) framework and can then merrily continue creating the application of their dreams using the technologies that they're personally most comfortable with. Those plugins, though, are not the ones I have in mind here. I mean end-user plugins, such as those that users of Firefox can plug into Firefox to add new functionality to it. (Here's a nice opportunity for me to plug the DZone Voting plugin for Firefox. Try it, try it now! It's great.) Similarly, unlike the Griffon framework (and unlike Spring RCP), the NetBeans Platform lets you extend existing applications without changing the original code base, by creating plugins. Does this current gap in Griffon (and Spring RCP) functionality mean it should not be used? Not at all. Since both Griffon and Spring RCP let you create good old Java applications, you can use the JDK 6 java.util.ServiceLoader class and, without the Griffon (and Spring RCP) creators needing to do anything else, you're able to let users of applications built atop these frameworks extend it too! In addition, in each case there are certain benefits in using the ServiceLoader class in these two frameworks (the benefits being distinct and particular to each) that the NetBeans Platform cannot, at least on the face of it, benefit from. However, the NetBeans Platform doesn't make use of the ServiceLoader class, it has an objectively superior approach (which could be reused in Griffon or Spring RCP, by the way), but that's a different story. The short point of this whole story is that you can already create extensible applications in Griffon (and in Spring RCP, but I'll provide a full scenario around that another day). Here's a condensed step-by-step generic approach to working with ServiceLoader: - Create a service. A service is a set of classes that exposes features via a public interface. - Create a service provider. A service provider provides one or more implementations of the service. In order to provide implementations of the service, the service provider needs only to have the JAR that defines the service on its classpath. In other words, the service and the service provider can be (but do not have to be) in different JARs. The service provider is sometimes referred to as an 'extension point'. The service provider can also be seen as a 'plugin'. - Publish the service provider. A provider configuration file needs to be placed in the service provider JAR's META-INF/services folder. The name of the file needs to match the FQN of the service. Each service provider made available by the JAR needs to be named in the file, by its FQN. - Distribute the service provider. The service provider JAR needs to be put on the classpath of the application that needs to be extended. The JAR that contains the service needs to be on that classpath too. - Load the service. Within the application that needs to be extended, a ServiceLoader needs to have been defined. The ServiceLoader will load the service. Then methods defined on the service (i.e., the interface) are invoked, which are called on each of the available service providers, if they have been published as described in step 3 above. Via the above approach, the application has no direct relationship to any of the service providers. If a service provider isn't there, it simply isn't loaded. A default service provider can be created to handle the situation where no service providers are available. But... can this work with Groovy? If the answer is "Yes", then Griffon applications are extensible, aren't they, since Griffon is nothing more than strictly structured Groovy code? And what could be the answer other than "Yes", given that Groovy is Java? And that right there is the benefit that Griffon has over the NetBeans Platform when it comes to creating extensible applications—you have the additional option of using Groovy to do so. (However, I guess that one could probably also create NetBeans Platform applications in Groovy, but lets leave those ruminations for another day too.) I reckon the ServiceLoader Javadoc is very good and so I'll use the example described there in my scenario below. So, based on that (maybe read it all, if you haven't yet, before going further) here's a simple scenario of how everything described above fits together concretely in the context of Griffon: - Create the application. Run "griffon create-app" and create an application called "EncoderSales". Here's the application (at least, here's how it looks for me in NetBeans IDE, via my tweaked Grails plugins for NetBeans IDE): So, this is the application that we will deliver to our users. Let's say that it will let the user choose an encoder (for something or other) from a list and then (at some further stage in the application, not covered here) somehow purchase it. However, we want to make it possible for the application to be extensible, so that providers of other encoders can add their encoders to the list. The encoder market is large and growing, one assumes, so we need to let the application be supplemented externally with additional encoder offerings. That's a pretty realistic scenario. - Create the service. So, and this is unavoidably step 1 of the whole process, we'll create a service. To that end, create a brand new Java application called 'CodecSetService', with an interface named 'com.example.CodecSet' (which is the name of the example service in the Javadoc). The service will define what the set of encoders will consist of, in order for a new encoder to be allowed to be added to the application. The service could also be created in Groovy, that's neither here nor there, whatever you're comfortable with: package com.example; public interface CodecSet { public String getEncoder(); } To really simplify things, we'll have one method instead of two and we'll use strings instead of the Encoder/Decoder return types referred to in the Javadoc example. - Create the service provider. Next, we'll create our first service provider. Remember that a service provider is an implementation of a service. We will create it in a new Java application. Again, we'll follow the example from the Javadoc and call our service provider 'StandardCodecsProvider', with the implementing class being called 'com.example.impl.StandardCodecs'. Again, for now we'll use a Java class for the service provider too. To fulfil all the requirements for creating a service provider, the 3 bullets that follow will result in a Java application that looks as follows: - First, build the service and put its JAR on the classpath of the service provider's application. Now that the service is available to the service provider, the latter can implement the former. - We'll create a very simple implementation (how could it be otherwise, since we're simply returning the name of an encoder): package com.example.impl; import com.example.CodecSet; public class StandardCodecs implements CodecSet { @Override public String getEncoderName() { return "Standard Encoder"; } } - Finally, in the service provider's application, create a folder structure within 'src', named 'META-INF/services'. Within it, create a file, without any extension, named 'com.example.CodecSet'. Inside that file, write one line and one line only, the content being 'com.example.impl.StandardCodecs' (without the quotes around it). - Put the service provider on the application's classpath. Now, put both JARs that you've created (i.e., the service JAR, as well as the service provider JAR) in the Griffon application's "lib" folder. Your EncoderSales application should now look as follows: - Load the service interface. Now we simply need to load the service interface into our Griffon application! Here we go—we use generics to specify the type and are then able to call the "getEncoderName()" on each service provider that is on our classpath and that has been registered according to the META-INF/services approach, as described above: import com.example.CodecSet class EncoderSalesController { def view def i = 1 def loadService(){ ServiceLoader<CodecSet> sl = ServiceLoader.load(CodecSet.class) sl.each() { view.encoderList.text = view.encoderList.text + "\n" + i++ + ". "+ it.getEncoderName() } } } We call the above from Startup.groovy: def rootController = app.controllers.root rootController.loadService() And 'view.encoderList.text' in the controller? What's that all about? That refers to a JTextArea in the view, which is defined as follows: application(title:'Encoder Sales', pack:true, locationByPlatform:true) { textArea( id:'encoderList', rows:10, columns:30 ) } Run the application. Isn't it beautiful? Here it is: It's clearly time to distribute your application to all your customers! Do so now. - Extend the distributed application. Good, your wonderful application is now distributed to your users and they're making use of it and telling you how wonderful it is. Then comes the moment when they'd like to extend it and, for whatever reason (you don't want to create the requested features in your original code base, or you don't have the time to do so, or the customer has some private features that need to be added, i.e., features that are germane to the customer and irrelevant to all the other users). In other words, there's a new encoder to be added to the list. Time to create a new service provider: - Put the service on your new service provider's classpath. - Implement the service: package com.example.impl; import com.example.CodecSet; public class SpecialCodecs implements CodecSet { public String getEncoderName() { return "Special Encoder"; } } - Publish the service provider via MET-INF/services. Your service provider should look very similar to the one discussed earlier, only the implementation is different (and that's exactly the point): - Distribute the new JAR to to the end users, who need to put it on their EncoderSales application's classpath. Below you can see that I have three service provider JARs, together with the service JAR: - When the application restarts (which is just one area where the NetBeans Lookup class is superior, in that it has a handy Listener, unlike the ServiceLoader, which means that if the classpath changes dynamically, you will be able to unload and reload objects, which lets you hot-reload JARs without restarting the application, as described by Tim here on Javalobby), i.e., via the reloaded service the new service providers, i.e., those that are on the classpath and registered correctly, are invoked, and they'll provide new entries in the list, each potentially provided by different service providers, all simply as a result of the ServiceLoader loading the service and then having the methods invoked on the service providers: Only the fourth bullet above, i.e., distribution, is slightly inconvenient. (On the other hand, that's how it works for the Lobo Browser too, last time I checked.) Your granny Smith end user isn't very happy receiving JARs and being told to put them in special places. So, why not create a Plugin Manager in your 'EncoderSales' application? Add a menu item that says 'Plugins' and, when selected, a dialog appears that lets the user browse for the JAR. When they click 'Install', the JAR will simply be put into one of the application's folders (a user directory or even in the installation directory itself), so long as it is on the classpath, which is all that is needed for the ServiceLoader in the application to call its 'getEncoderName' method. (Perhaps the Griffon framework could provide this kind of functionality itself, so that the Griffon user could via a few lines of code simply enable the presence of a Plugin Manager, which is something the NetBeans Platform allows you to do too.) (By the way, in case you're wondering about this, you can also specify the order of instantiation as well.) And that's how Griffon application are, in fact, extensible. (And, as one should be able to see, Spring RCP too.) So, returning to my original (slightly provocative) statement, extensibility is not a reason for choosing the NetBeans Platform over Griffon or Spring RCP. Yes, there's a little bit of extra work involved, at the moment anyway, but isn't that always the case with plugins? Postscript: The John O'Conner quote at the start of this story comes from his excellent article Creating Extensible Applications With the Java Platform, which you should definitely read if you haven't already! Sep 20 2008, 01:12:38 PM PDT Permalink Time for a brief plug for a little tool I wrote which is similar to ServiceLoader but more powerful: The main advantages are that (1) you can use annotations to register services, rather than create separate metadata files; (2) you can inspect annotation metadata from e.g. EncoderSalesController without being committed to loading every service class right away, which could matter if there are dozens of them and startup time is a concern; (3) you can register services from fields or factory methods, not just whole classes. A future version of the NetBeans Platform may include a similar facility (details still TBD). I don't know yet whether the annotation processor works correctly on .groovy files, but it should at least work to define plug-ins in Java yet load them from Groovy. BTW with either ServiceLoader or SezPoz, if you want to support dynamic plug-in reloading, just pass a custom ClassLoader. The main difference from NetBeans' Lookup is that there is no listener facility; but if you know that a plug-in has been reloaded, you can perhaps just reload all the services. (Lookup will attempt to preserve existing service instances if they can still be loaded from the same defining ClassLoader, which gives better performance when there are a lot of services and only a few modules are being reloaded.) Posted by Jesse Glick on September 22, 2008 at 07:07 AM PDT #
http://blogs.sun.com/geertjan/entry/an_approach_to_pluggable_griffon
crawl-002
refinedweb
2,524
61.16
PHP Best Practices: PSR-1 When you're programming, it's important to follow certain best practices in order to make your code easy to read and understand. This is an essential point when you're working in a team or if your code is going to be used by another developer. However, it is also important when we're working alone on a project. What is PSR-1?What is PSR-1? PSR-1 is a basic coding standard. It's oriented to the content of PHP files and the names of the classes and methods. It aims to ensure a high technical level of interoperability between PHP code. It covers topics like Files, PHP tags, character encoding, namespace, class names, class constants, properties and methods Overview of RulesOverview of Rules Some of these rules are: Files MUST use only <?phpand The reason? If you accidentally add code after the PHP closing tag, it’ll be interpreted as HTML. Files MUST use only UTF-8 without BOM for PHP code. Depending on your code editor the PHP code will be saved in different formats. You need to configure your editor to use UTF-8 encoding, and include a byte order mark (BOM). Namespaces and classes MUST follow an "autoloading" PSR. This means each class is in a file by itself, and is in a namespace of at least one level: a top-level vendor name. Class names MUST be declared in StudlyCaps. <br/> class MyNewClass extends Parent{...} StudlyCaps means that the first capital of each subword is capitalized. Class constants MUST be declared in all upper case with underscore separators. <br/> const DATE_TODAY = '2016-11-11'; This helps you to see clearer the difference between a constant, a method, a variable, etc. Method names MUST be declared in camelCase (). public function getNameById($id){...} camelCase is a special case of StudlyCaps. First letter lowercase, but after that all words capitalized and run together PHP code MUST use the long <?php ?>tags or the short-echo <?= ?>tags; it MUST NOT use the other tag variations. This is a resume of the standards that should be used. For more details you can take a look at The PSR-1 and this PHP Interview Questions Sample Answer. I hope this help you to improve your code!
https://www.codementor.io/soniavzquez/php-best-practices-PSR-1-idk8buo88
CC-MAIN-2018-05
refinedweb
383
76.11
strtoul(), strtoull() Convert a string into an unsigned long integer Synopsis: #include <stdlib.h> unsigned long int strtoul( const char * ptr, char ** endptr, int base ); unsigned long long strtoull(oul() function converts the string pointed to by ptr to an unsigned long; strtoull() converts the string pointed to by ptr to an unsigned long long. These functions recognize strings that contain the following: - optional white space - a sequence of digits and letters. The conversion ends at the first unrecognized character. A pointer to that character is stored in the object endptr points to, if endptr isn't NULL. Returns: The converted value. If the correct value causes an overflow, the function will return ULONG_MAX||ULONGLONG_MAX and set errno to ERANGE. If base is out of range, the function returns zero and sets errno to EINVAL. Examples: #include <stdlib.h> int main( void ) { unsigned long int v; v = strtoul( "12345678", NULL, 10 ); return EXIT_SUCCESS; } Classification: Last modified: 2014-06-24 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/s/strtoul.html
CC-MAIN-2018-13
refinedweb
175
57.37
This is the third tutorial for the Slay game on Linux (called Onslaught). Follow the link for the first tutorial in this series. This tutorial is about the map generator. It was derived from an earlier one I wrote for the Empire game. You can see that on GitHub in the file aboutmpire.zip. Click that file then click download on the page that opens. Then in that open the empire9src.zip and the original map generator files in that are are mapgen.h/.c, common.h/.c and data.h. Those are just for the curious; we won’t need them for this tutorial. There is a copy of data.h in the source files for this tutorial. Download the source files for this tutorial from GitHub. They are in the file Onslaught2.zip. Note the file contains both a Windows .sln file and a .vscode folder with JSON files for compiling with clang under Linux. Now that we can display hexagons (which in true wargame style I will call hexes from now on) , it’s time to create the map generator. The purpose is purely to create a playable map. As part of the generator, the player’s starting positions are also determined. The maps in the game are 20 across by 15 deep (small), 30 x 20 across (medium) and 40 across x 30 deep (large). We want these to fit on a screen say 1024 x 768 so a hex size of 34 pixels high by 32 pixels wide almost suits our purposes. It gives a large map of 31 hexes across by 28 down. We’ll need a bigger window for large maps and I used 1300 x 760. Generating a Map In the empire map generator (in the zip file AboutEmpire.zip) on GitHub I used multiple land points and sea points on an empty map. These are randomly placed on the map then a process of building up layers around each point adds land and sea to the map. The only rule being you can only add a layer point to an empty cell. So when the points grow into each other you get the interesting shapes. For our map the only difference is that we want to have one continent created not 2 or 3 like in Empire and the total size must be between 50% and 80% of the available space. So a small map of 300 hexes (15 x 20) will have a continent varying in size between 150 and 240 hexes. How it Works A very long time ago I created a text file which looks a bit like this on the left. What that is, is 36 layers of text. Start with one point. Add 8 letters around it then 12 Bs and so on. The shape looks a bit weird but it is a circle except that text characters aren’t square so it looks longer and narrower. Here’s what the centre bit looks like. So it goes outward A-Z then a-o but works out as 35 layers. I’ve converted all these characters into relative offsets in the file data.h. There are 35 NumLayerPoints. #define MaxLayers 35 int NumLayerPoints[MaxLayers]= {8,12,16,32,18,28,40,44,60,52,54,56,72,80,76,100,86,92,96,96,128,128,106, 120,136,140,140,168,126,160,168,164,172,180,156}; So 8 As, 12 B’s and ending with 156 o’s. Then there are the offsets, sayiong where in a large array of points, each layer starts. int Offset[MaxLayers]= {0,16,40,72,136,172,228,308,396,516,620,728,840,984,1144,1296,1496,1668, 1852,2044,2236,2492,2748,2960,3200,3472,3752,4032,4368,4620,4940,5276,5604, 5948,6308}; Then finally there is the very large array circlepoints. const int circlepoints[6620]={ -1,-1,0,-1,1,-1,-1,0,1,0,-1,1,0,1,1,1, That shows the first 8 points- all the A’s relative to the * in the centre. There are 8 points for A that start at offset 0. Each two values are the x and y offsets. The offset for the 12 B points is 16 (8 points for A x 2). So by using this data, it’s possible to build up up to 35 layers around every point. The map uses a struct with the island field (read it as is land) using an enum value. ltEmpty is the default and the map is initially set to all ltEmpty. I use landtype (a typedef for the enum maptype) so I don’t have to prefix everything with enum. enum maptype {ltEmpty, ltLand, ltSea}; typedef enum maptype landtype; struct hex { int map; int continent; landtype island; // ltempty, ltland or ltsea }; Going Cross-platform Though I said initially this was only going to be a Linux game, I decided to make it Windows for one main reason. The debugging is a lot better in Visual Studio than Visual Studio Code when it comes to SDL programs. So the few places that differ now have compiler #ifdef _WIN32 directives. For example this is the start of onslaught.c now. I’ve shown the Windows-only code show in Bold and the Linux-only in italic. The rest is common to both. #include "hr_time.h" #include <time.h> #ifdef _WIN32 <strong>#include <SDL.h> // All SDL App's need this #include <SDL_image.h></strong> #else <em>#include<linux/time.h> #define __timespec_defined 1 #define __timeval_defined 1 #define __itimerspec_defined 1 #include <SDL2/SDL.h> // All SDL App's need this #include <SDL2/SDL_image.h></em> #endif #include <stdio.h> #include <stdlib.h> #include "data.h" Due to laziness, I have a slightly different path for SDL on Windows compared to Linux. I’m sure I will fix it one day so the two are the same. The Linux one seems fixed, but as I put the Windows include path into Visual Studio, it should be possible to change it. The only other places where Windows and Linux really diverge are things like the c string functions and fopen which Visual Studio gets very antsy over, if you don’t use the _s versions. So don’t use strcat but strcat_s on Windows and strncat on Linux. I use them so infrequently, it’s not a big thing anyway. Fine tuning Map generation On problem I found initially was the Empire map generator developed multi continent maps. These three #defines are what control map generation and I had to play with them quite a bit till it started producing the type of map I wanted with one continent. #define LANDDISTANCE 7 #define LANDPOINTS 25 #define SEAPOINTS 15 The LANDDISTANCE is used when placing land points. It is used in the function NearLand() which scans the whole map and uses Pythagoras to calculate a distance. // Return 1 if distance is <= LANDDISTANCE int NearLand(int xo, int yo) { for (int y = 0; y < MAPHEIGHT; y++) { for (int x = 0; x < MAPWIDTH; x++) { if (map[x][y].island == ltLand) { int distance = ((xo - x) * (xo - x)) + ((yo - y) * (yo - y)); if (distance <= LANDDISTANCE) return 1; } } } return 0; } I don’t calculate the square root, so LANDDISTANCE is really the square of the distance. It’s a minor optimisation. There’s possibly a case for just picking random points; it might be quicker and wouldn’t have an inherent bias (This always goes from top left to bottom right) but it is pretty fast. Press N a few times to see that. Calculating map size and polishing the map Before the function CountContinents() is called, the function FillInBlanks() looks for all empty map locations and sets them to sea. I use a recursive function to measure the map size. The function CountContinents() goes through the map and calls the function FillIn(). This uses the array AllContinents to count all contiguous hexes (I’m being lazy and using all 8 locations rather than six for hexes). It uses the continent field to track these. Initially the conmt9inent field is set to -1 for every location. As soon as CountContinents finds a location with a continent of -1, it starts finding all contiguous locations of the same type (sea or land) and continent = -1 and sets continent = the numbner of continents. Note that the sea is continent 0. After CountContinents has finished, the variable NumContinents has the number of continents and the array AllContinents has an entry for each continent with the type and count. Next is the pruning stage. This iterates through the AllContinents table and for any land with less than 50 squares, it is converted to sea by calling the recursive function Sinkat. Finally the AllContinents array is checked to see that there is only one large land mass with between 35% and 60% of the game area as land. If not the map is rejected and regenerated. Setting the players starting position The function SetPlayers() is passed the number of players (8 for now) . It calls FindRandomLand() and then tries to allocate 4 or 5 blocks of troops out of the hexesPerPlayer that is has calculated for each player. This is somewhere in the region of 55-65 hexes for each player. The blocks are placed by calling AddBlockPerPlayer() which then distributes the remainder of unplaces hexes randomly across the map. The idea is to have a few clumps. I found a couple of bugs. - There were a few, typically a dozen or less hexes that never got players allocated. So I added a function FixErrors that looked for them and set them to a random player. I’d added an error hexagon into the graphics to highlight them. - Occasionally, Sinking a continent leaves a few single hexes. I had added the isvalidhex() function to fix and earlier problem where there were two continents very close together. So roughly 1 in 6 maps has this. I’ll get it sorted for the next tutorial. So this is a typical Onslaught map. As you can see it has one isolated cyan hex. In the next tutorial, I’ll be adding in forts, trees and wild spaces. I’ll also add the mouse hit detection code so you can detect the coordinates of the hexagon you click on. I tested this on Linux and it compiled and ran without any issues.
https://learncgames.com/tutorials/slay-tutorial-three-the-map-generator/
CC-MAIN-2021-43
refinedweb
1,739
73.98
Sealed Classes Sealed class are classes that cannot be inherited by other class. Since sealed-classes cannot be inherited, they cannot be abstract. The following program shows an example of a sealed-class. namespace SealedClassesDemo { public sealed class Base { private int someField; public int SomeProperty { get { return someField; } set { field = value; } } public void SomeMethod { //Do something here } //Constructor public Base() { //Do something here } } public class Derived : Base // ERROR { //This class cannot inherit the Base class } } We use the sealed keyword to indicate that a class is a sealed-class. You can see that sealed-classes are just like normal classes so it can also have fields, properties and methods. Line 25 will produce an error because the Derive class is deriving from the sealed Base class. Sealed classes are useful if you are making a class that prohibits itself from being inherited by others. Subscribe Inline Feedbacks View all comments
https://compitionpoint.com/sealed-classes/
CC-MAIN-2021-31
refinedweb
150
61.36
Linear Regression What is linear regression and how it works? Linear Regression is a supervised machine learning algorithm where the predicted output is continuous and has a constant slope. The linear regression model has a linear relationship between the dependent and independent variable. Let x be the independent variable and y be the dependent variable. We will define a linear relationship between these two variables as follows: y = a_0 + a_1*x where a_1 is the slope of the line and a_0 is the y-intercept. This equation will be used for predicting the value of Y. Before moving on to the algorithm, let’s have a look at two important concepts to understand linear regression. - Loss function: It is the function used to find the best value of a_1 and a_0. We will use mean squared error by following steps: - Find the difference between the actual and predicted value of y for given x. - Square the difference - Find the mean of squares for every value of x. - Gradient descent algorithm: It is an optimization algorithm used to find the minimum of function. In linear regression, it used to minimize the cost function, by updating the value of a_1 and a_0. Imagine a ‘U’ shaped valley. Suppose our aim is to reach the bottommost position. We start from the topmost position. There is a catch, you can only take a discrete number of steps to reach the bottom. If you decide to take one step at a time you would eventually reach the bottom of the valley but this would take a longer time. If you choose to take longer steps each time, you would reach sooner but, there is a chance that you could overshoot the bottom of the valley and not exactly at the bottom. In the gradient descent algorithm, the number of steps you take is the learning rate. This decides on how fast the algorithm converges to the minima. To update a_1 and a_0, we take gradients from the loss function. To find these gradients, we take partial derivatives with respect to a_1 and a_0. The partial derivates are the gradients and they are used to update the values of a_1 and a_0. Alpha is the learning rate which is a hyperparameter. A smaller learning rate could get you closer to the minima but takes more time to reach the minima, a larger learning rate converges sooner but there is a chance that you could overshoot the minima. Linear Regression selection criteria: - classification and regression capabilities - data quality (outliers can affect) - computational complexity Implementation: I have used this dataset , which consists of marks scored by students and no. of hour student studied. Our aim is to predict the marks scored by the student. - Code using the above discussion of loss function and gradient descent. #import required libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline #reading data from given link url = "" df = pd.read_csv(url) X = df.iloc[:, 0] Y = df.iloc[:, 1] plt.scatter(X, Y) plt.show() # Building the model m = 0 c = 0 L = 0.0001 # The learning Rate epochs = 1000 # The number of iterations to perform gradient descent n = float(len(X)) # Number of elements in X # Performing Gradient Descent for i in range(epochs):) 9.896964110671043 1.6314708810783134 Y_pred = m*X + c plt.scatter(X, Y) plt.plot([min(X), max(X)], [min(Y_pred), max(Y_pred)], color='red') # predicted plt.show() Linear Regression is used for evaluating and analyzing trends and sales estimate, assessment of risk in the financial sector and insurance domain etc. Conclusion: Linear Regression is a very useful and simple algorithm of machine learning. Hope you find this article helpful. Keep learning!
https://medium.com/analytics-vidhya/linear-regression-6b642119533a?source=user_profile---------1----------------------------
CC-MAIN-2022-33
refinedweb
620
65.93
DotVVM lets you build interactive web UIs with just C# and HTML using the MVVM approach. It simplifies building of line of business web apps and ships with many built-in controls like GridView, FileUpload, Validator and more. The Views in DotVVM use HTML syntax with controls and data-bindings. The ViewModels are plain C# objects with properties and methods. You can access the ViewModel properties using {value: Name} and call ViewModel methods using {command: Submit()}. <div class="form-control"> <dot:TextBox </div> <div class="form-control"> <dot:TextBox </div> <div class="button-bar"> <dot:Button </div> public class ContactFormViewModel { [Required] public string Name { get; set; } [EmailAddress] public string Email { get; set; } public void Submit() { // ... } } DotVVM comes with many features including: Learn the basic principles of DotVVM in our DotVVM Academy tutorials. The easiest way to start with DotVVM is to download DotVVM for Visual Studio and do File > New > Project. You can also install DotVVM in existing ASP.NET projects and use it side-by-side with other ASP.NET frameworks (Web Forms, MVC, Razor Pages). There is also dotnet new template for those who prefer command-line approach. You can get our free extension for Visual Studio Code. DotVVM is used in production by hundreds of developers and companies. The first stable release was in June 2016. You can find the plans for next releases in the roadmap. We have already started development of DotVVM 3.0 - everything is happenning in the v3-master branch. DotVVM framework is open source and will always be free to use. It's developed under Apache license. There are also free extensions for Visual Studio and VS Code available. They are not open source, but they will also be free to use. You can get more productive with DotVVM and support development of the framework by purchasing commercial components and tools developed by the creators of the framework: We'll be glad to accept any contribution. It doesn't need to be a pull-request - you can help us by spreading the word about the project in a blog or a user group, fix a typo in a documentnation or send us your feedback and thoughts. You can find more info in Contribution Guidelines. We kindly ask you to respect the Code of Conduct. Feedback is crucial to make DotVVM better. You can reach us at any time on our Gitter Chat. This project is supported by the .NET Foundation.
https://awesomeopensource.com/project/riganti/dotvvm
CC-MAIN-2020-50
refinedweb
408
66.44
Archives NASDAQ cut out its free XML feed...bummer Oh well, I guess you get what you (don't) pay for. It was too good to be true...NASDAQ used to have a publicly-accessible XML feed for stock quotes, and I've noticed it's been inaccessible for several days, and finally found a couple links from some PHP gentlemen who said the service has been cut off. So, this basically killed of the effectiveness of a custom server control I built months ago and that was available from the ASP.NET Control Gallery. Darn. Bravo, Jeff - awesome "Power ASP.NET Programming" WebCast In case you missed it live earlier this month, or if you're like me and live in a place where geography mandates having to get up at 3AM on Wednesday mornings to watch live presentations, Jeff Prosise's “Power ASP.NET Programming“ kicks major ass. The Wintellect guru talks custom HttpHandlers for dynamic imaging with GDI+, logging in the HTTP pipeline, and has lots of cool demos, and a sweet database-dependency trick for SQL Server and ASP.NET 1.x. Jeff also discusses what not to do when developing code and components, so as a pessimist, I enjoyed it. It's a 200-level WebCast, discussing topics outside of the scope of the normative presentation on ASP.NET, so it's a must-watch. (Plus, you'll chuckle at the constant commentary by what I assume to be Jeff's pet parrot squaking in the background). :) Check it out. What a long, strange trip it's been: the biggest ASP.NET moments for 2003 Borrowing a timeless theme from the late, great Jerry Garcia, here’s my list of memorable moments for being a proud ASP.NET developer over the past 12 months. Feel free to append your own, as I’m sure I’ve left something out. - Updated version of ASP.NET Web Matrix released - New edition of Steve Walther’s seminal work “ASP.NET Unleashed” published, featuring ASP.NET 1.1 examples in C# and VB.NET - MMIT included as part of VS.NET 2003, eliminating need for separate download - Dave Wanta’s aspNetEmail component slays competition for sending mail - Someone figures out how to share session data between ASP 3.0 and ASP.NET 1.x - ASP.NET Forums take off...and take over - Data provider for Oracle released - C# gains leverage over VB.NET (ouch - you may throw tomatoes....NOW!!!) - The eternal “should I use a DataReader or DataSet?” argument, after much debate, is put to rest in numerous community forums - Whatever happened to ASPElite? - I foolishly fall victim to the soon-to-be bought out IDG Books (aka, Hungry Minds), now Wiley Publications, serving as technical reviewer and getting screwed out of a payment - Starter Kits made public - ASPAdvice inherits mailing list community from now-defunct ASPFriends - The .NET Show promises - and then cancels – episode on developing custom server controls - Microsoft Application Blocks released to rave reviews - I get selected as a Whidbey alpha tester. I have seen the future, and it is very, very, very good. - Freeware Cassini web server debuts (I think this happened in 2003) - ASPToday.com becomes part of fallout as Wrox goes under; properties later acquired by APress - Microsoft makes big push towards RSS in several of its public web properties - Community top dogs make move towards blogs, thanks to Scott Watermasysk’s .TEXT - Bravo to the cat who made DataGrids scrollable by setting <div style=”overflow:auto;”><asp:DataGrid id=”dg” runat=”server”></div> - MSDN-TV debuts with Rob Howard talking about AppSettings - I secure two subscriptions to ASP.NET Pro Magazine – one for the office to get wrecked, one for archival at home - Addison-Wesley rolls out outstanding “.NET Developer Series”- advanced books without fluff or marketingspeak - ASP.NET WebCast Week on MSDN announced – <and the crowd goes wild!> - 2.0 - Whidbey blows ‘em all away after premiering at PDC Community project: creating an ASP.NET-specific extension for UML I'd like to initiate a community-oriented project for visual modeling, centric strictly to ASP.NET development. It will, at its core, incorporate the main concepts Jim Conallen of Rational introduced for the Web Application Extension for UML (WAE) in his excellent book “Building Web Applications with UML”. Basically, I’m looking to organize discussions for a common set of icons and associated visual modeling glyphs to be used by ASP.NET developers, for our way of life. This logically could begin with the simple icons already available in VS.NET and Web Matrix for ASP.NET-related file types to demonstrate files and their relationships, and could extend all the way to things like components, Use Cases, XML Web services relationships, namespace hierarchies, custom controls, HttpHandlers, caching & cache dependencies, DALs, application settings, and Global.asax-resident routines. However, this will only extend UML, not supercede it. I’ve been meaning to do this for use within my own projects, and I’d be happy to share it with you, too. I think it would really help us understand each other’s cool code and architectural tips as we share ideas if we could develop a common set of images and conventions just for us. In my opinion, Microsoft technologies are to date a bit weak at providing such visual help (in comparison to Rational, for instance), and UML in general is overkill for web-based applications. The WAE Conallen spoke of is good, but not MS-specific. Basically, I'm just making an open call for a diverse group of people within the ASP.NET community willing to share their ideas (minimal time required...just a couple of messages every now and then) and work on developing an image set to iconify ASP.NET concepts. We’ll then aggregate this information and make it available for public download. If this really takes off, I’m hoping to have enough cool stuff to collaboratively develop an IDE add-in for visual modeling, available as freeware. Hopefully, it’ll be effective enough to be recognized and used with somewhat broad distribution by Microsoft web developers. I’m willing to start and archive the information generated by such discussions, and do the majority of the legwork to get this going. Anyone interested? Practicality of having typed view state/ViewState API for ASP.NET 2.0? I’m quite sure someone has brought this up at some point either theoretically or jokingly, and I’m not sure how feasible it would be (although I think it would be pretty cool), but can/should a page’s view state be able to be typed, rather than just storing all data within as type object? Perhaps the convention of - ViewState[“key”] - could include a second argument when 2.0 rolls out, which would be the explicitly-stated data type for the data? CHEESY EXAMPLE 1: String myName = “Jason Salas”; ViewState[“aDudeInGuam”,System.String] = myName; Or, possibly this could be set in web.config for **certain** ViewState entries, providing typing information, as the Profile does object for personalization in 2.0? CHEESY EXAMPLE 2: <viewstate keyName=“phoneNumber“ type=“System.Int32“/> Or, maybe include a ViewState API (there’s a thought), similar to what is provided with the Cache API, wherein developers have a variety of overloaded methods from which to choose in setting/accessing view state values? CHEESY EXAMPLE 3: int homePhoneJenny = 8675309; ViewState.Insert(“keyPhone”, homePhoneJenny,System.Int32); Would this even be worth it, or make sense? It seems to me like this would fit in nicely with Whidbey’s push towards more streamlined programming without the need for casting/recasting data. Certainly, many people would get something out of it when working with business logic, and if this would help improve the expensive performance hit caused by the Framework's internal binary serialization for types without readily-available type converters, that would be gravy. What do you think? Is NASDAQ's XML feed down? I noticed a couple of days ago that the free XML feed from NASDAQ has been inoperative, returning an empty root XML node, and has yet to come up. I first got wind of this after noticing that a custom stock ticker server control several months back (), was showing up blank. I checked the source, and sure enough, NASDAQ was empty. Something similar happened to the free XML feed for weather data about a year ago. I, and several others, used to tap that service for its great features. The guy who ran it (a nice dude, I corresponded with him a couple times), took it offline after apparent repeated problems. Still trying to achieve anonymous personalization with WebParts in Whidbey My? The top buzzwords used to market software development products I recall one of my viewers being absolutely livid over the fact that I mentioned the term “killer app” during the TV segment I host on web development, thinking I was making a call to violence. In response, I did what all great journalists do - used her lack of foresightedness as the subject of my next column. :) It's funny...as I'm filling out Christmas cards, I'm subconsciously being way too wordy in the corporate sense, rendering what should be sentimental, cheery, holiday greetings into de facto fluffy ads. In business school, I was taught to be as verbose and long-winded as possible, and then as a journalist, I'm required to be extremely refined and simplistic. And of course, as a programmer, my very existence is rooted in and around logic. Needless to say, the many directions in which my brain is tugged daily make for some interesting internal debates about how to communicate. This made me think...what are the most overused buzzwords/marketingspeak used in the development world to market IT products today? Here are some of my faves: - “...gives you more granular control over...“ - “language-agnostic...“ - “scalability with stovepipe applications“ - “a rich UI“ I'm interested in seeing what new terms become part of the developer's lexicon, whether by use or by force. What are your top buzzwords/terms? Digital hypocrisy: crossing the use/misuse continuum on the Web with ROBOTS.TXT I've always found the optional file you can save in a Web site, ROBOTS.TXT, while sound in purpose, extremely hypocritical and potentially lethal to a site's integrity. As a guy who’s been in technical marketing for more than a decade, it's always been interest of mine to see the practical use of tidbits of information towards giving a site maximum exposure. As a budding developer years ago, this was also one of my first forays into “security“. As a refresher, ROBOTS.TXT is a simple text file stored in the root directory of a Website, containing metadata, instructing search engine spiders which directories/subdirectories to avoid browsing so as not to include sensitive information in their indexes. A simple concept, but the fact that these files can be browsed by any idiot with a browser and Internet connection of any speed makes them dangerous. For more on ROBOTS.TXT, visit It's literally like saying, "Hey, there are certain directories I have secretive content stashed in, and I don't want you to see them at all...and here they are." Need proof? Check these URLs out for some good examples how varying organizations in varying industries creatively use the file: In fact, if memory serves, I recall an engineer at Sun Microsystems several years back writing quite the scathing criticism about the use of ROBOTS.TXT on, seeing as how it gave hackers one less challenge to break their stuff (Sun apparently had a bunch of internal download sections, CGI scripts and administrative utilities located in directories they didn't want search engine spiders to find out about). By storing the directory names in ROBOTS.TXT, Sun was essentially giving people the direct URL(s) to their private information, which granted was password-protected, but still overcame arguably THE major hurdle of hacking a site - figuring out which directories contain the good stuff. As for me, I constantly use the META tag in pages I don't want spiders to see. That normally does the trick. Using ROBOTS.TXT improperly just invites users savvy enough to know it exists (as many of you now do, after reading this) to type in your site’s domain name, and appending “/robots.txt”. To be the file’s proponent, it does do an effective job of preventing spiders from indexing your stuff. And sure, this locks unwanted access out from I'd dare say 97% of the Web browsing community. It would only be Web developers trying to hack Web developers, and one would hope that there would be enough honor among thieves, as it were, or at least an appreciation for parity, that savvy people would not engage such pursuits. However, some organizations do use the file to their advantage, not implementing it as a security means, but more so as a way to not let redundant content or data that would otherwise clutter the Web even more be indexed. And just in case you’re wondering, don’t even bother looking for the file on my site - it doesn’t exist. :) I'm hoping for more project-oriented books for ASP.NET 2.0 I was really impressed with the former Wrox's (now APress) title, “ASP.NET Website Programming: Problem, Design, Solution”, and I'm hoping that for Whidbey, they'll be more titles like this. It really gave an architectural perspective on an application, taking a single theme and expanding it exhaustively throughout the course of the book. It show in-depth code and concepts behind several sub-applications within the main app, which is really needed more these days. And, it really leveraged some of the aspects of building an ASP.NET application with reusable code and components. It's still one of the better reads out there. Hope there's more planned for the future. Code for custom RSS generator server control in ASP.NET 1.x I wrote a custom server control for an RSS generator after some people had requested it from a previous blog I did, throwing out the question of Microsoft possibly being able to develop one or more custom server controls to generate and consume RSS feeds. It got a decent response, with people vehemently petitioning both for and against it. It's far from a landmark achievement of modern computer science, but it demonstrates how easy it is to do (which, mind, you was never in question). Code download: RSS custom server control I wrote this custom server control class to demonstrate how easy it is to develop a portable control generating RSS feeds for a content-oriented site. It formats data coming out of a SQL Server database to conform with the RSS 2.0 Specification. - Click here to see what the output RSS newsfeed looks like. - Click here to download the source code to extend the control for yourself The only requirement is that since this control generates XML data, a page using the control can have no other HTML headers or markup other than the control, and page-level directives, so output caching will still apply to the XML-based data. For example, this would be the code in a client page, like an .ASPX or .ASCX file: <%@ Page debug="false" trace="false" language="c#" AutoEventWireup="false" %><%@ Page debug="false" trace="false" language="c#" AutoEventWireup="false" %> <%@ Register TagPrefix="kuam" Namespace="RSSFeed" Assembly="RSSFeed"%> <%@ OutputCache Duration="30" VaryByParam="none" Location="server" %> <kuam:rssgenerator Here's the skinny on the object model (3 public properties): - DataFormatString - an echo of the .NET Framework's property of the same name, for structuring the destination URL - Server - the database connection string for the data store to hit - SQLString - the query to execute against the specified DB There's some room for improvement, which is very easily done, notably in the following areas: - support for databases other than SQL Server (Access, Oracle, ODBC, etc.) - support for XML-based data stores - a few more public properties for more customization Let me know if you find it helpful, and write me if you extend it to fit your own uses. I did this in between TV shows, and I'm always a sucker for improvement. :) using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.ComponentModel; using System.Text; using System.Data; using System.Data.SqlClient; namespace RSSFeed { /// <summary> /// This custom server control grabs data from KUAM.COM to be used as an RSS feed for headlines. /// This control requires removing all of the HTML headers from a page (no content). Therefore, the only /// things that can be on the page are the control itself and any page-level directives. /// </summary> [DefaultProperty("Text"),ToolboxData("<{0}:rssgenerator runat=server></{0}:rssgenerator>")] public class rssgenerator : System.Web.UI.WebControls.WebControl { // data members private string _sql; private string _serverName; private string _url; // public properties [Bindable(true),Category("Data"),DefaultValue("")] public string SQLString { get {return this._sql;} set {this._sql = value;} } [Bindable(true),Category("Data"),DefaultValue("")] public string Server { get {return this._serverName;} set {this._serverName = value;} } [Bindable(true),Category("Data"),DefaultValue("{0}")] public string DataFormatString { get {return this._url;} set {this._url = value;} } // get the daily news private string GetRSSNewsFeed(string server,string sql) { SqlConnection conn = new SqlConnection(server); SqlCommand comm = new SqlCommand(sql,conn); SqlDataReader dr; string newsFeedData = string.Empty; try { conn.Open(); dr = comm.ExecuteReader(CommandBehavior.CloseConnection); newsFeedData += "<!-- RSS Newsfeed custom server control -->\n"; newsFeedData += "<!-- Written by Jason Salas \n Web Development Manager / News Anchor, KUAM News \n jason@kuam.com \n \n December 19, 2003 -->\n"; newsFeedData += "<rss version=\"2.0\">\n\t<channel>"; while(dr.Read()) { // TODO: make the array of DB values come from a string[] array, use boolean operator for data provider newsFeedData += "\n\t\t<item>\n\t\t\t<title>" + MakeDataXMLSafe(dr.GetString(2)) + "</title>\n\t\t\t<description>"; newsFeedData += CreateAbstract(dr.GetString(4)) + "</description>\n\t\t\t<link>"; newsFeedData += MakeDataXMLSafe(string.Format(DataFormatString,dr.GetInt32(0))) + "</link>\n\t\t\t<author>"; newsFeedData += MakeDataXMLSafe(dr.GetString(3)) + "</author>\n\t\t\t<pubDate>"; newsFeedData += MakeDataXMLSafe(string.Format("{0:D}",dr.GetDateTime(1).ToString())) + "</pubDate>\n\t\t</item>"; } dr.Close(); newsFeedData += "</channel>\n\t</rss>"; } catch(SqlException ex) { newsFeedData += ex.ToString(); } catch(Exception ex) { newsFeedData += ex.ToString(); } finally { if(conn.State == ConnectionState.Open) conn.Close(); comm.Dispose(); conn.Dispose(); } return newsFeedData; } private string MakeDataXMLSafe(object data) { string dataString = data.ToString(); dataString = dataString.Replace("'","'"); dataString = dataString.Replace("\"","""); dataString = dataString.Replace(">",">"); dataString = dataString.Replace("<","<"); dataString = dataString.Replace("&","&"); return dataString; } private string CreateAbstract(string bodyContent) { // create an story summary by truncating the BODY field of the DB table int periodIndex = bodyContent.IndexOf("."); string finalText = string.Empty; if(periodIndex < 150) { int newPeriodIndex = bodyContent.IndexOf(".",periodIndex+1); finalText = bodyContent.Substring(0,newPeriodIndex); } else { finalText = bodyContent.Substring(0,periodIndex); } return finalText + " ... "; } protected override void OnInit(EventArgs e) { // set the MIME type for the page in which the control sits to XML this.Context.Response.ClearContent(); this.Context.Response.ClearHeaders(); this.Context.Response.ContentType = "text/xml"; } protected override void Render(HtmlTextWriter output) { output.Write(GetRSSNewsFeed(_serverName,_sql)); } } } Why even bother asking for permission to link to a site? OK...I'm a web guy in the TV/media biz, so I'm not exactly surrounded by a huge community of people who subscribe to the software developer’s way of life. In other words, I get a lot of requests from people from all walks of life who think “you’ve got a great Inter-web,” try to email 90MB TIFFs embedded in Word documents, and constantly ask me where on the Internet they can find information on any topic, as if I’ve got Google’s entire search index stored mentally. You get the picture. Thus, my reason for writing - it's perfectly OK for the non-hardcore web community and those marketing morons not in the know to link to someone's site without asking. For real. Throughout the year, but in particular around the holidays, I get bombarded by requests by legitimate individuals and organizations that send request e-mails asking if they can link to my site (I've gotten 7 today so far). Now, I did a fair amount of coursework in graduate school on intellectual property law (which is to say, 1 class), and while it may be kosher to ask to associate oneself to another organization's site, it's realistically impossible to accurately track just who out there is connecting to your domain via hypermedia. I'm a marketing major myself, so this practice of unnecessary politeness drives me nuts. Such was a reasonable inquiry when the Web first took off, but we’re too far into the game at this point. Behavior of this nature is arguably THE reason the job title of “Administrative Assistant” was created...giving those people something to do for 8 hours a day, and giving them something to lay claim to. If IBM started linking to my site, it's free press for my company's stuff - and there really is no such thing as bad press. We in the blogging community openly and great frequency and passion link to other people's blogs, to MSDN, to countless online resources, news articles, media files, and everything under the sun. And we do so both in praise of, in reference to, and in criticism towards, the content contained therein. My boss at a former job once asked me to compile a list of ALL the sites pointing to our domain. How the heck am I to list not only the media & news sites linking to us, but also every Geocities and AngelFire site out there? Impossible! Heck, it's the foundation of why the Web was created in the first place, so make use of it. A company I once dealt with had an agreement companies needed to sign if they were to link to any of its pages, containing so much legalese it would make Johnny Cochran salivate. Not surprisingly, no one bit with the agreement, and most people got turned away by the anal retentiveness. Those that were still interested just did anyway, I’m guessing out of spite. And again, the company itself never really who was doing so. So fear not, e-marketers, link away. Let me put it in terms you can understand, wherein you can believe your own hype. Swallow a healthy spoonful of the medicine from the very Nike campaign you helped to create: just do it. SUGGESTION: formatting/color-coding changes for VS.NET I spoke to a Microsoft usability engineer recently who said there were discussions about possibly changing the color coding scheme employed by Visual Studio .NET. While I'm totally happy with the current formatting convention used by the IDE (blue for language-specific keywords, green for comments, gray for in-line documentation, bolded purple for classes, etc.), I'd like to make the following suggestions: - Enumerations should be formatted differently than from classes and structs. I realize functionally enums are similar to classes and structs, but formatting them as bolded purple tends to get me confused. I get it, but I'd like it to be different. Since they're a type of data type from which a predetermined range of values are selected, it would help me if they'd use some other type of coloration. - Method calls should be bolded to distinguish them from "normal" code. One of my favorite text editors, the freeware Jext () formats method calls/function invocations in bolded black text (as well as the parenthesis), to identify a method. I really like this, and is really speeds up my productivity when I'm hunting for something in my code. - I'm not sure if this is possible/feasible, but create a new class for SQL/T-SQL statements and provide in-line SQL syntax formatting, perhaps called "System.Data.SqlClient.SqlLanguage" (or something to that effect), and provide the ability to color-code SQL syntax inline, as if it were being done so in Query Analyzer. This would make for fantastic debugging! (I'm tentative about this one...would this hamper performance for instantiating yet another object on a page just to get code-coloration?) At the very least, I'm hoping for consideration over the bolded method call suggestion. That REALLY helps. A developer's New Year's resolutions (aka, "How I plan to fatten my resume for 2004") I've made a little promise to myself as a web developer to try (and hopefully be somewhat proficient in) a few key areas of programming in 2004. Thus, I'm hoping to dabble in the following for possible use in my work 12 months from now: - Windows Forms - integrating ASP.NET and Flash - .NET Remoting - Programming .NET components for Office How about you? What's on your mental To Do list for '04? Output caching and MIME types other than HTML I’ve got an interesting question - does output caching apply when the MIME type of a page is modified by changing its ContentType, or is it only applicable for HTML-based content? I’m trying to cache an .ASPX page where the MIME type is changed from the default “text/html” to “text/xml“, using the OutputCache directive, and I’m not sure if it’s working (it doesn’t appear to be). I can't really using page-level tracing, because the markup generated by tracing is read as XML up to a certain point, and then it throws an error. I wouldn't expect output caching to work for other MIME types like “image/jpeg“ or “application/ms-word“, and I've worked around it using the Cache API, but again, one of those things I'm curious about because I honestly don't know. Will (and should) ASP.NET 2.0 embrace RSS more? I've been messing with various RSS (really simple syndication) applications after having created my own implementations of syndicating content from my site. If you can't beat them.... Anyhoo, I've been thinking about whether it would be a good idea to suggest that ASP.NET openly embrace RSS more, perhaps to the point of including one or more server controls that could easily let a developer syndicate their site's stuff without going through the coding aspect of it. I think a drag-and-drop control that would seamlessly allow a site's content to be readily available to consumers would be a great addition to Whidbey's feature set. It's very easy to build providers and consumers already in ASP.NET 1.x, and in no doubt in wide distribution by the ASP.NET community, so I think the demand is justified. In fact, a past episode of MSDN TV cited RSS broadcasting as a major driving force a significant part of MSDN, Microsoft.com, and other aspects of its domain. However, for mere textual content, can one reasonably argue to a certain point that this might conceivably stymie, if not negate, the efforts of men better than me to further the use of XML Web services? The counterpoint would be that you get the same effect as consuming a remote content feed without needing to use the XML web services development model's overhead (although IMHO, consuming web services in ASP.NET 1.x is more fluid than creating an RSS client). Essentially, the API would consist of a dev specifying a datastore (database, XML, etc.) and connection string (DB string, XPath, etc.), and the control would do the rest, implementing a template-based XML document, conforming to the RSS 2.0 Specification. (Custom controls can be a bit tricky when working with MIME types other than “text/HTML” in the current model, but that's why those guys get the big bucks.) I also think providing automatic caching facilities through a public property would be a nice touch. What do you think? Would this be overkill? Are you happy with how ASP.NET uses RSS the way it is now? Great examples for using C# 2.0 Generics with ASP.NET If you’re having a tough time wrapping your brain around Generics in C# 2.0 as applicable to ASP.NET, or want some cool practical examples of how to use Generics check out Patrick Lorenz’s awesome book “ASP.NET 2.0 Revealed”. In particular, read the section describing data-driven server controls for the sweet example of using an ObjectDataSource using Generics as part of a business logic tier to bind to a GridView or DetailView and easily add editing, deleting and inserting new records. It's one of the few practical examples around at this point. Also included in the book is Scott Guthrie’s excellent example from his “Tips & Tricks” presentation from PDC about using Generics in ASP.NET. The new "in" thing for web development: get rid of the query string After I commented yesterday about MSNBC.com's site redesign, Robert McLaws had the wisdom to point out that the site's URLs are now in the following format:, making each story look like its own subdirectory. In similar fashion, I've also taken note that Steve Smith at ASPAlliance also recently migrated his site's URL convention, lopping off the query string for user-submitted articles: After having migrated my own site to ASP.NET, I now use a convention that MSNBC previously used, employing my database’s ID field as the disguised filename:. The facilities within ASP.NET for handling dynamically rewriting a path (namely, the RewitePath() method) make pulling this off incredibly easy. This draws to light a new theme that seems to be popping up more and more within the web development community, in particular from ASP.NET-driven sites: ridding oneself of the query string. It would appear that site designers are now considering the cosmetic appeal of a URL as part of the site's total usability, and an Internet address' psychological effect on the user. Perhaps this infers that a user's thought pattern might be that if a URL is messy and complex, the site will be, too? It seems that people are finally catching on to a principle that as a marketing guy, I've held since the first day I saw it: that query string-based URLs are really ugly. Using one or more appended name/value pairs in a site's URL is incredibly hard to remember, and the values that were once extracted can now be accessed and persisted in other places just as well (Cache API, Session, ViewState). I recall how people flocked to adding query string values to their URLs circa 1997 - whether they really needed them, or not - just to look advanced, shying away from plain 'ol “/directory/filename.html”. Apparently, people are starting to realize the promotional potential and KISS charm in simple page addressing schemes. Good to see. SUGGESTION: allow control for CatalogWebParts via remote windows in ASP.NET 2.0 I think it would be a nice touch if the Portal Framework could have functionality included wherein a developer woulnd't have to drop a CatalogWebPart on the same page as being worked on. For instance, the Framework could include a method or property that allowed child/popup windows control the changes and then upon submission, commit the changes back to the parent page. One of the methods already available in the API wraps a call to window.open(); to launch a static “help” page, but this of course, would be way more complex. In a discussion I had with Andres Sanabria, product manager for Web Parts & the Portal Framework, he indicated that it might be possible, but it's sticky since passing server data back-and-forth between a child and parent window client-side introduces new problems. He said though, that I wasn't the first to bring this up. Regardless, people are most certainly going to want to do this at some point, and undoubtedly someone will come up with a workaround if it's not standard, but it would be nice it came as part of the base functionality for ASP.NET 2.0. Thanks for listening! Code for Web service-less portable content I've gotten a couple of requests for the ASP.NET code for my blog about making your site's content portable to remote consumers without using a web service or RSS, so here 'tis. SqlConnection conn = new SqlConnection(conn); SqlDataReader dr; SqlCommand comm = new SqlCommand(strSQL,conn); StreamWriter writer = File.CreateText("C:\\inetpub\\wwwroot\\portableheadlineswithabstracts.js"); string swappedOutSingleQuotes; int periodIndex; int newPeriodIndex; string finalText; writer.WriteLine("<!-- "); conn.Open(); dr = comm.ExecuteReader(CommandBehavior.CloseConnection); while(dr.Read()) { writer.WriteLine("document.writeln('<a target=\"_blank\" href=\"" + dr.GetInt32(0) + ".aspx\"><b>" + dr.GetString(1) + "</b></a><br>');"); // create an abstract for the story by truncating the BODY field of the DB swappedOutSingleQuotes = dr.GetString(2).Replace("'","’"); periodIndex = swappedOutSingleQuotes.IndexOf("."); if(periodIndex < 150) { newPeriodIndex = swappedOutSingleQuotes.IndexOf(".",periodIndex+1); finalText = swappedOutSingleQuotes.Substring(0,newPeriodIndex); writer.WriteLine("document.writeln('" + finalText + " ... <br><br>');"); } else { finalText = swappedOutSingleQuotes.Substring(0,periodIndex); writer.WriteLine("document.writeln('" + finalText + " ... <br><br>');"); } } dr.Close(); writer.WriteLine("//-->"); writer.Close(); Response.Write("<h1>The headlines with abstracts were written successfully!</h1>"); First, here’s some basic instructions that you can place on your site, letting remote designers/developers know how to add your content to their pages with a single <SCRIPT> tag: As far as the database fields used, here’s the breakdown: GetString(0) = StoryID (INT – Unique ID) GetString(1) = Title (TEXT) GetString(2) = Body(TEXT) Here’s a sample of what a remote page would look like for the remote content (news headlines with abstracts) so you can view it in action: As long as you’ve got the write permissions on your directory, you’ll be up and running in no time! I hope it does the trick for you or gives you some ideas for your own projects. New-look MSNBC.com MS! :) Make your site's content portable to remote consumers without a web service or RSS I run a news Web site (obligatory applause), and one of the keys to us staying competitive is making our news headlines portabloe to other sites. It's a simple model: people put our headlines on their page(s), which link back to us. I figured out a way to do this This is atually the pseudocode for a tutorial I did a couple years back for ASP101.com but it resurfaced recently, and some people thought it was cool in today's XML-friendly web: - Connect to your data store (database, XML, Exchange, etc.) - Write the content in JavaScript syntax to a .JS file that you save on your server (usually overwriting a file of the same name) - Have ALL remote clients reference the full URL to your .JS file in the SRC attribute of <SCRIPT> tags: - <script language=“JavaScript“ src=““></script> It's a simple, 2-minute solution that practically all consumers will be able to use. Documenting and supporting it is a snap, and you won't need to worry about whether distant-end developers know how to consume XML Web services, RSS feeds, updating DLLs, etc. It's also usable in third-party hosting situations where supported services are a bit tighter than most. You write it once, update it as often as you see fit (my own implementation runs off of a scheduled Windows task). Click here for the ASP 3.0/ADO source...let me know if you need it for ASP.NET. It's not posted, but I've got it. I'd like to see an ASP.NET-specific extension to UML (and support in Visio wouldn’t hurt, either) Jim Conallen of Rational wrote the seminal book “Building Web Applications with UML”, in addition to penning numerous resources, available from IBM's site. He describes the Web Application Extension for UML (WAE), which is a great, scaled down philosophy for laying out components, interfaces and page relationships/mapping – both cosmetic and functional - within the context of a web application. Jim’s book highlights an area of development that for many is either thought to be either too grandiose or too closely-tied to traditional desktop development to be relevant in the web environment, or just generally misunderstood, and therefore, largely underutilized. The book “Building e-Commerce Sites with the .NET Framework” also uses a lot of database diagrams, Use Case models and site-flow diagrams, demonstrating that one doesn’t need to do a lot of classical UML such as class diagrams to be effective and build good documentation. I'd like to see more documented evidence and more widespread use on the use of modeling (UML and otherwise) within web applications. I got a lot out of Jim's book, and have conversed with him sporadically on the use of modeling. I started incorporating visual modeling into my projects a few years back, and while it is arguably overkill for smaller projects (it is a lot of additional work if done right), it is a critical part of development and really speeds the production process. I realize that it's probably not feasible to use include UML and other visual modeling tools into the basic offering for Visual Studio .NET, due to the fact that for many environments it just wouldn’t be used, not to mention increasing the cost of the base product, but it would be nice to have better modeling tools other than the “Web site” tools in Visio, which are largely mapping diagrams showing link relationships and doesn’t speak to web components. On the flip side, the software engineering tools in Visio not surprisingly tend to favor the desktop. I’m not ragging on Visio, just asking for more. If someone out there created an UML offshoot that was specific to ASP.NET, such as allowing for custom server controls, HttpHandlers, modules, Global.asax routines, etc. I think this would be great. This could either be a physical product or an intangible development methodology or a recommended standard. I believe either would help and be greatly appreciated. On this note, while the first edition of his book mentioned ASP.NET briefly a largely from a conceptual standpoint, Jim has told me that the next version of his book will get more in-depth with demonstrating web-centric modeling for ASP.NET. Interesting point: XmlTextReader interprets end elements as elements This sounds weird, but I discovered something earlier this week that I never would have expected, but makes perfect sense. When using an XmlTextReader to navigate through a remote XML document in what I thought was the right way, I kept getting extra blank nodes. When reading the following XML structure: <Story> <Headline>Campaign finance reforms upheld</Headline> <Abstract>The Supreme Court upheld two key parts of a new campaign finance law Wednesday — one on so-called soft money loopholes and the other on issue advertising.</Abstract> </Story> <Story> <Headline>U.S. copter down in Iraq</Headline> <Abstract>A U.S. military helicopter made an emergency landing Tuesday in Fallujah, just hours after a car bomb attack on barracks near the northern city of Mosul wounded 41 U.S. soldiers, mainly with flying debris and glass. Elsewhere, a rocket attack on a Baghdad mosque killed three Iraqi civilians.</Abstract> </Story> The XmlTextReader was apparently treating the closing </Story> end elements as elements! Duh! Thanks to Dan Wahlin (the man when it comes to anything XML) for helping me suss this out. PivotTables (aka cross-tab queries) in Longhorn - YAH! [TAKING A BREAK BETWEEN SHOWS...] I'm stoked about the fact that Longhorn will support PivotTables, also known as cross-tab queries. If I recall, PivotTable queries have been rolled into a single function. Sweet! I recently did a project where these were used extensively, and I nearly forgot just how much code (relatively speaking) it takes to generate such stuff. Happy anniversary/RIP ASPFriends Catholics will appreciate the significance of a first-anniversary rosary, the process held to commemorate the one-year anniversary of a loved one’s passing. It just dawned on me this morning that it’s been about a year since the moderately-balleyhooed demise of the ASPFriends mailing lists. I did a story on it for work, interviewing two people who I consider my friends, Scott Guthrie and Charles Carroll. And if nothing else, it made for an interesting blemish on the complexion of the history of ASP.NET development. We’ve migrated away – either by closure, by preference, or merely out of following the pack - from ASPFriends, the Wrox P2P Forums, and DevelopMentor mailings lists and forums and now embraced concepts like the ASP.NET Forums, blogs, WebCasts and a whole slew of community-oriented events. Whether this is indicative of the progression of technology or just reminiscent of migratory patterns that would make salmon jealous is debatable. Much in the way of how my parents remember where they were when JFK was shot, or me committing to memory where I was when the announcement was made that Elvis had died, or John Lennon got assassinated (or more recently, when the Smashing Pumpkins broke up), can you recall what you were doing when the whole battle over ASPFriends ensued? This was a simple matter turned ugly and got tragically aired out to the entire ASP.NET community over the span of a few harried days. I remember it vividly. And if you’re sitting now, groaning about why I’m bringing up old stuff, it’s because it’s comical, if anything, to remember just how large what should have been a small issue became. I recall a long-winded mass e-mail from Charles, sent numerous times, stating his case and announcing, in no shortage of words and implied emotion, that he would be terminating the valued e-mail mailing lists because of a contractual dispute with Microsoft. In doing so, he indirectly lobbied for people’s support to become campy and join his crusade against the corporate monolith. He made public outcries against noted and distinguished community members like Steve Smith and Alex Lowe. He denounced Microsoft’s efforts. He gave testimony about how many hours he put into the project, how he personally moderated many of the lists, how he recommended people for Microsoft MVP honors for ASP.NET, and how he personally financed the site’s hosting charges. I then recall a response letter from Scott a couple of days later, stating Microsoft’s position, promising great things with the ASP.NET Forums, and informing us that short of a court order, Charles was asked repeatedly to cease his affinity to call and harass Microsoft staffers about the issue. Obviously, civility and professionalism won. The response from the ASP.NET community, not surprisingly, was largely apathetic. We witnessed occasional supporters in the days following openly crying out for ASPFriends not to go offline. Likewise, other people took the time out of their days to say, “Good riddance”. But for the most part, the vast majority of developers accepted it, said nothing, and moved on with their lives. Sadly, ASPFriends, Charles’ great creation and without a doubt THE most-popular aspect of the ASP.NET community experience has been whittled down to a few Yahoo! Groups and a few sparse mailers from ASPElite. This is a sad and tragic death to something from which gave us all so much. ASPAdvice, run by Smith and Lowe, has since effectively picked up the slack and is a thriving online community of its own, using the same e-mail-based peer support concept. The Forums on are phenomenally popular and everyone who’s anyone in the ASP.NET community has a blog. Life goes on. And who knows? We may very well see the closure of the applications used today for other new and interesting products in the near future. Innovation says that’s probably going to be the case, and a lot can happen in a year. So say a prayer, drop some virtual flowers, and remember the good old days of ASPFriends. And thank whichever deity you subscribe to that we’ve been able to move on and get to where we are now. ASMX sample response message using serialized XML doesn't account for derived membersI've noticed something in the sample response XML generated by an .ASMX file in ASP.NET 1.x (at the very least, in 1.0). Specifically, when using serialization for custom XML, the Web service apparently does not take into account data members derived from a base class when reporting what a response message will look like. Don't get me wrong, the final XML message itself is perfect, but I've found inaccuracies in the .ASMX response message.For instance, here's an example I ran into when working on a statistic service for a local football league. I used a base class "Player", containing only properties. The classes "Offense", "Defense" and "Special Teams", all contain statistical information, and inherit from Player to get the shared properties Name, Position, JerseyNumber and Team:public class Player { private string _name; private string _position; private string _jerseyNumber; private string _team; public string Name { get { return this._name; } set { this._name = value; } } public string Position { get { return this._position; } set { this._position = value; } } public string JerseyNumber { get { return this._jerseyNumber; } set { this._jerseyNumber = value; } } public string Team { get { return this._team; } set { this._team = value; } }} [XmlRoot("OffensiveStats")] public class Offense : Player { // implementation...removed for brevity } [XmlRoot("DefenseStats")] public class Defense : Player { // implementation...removed for brevity } [XmlRoot("SpecialTeamsStats")] public class SpecialTeams : Player { public int Punts { get { return this._punts; } set { this._punts = value; } } public int PuntReturns { get { return this._puntReturns; } set { this._puntReturns = value; } } public int PuntReturnTDs { get { return this._puntReturnTDs; } set { this._puntReturnTDs = value; } } public int KickoffReturns { get { return this._kickoffReturns; } set { this._kickoffReturns = value; } } public int KickoffReturnTDs { get { return this._kickoffReturnTDs; } set { this._kickoffReturnTDs = value; } } // default class constructor...required here for serialization public SpecialTeams() {} // overloaded class constructor public SpecialTeams(string name,string position,string jerseynumber,string team,int punts,int puntReturns,int puntReturnTDs,int kickoffReturns,int kickoffReturnTDs) { base.Name = name; base.Position = position; base.JerseyNumber = jerseynumber; base.Team = team; this._punts = punts; this._puntReturns = puntReturns; this._puntReturnTDs = puntReturnTDs; this._kickoffReturns = kickoffReturns; this._kickoffReturnTDs = kickoffReturnTDs; } }[XmlRoot("Leaderboard")] public class Leaderboard { [XmlArray("Offense")] [XmlArrayItem("Player")] public Offense[] offensePlayers; [XmlArray("Defense")] [XmlArrayItem("Player")] public Defense[] defensePlayers; [XmlArray("SpecialTeams")] [XmlArrayItem("Player")] public SpecialTeams[] specialteamsPlayers; }As you can see, the Leaderboard class contains arrays of Offense, Defense and SpecialTeams objects to generate rosters of the statistical leaders in those respective categories, and it's this latter class that's returned by the Web service. Pretty cut-and-dry stuff, and far from groundbreaking. But here's where I noticed a gotcha: while the eventual XML generated contains all the fields and properties from the subclasses, as one would expect, the .ASMX file does not include the fields within the base class.In my particular implementation, I'm reading values from a DB, which are read into the dataset and then passed as arguments to overloaded constructors of the Offense, Defense and Special Teams classes.However, this is the sample response the .ASMX file generates:<?xml version="1.0" encoding="utf-8"?> <Leaderboard xmlns=""> <Offense> > </Offense> <Defense> <Player> <Interceptions>int</Interceptions> <InterceptionTDs>int</InterceptionTDs> <FumbleRecoveryTDs>int</FumbleRecoveryTDs> <Tackles>int</Tackles> <Sacks>int</Sacks> <Safeties>int</Safeties> </Player> <Player> <Interceptions>int</Interceptions> <InterceptionTDs>int</InterceptionTDs> <FumbleRecoveryTDs>int</FumbleRecoveryTDs> <Tackles>int</Tackles> <Sacks>int</Sacks> <Safeties>int</Safeties> </Player> </Defense> <SpecialTeams> <Player> <Punts>int</Punts> <PuntReturns>int</PuntReturns> <PuntReturnTDs>int</PuntReturnTDs> <KickoffReturns>int</KickoffReturns> <KickoffReturnTDs>int</KickoffReturnTDs> </Player> <Player> <Punts>int</Punts> <PuntReturns>int</PuntReturns> <PuntReturnTDs>int</PuntReturnTDs> <KickoffReturns>int</KickoffReturns> <KickoffReturnTDs>int</KickoffReturnTDs> </Player> </SpecialTeams> </Leaderboard> Note that the fields inherent to each class are represented, but the inherited fields (Name, Position, JerseyNumber, and Team) aren't there. This is consistent through the sample response content generated for requests made through SOAP, HTTP-GET and HTTP-POST. However, everything comes out perfectly, as expected, when executing the method and examining the XML. Certainly, a consumer of the Web service can see the true XML returned by invoking the method, but it makes for some unexpected surprises and misdirection when the true data to be returned isn't reported. If this was the result of ignorant on my part or a genuine flaw in the .NET Framework, I'd just like to know which. Either way, it didn't produce the results I expected, although fortunately, it still worked perfectly in the final wash. I researched this for awhile, and tried a few different approaches, and I thought I got it right.Anyone else run into this? VS.NET *should* wrap all attributes with quotations by default I’ve got a comment/suggestion about the way VS.NET Whidbey handles the values for HTML attributes and declarative control properties. If the intent is to truly output XHTML 1.0, I was assuming that the IDE would naturally generate attributes and properties that would be surrounded by quotes (i.e., <a href=“adoc.html”>, <asp:Label id=“myLabel”/>). However, I’ve often found that when IntelliSense tries to autocomplete values in the way I’ve been used to since the Visual InterDev days (hitting “TAB” to autocomplete a statement, member or method), the quotes get left off and write out the above examples like this: (<a href=adoc.html>, <asp:Label id=myLabel/>). I’d like to suggest that these type of statement completions be set to wrapped in quotes automatically. Is this just me or is this a known **bug**? Suggestion: all IEWebControls should ship as part of ASP.NET 2.0 I've got a quick suggestion I'm hoping Microsoft would consider: can the IEWebControls (TabStrip Control, et al.) ship as part of the standard package for ASP.NET 2.0? I think the TreeView is great, and it would be perfect if the controls that could be downloaded with 1.x came out-of-the-box with Whidbey. However, I assume that some of the control aren't fully compliant with all browsers (DHTML issues and whatnot), or at least they weren't a few years ago wheh I first read about them. Kinda funny how I'm blogging now... It's actually humorous how I have an ASP.NET blog now...nearly 8 months ago today I wrote an article citing the dsangers of documenting your life experiences for the world to see. Can you spell H-Y-P-O-C-R-I-T-E? :) Open "casting call" for .NET book publishers - what ya got comin' for 2.0? Hi all, I’d like to make an open “casting call” (sorry, I’m in the TV biz) to all book publishers to post either lists or links to all the books you’ve got in the works or in the planning phases for.NET 2.0. The general consensus seems to be that there were a helluva lot more titles on the market even in the days of .NET Beta 2 than there were for ASP 3.0, which at that point had been out for a couple of years. Many speculate that the number of .NET 2.0 books will surpass that number, so I’d like your feedback on what you’re going to be putting out onto our shelves and into our laps. General omnibus titles? Specific, market niche books? A little but of both? Thanks for your input! Anxiously waiting for Dino's ASP.NET 2.0 book I've been through the first two “official” books to make it to print: ..and I'm anxiously waiting for Dino Esposito's title “Introducing ASP.NET 2.0“ by MSPress to come out (Feb. 2004 I think). I've asked O'Reilly and the rep said they've not got any beta books planned as of yet. Dino's writing is always very example-driven, and he's a great writer. So in the time until Dino's book is out, I'd wholeheartedly recommend that any experienced ASP.NET developer get the first two as soon as you can. They each have their distinct advantages, but actually contain enough information in differing ways that they compliment each other nicely. Amazon doesn't “recommend” buying both as a package deal, but it's a good thought. The Addison-Wesley text is slightly more technical from an archirtectural standpoint, and is therefore more conceptual. It gives insight into many of Whidbey's new APIs and new methods available to you, and highlights several new features like precompilation. The APress title is more hands-on, and is more code-rich. The thing I like best is that the introductory chapters deal with the new langauge features like Generics, and then uses them practically in examples. The use of Generics is especially appreciated. I read them in the order they're listed above, and they're a must-have. Book Review: A First Look at ASP.NET v 2.0 The scientist Louis Pasteur is famous for, amongst other things, saying, “chance favors the prepared mind.” With Whidbey on the horizon, Dave Sussman, Alex Homer and Rob Howard, are getting you prepared for battle, as you combat long, drawn-out development sessions and having to write thousands of lines of code. You’ll definitely want to pick up a copy of this book to properly arm yourself. Whether you’re an existing alpha tester or one of the many who is privy to a PDC copy of Whidbey, this is the definitive source you’ll want in your arsenal for the next evolution of ASP.NET. There’s code galore, and the concepts are explained easily and well, while still mixing in the specifics of how the next version of .NET will help you become a better web developer. The book’s hearty 470+ pages display a tone that is friendly and comforting, which is a plus when taking into consideration the literal piano of information about new features and enhancements that will be dropping on you. It seems to be best read by an experienced ASP.NET developer, familiar with concepts and terms inherent to Microsoft web development. One will quickly welcome the perspectives given on a variety of topics from caching to the new server controls, to the enhancements Version 2.0 of the .NET Framework delivers. The book does not completely marry the reader to the Whidbey version of Visual Studio .NET, rather presenting the code examples in an IDE-agnostic manner, so as to still appeal to the NotePad enthusiast in all of us. Still, the vast and massive improvements to VS.NET itself are well documented. All the book’s examples are presented in Visual Basic .NET, which isn’t so bad, as one of the key points of the title is that Whidbey’s new model minimizes the authoring of code itself, so you can concentrate more on working with encapsulated server controls and optimizing your web apps through intelligent configuration and management utilities. A very healthy chapter on Web Parts and Whidbey’s model for the portal framework is most appreciated, and the ease by which you’ll sift through the accompanying code just goes to prove how much better developing web-based applications will be once Whidbey arrives. Equally-thick chapters on new aspects of the feature set such as master pages, membership, and personalization, as well as great discussions of the improvements to the existing security, data controls, configuration and administration. The book also does a great job of keeping multi-platform application development in mind, constantly mentioning the capabilities of Whidbey to generate output for both the desktop-based and mobile browser. My personal favorite new feature of ASP.NET 2.0 is Web Parts and Personalization, and the book has a great deal of information on both. The book proves that not only has Microsoft listened to customers and thought way ahead in developing the next big thing, but the title’s authors themselves answer many questions you’d likely ask. If you’re wondering if this book (and Whidbey in general) is worth it – believe the hype. Get this book now. You’ll be very happy you did, and will be anxiously anticipating the release of Beta 1. Book Review: ASP.NET 2.0 Revealed This IntelliSense for web.config files in Whidbey I bounced the topic of IntelliSense for web.config off the ASPAdvice general mailing list for Whidbey (aspnetv2@aspadvice.com), commenting about how I love the fact that syntax gets coloration treatment, as do all XML files (I haven't tried XSLT files yet). However, as sweet as it is, it's a let down without IntelliSense support, which is a downer, seeing as most values in config files are emulation-based. Scott Guthrie shot back a message later and said that's definetly in the works. Awesome. Book review: "The C# Programming Language" I've posted a review to comment on “The C# Programming Language” from Addison-Wesley, which is the C# language spec. It's not a tutorial, but you'll like it. Suggestion: WebPartManager should be auto-included on page I’ve got a couple of suggestions on how Visual Studio .NET handles Web Parts. First, one of the requirements of getting Web Parts to work properly is that an instance of a WebPartManager object needs to be present on a page. I was surprised to discover that the Visual Studio .NET alpha does not add a WebPartManager automatically when WebPartZones are added visually through drag-and-drop to a WebForm. To date, publicly-available samples like the PDC Hands-On Labs and Whidbey documentation, indicate a WebPartManager needs to be manually added to a page, either programmatically or declaratively. This actually struck me as surprising, considering how the IDE automatically handles other aspects of the .NET Framework. Microsoft indicates that Web Parts can be “used” without an accompanying WebPartManager, however in doing so, WebPartZones are then only able to render content, sacrificing the key functionality Web Parts were meant to deliver (i.e., displaying a title bar, allowing draggable repositioning, etc.), making them the functional equivalent of Literal controls, which would appear to be a terribly inefficient method just for displaying content. I can realistically foresee the lack of a WebPartManager control as being a problem that developers of all levels will have when working with Web Parts that won’t seem to work as advertised, being one of the most-asked questions in forums, UseNet, mailing lists, etc. (Question: “Why doesn’t my page display WebParts correctly?” / Answer: “Did you include a WebPartManager?”) Therefore, if the placement of a WebPartManager object on a page is “mandated” for Web Parts to work properly, I suggest it be included automatically by VS .NET when a WebPartZone control is dropped onto a page. This to me seems logical and would be consistent with the other ways the IDE manages server controls. Perhaps if the use of a WebPartManager is optional, either allowing for developer preference or to leave flexibility for future functionality that doesn’t require its presence, a smart tag could be included that would create/configure a WebPartManager object, much in the same way datasource controls are created for data-bound controls (i.e., a SqlDataSource context menu being available when adding a GridView control). Second, the publicly-available examples indicated that a WebPartManager control can be included anywhere within a WebForm, and various conventions make various recommendations about the best locale for its placement. Patrick Lorenz, in his excellent book “ASP.NET 2.0 Revealed”, suggests standardizing placement of a WebPartControl within a WebForm’s server-side <HEAD> tags. Personally, I think it’s rather eerie that the control is allowed to just sit anywhere on a page. Some people may like this liberal, unregulated approach, but I tend to rely on a bit more on discipline and rules in guiding my coding, so I’d prefer it if a WebForm’s WebPartZone’s were required to be encapsulated/wrapped physically by a WebPartManager control. <asp:WebPartManager id=“manager” runat=“server”> <webpartzone id=“zone1” runat=“server”> This is content for zone1 </webpartzone> <webpartzone id=“zone2” runat=“server”> This is content for zone2 </webpartzone> </asp:WebPartManager> Still, looking at the overall behavior of Whidbey, the datasource controls (e.g., SqlDataSource, ObjectDataSource, et al.) don’t require specific placement on a page, and likewise don’t wrap around the control(s) they bind to. The general behavioral practice at this point seems to be laying them at the bottom of a WebForm. If this de facto convention becomes the general practice, I won’t complain. Just thought I’d throw this out. Thanks for listening! What do you think? Suggestion for ASP.NET 2.0: add an e-mail validation server control I sent this today to the ASPAdvice mailing list...comments? I’d like to make a suggestion for a new validation server control I’d like to see shipped as part of ASP .NET2.0 – an e-mail validation server control. I’d like to see a control that would internally contain a default regular expression (e.g., ^[\w-]+(?:\.[\w-]+)*@(?:[\w-]+\.)+[a-zA-Z]{2,7}$) that would validate the form of a given e-mail address, ensuring proper formatting. Certainly this is possible by using a RegularExpressionValidator, but it would be great to see this come right out-of-the-box. With all of the encapsulated functionality that 2.0’s rolling out, I think this would be a logical and very valuable addition to the feature set. What I’m proposing is this: a control that would by default, validate universally-used e-mail formats. It would also contain a public property that would, if set, override the aforementioned default behavior and allow the developer to implement their own validation rule. Additionally, the server control would, upon submission attempt, make a network call and validate the existence of an e-mail address. Most developers who are savvy enough to do this on their own or know where to find resources to help them build these types of controls, like, do it all the time, and lesser-experienced devs have a hard time with this and ask about it constantly. Thanks for listening! Working on Web Parts, C# 2.0 Generics... Well,); } } }
http://weblogs.asp.net/jasonsalas/archive/2003/12
CC-MAIN-2014-35
refinedweb
10,470
54.93
: - Explain how to configure incident SLAs in Service Manager 2010. - Explain how to use the plug and play solution that we built for managing SLAs. - Explain how we built the solution and in particular how to create custom Windows Workflow Foundation activities that use the Service Manager SDK. How to Configure Incident SLAs in Service Manager ‘Target Resolution Time’) is set to the time the incident was created plus 30 minutes per the configuration shown above. Out of the box you can manage incidents which are still active past their target resolution times by using the ‘Overdue: - Have a view of incidents which are within X minutes of breaching the SLA – see this blog post but instead of doing it for Last Modified do it for Target Resolution Time is Less Than [Now] + 30m (or whatever your desired warning threshold is). - Send a notification to the assigned to analyst when the incident is X minutes away from breaching SLA. - Send a notification to a manager when the incident is X minutes away from breaching SLA. Send another one when it has breached SLA. - Escalate/route an incident automatically when the incident is X minutes away from breaching SLA or when it has breached SLA. To detect and act upon incidents about to or breaching their SLA (their Target Resolution Time) you can use the built in workflow engine of Service Manager 2010. Here is how you can use this solution we provide in this blog post. Deploying the Solution - - Copy the following DLLs to the C:\Program Files\Microsoft System Center\Service Manager 2010 directory:! 2. Import the management pack Microsoft.Demo.IncidentSLAManagement.xml into Service Manager. Note – you can optionally configure how frequently the workflow that checks service levels runs. By default is every 15 minutes. Make sure you decide how often you want it to run before you import and don’t run it too frequently! Just search for ‘Minutes’ in the XML and you’ll see where it is set to 15. Just change it to some other number if you want before you import. 3. Go to the Administratoin/Settings view in the console. Double click on Incident SLA Management Settings and configure the warning threshold. This is the threshold at which you will change the incidents’ SLA status to Warning. By default it is zero meaning there is no warning interval.. - First go to the Library/Templates view and create a new incident template that will route/classify your incidents according to what you want – for example, if when incidents change to SLA Status = Breached you want to chnage the support group to ‘Escalation Team’ then in the new incident template set the Support Group = ‘Escalation Team’. - Navigate to the Administration/Workflows/Configuration view. - Select the Incident Event Workflow Configuration row and click Properties. - In the workflow dialog that comes up click Add. - Click Next on the welcome page of the wizard (if it comes up) - Provide a name for the workflow like ‘Escalate SLA Breaching incidents to the Escalation Team Support Group’. - Select ‘When an incident is updated’. - Select the Incident SLA Management MP. 9. Click Next. 10. On the criteria page set it up so that “when the SLA Status change to Breached” the workflow will be triggered like this: 11. Click Next. 12. On the template screen, select the incident template you created in step #1. Click Next. 13. Optionally choose to notify people related to the incident. Click Next. Note: We have provided a couple of “out of the box” notification templates – one for ‘Incident SLA Status – Warning’ and one for ‘Incident SLA Status – Breached’. 14. Click Create. 15. Click Close.. How We Built the Solution Note: This part is intended more for developers! The solution is comprised of the following parts: - Incident class extension to add a new enum property for SLA Status - Enum values for ‘Breached’ and ‘Warning’ - New class for capturing the Warning Threshold administration setting - Custom form for displaying the Warning Threshold - Custom task to display the Warning Threshold settings form when the user clicks ‘Properties’ in the Administration/Settings view - 2 notification templates – one for breached and one for warning - 2 views – one for breached and one for warning and a new folder to put them in - New custom Windows Workflow Foundation activity that queries the database looking for objects which are in a warning state or breached state and marks them accordingly - Rule that runs on a schedule that runs the custom Windows Workflow Foundation activity. - The first one gets incidents which are currently breaching SLA and which have not already been marked as breaching. - The second one gets incidents which are within the Warning Threshold of breaching SLA and have not already been marked as warning. - The last one gets incidents which have been marked as Warning, but because the target resolution time has since been adjusted (due to the incident urgency/impact changing) are no longer in a warning state.. Using Custom Workflow Activities in the Authoring Console To use this new custom workflow activity: - Copy the .dll from the bin\debug or \bin\release folder of your project and copy it to C:\Program Files (x86)\Microsoft System Center\Service Manager 2010 Authoring\Workflow Activity Library - Start the Authoring Tool - Create a new Management Pack (or open an existing one) - Create a new workflow by right clicking on the workflows node and choosing new and going through wizard - When the activity toolbox comes up, create a new “group” in the tree to organize your custom activities by right clicking the top level ‘Activity Groups’ node in the tree and choosing ‘Create Group’. - Right click on that new group and click on ‘Choose Activities…’ - In the dialog that comes up, click ‘Add Custom Activities…’. - Then select your assembly .dll and click Open - Then select your activity in the list and click OK - Now your activity will show up in the Activity Toolbox and you can drag it into the workflow designer. Conclusion! Join the conversationAdd Comment Hi, This is solution was really missing from SCSM, so I’m happy that it is finaly here. If you want to enable or disable the ProcessIncidents workflow, then you can’t do it here: Administration/Workflows/Configuration instead you can do it here: Administration/Workflows/Status. @Ulvenator Have you checked out the source code for this project yet? You need to exposed DependencyProperty in your workflow activity something like this: public static DependencyProperty UserNameProperty = DependencyProperty.Register("UserName", typeof(string), typeof(GetSLABreachingIncidents)); [DescriptionAttribute("If not specified, the defined workflow account will be used.")] [CategoryAttribute("Test configuration")] [BrowsableAttribute(true)] [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)] public string UserName { get { return ((string)(base.GetValue(GetSLABreachingIncidents.UserNameProperty))); } set { base.SetValue(GetSLABreachingIncidents.UserNameProperty, value); } } Then you need to bind the property to the appropriate property of the object that is triggering the workflow. To do this you need to drop your workflow activity onto the designer. Then your dependency properties will show up in the properties pane. Click the … button next to the property name you want to bind. Select the bottom radio button in the dialog that comes up. Then choose the property that you want to bind to. See some of the other demo videos on the blog here to get an idea for this binding stuff. Hope that helps! Hi Travis, Is there at least a workaround for the locale issue? Would be good to know, thanks. James Currently the solution doesn’t support business hours when doing the calculation. Though, this is a feature we’ve added as a work item on the codeplex site for the solution. Thanks for letting me know.? @Ozge – If you trust the download location you can continue on this message. The reason that this error shows up is because the SLA .dll is not signed. @Petter Do you have the RTM version of Service Manager installed? Can you please check the event log to see if there is anything there? Currently the solution doesnt support business hours. We’ve added that as a work item for us to implement on the code plex site already though. Feel free to suggest other improvements on the project site: inteluser – please follow the instructions in this blog post to see if you can discover the issue and report back what you find: blogs.technet.com/…/troubleshooting-workflows-in-service-manager.aspx Inteluser – You imported the MP, and copied the DLLs to the right places as described in the read me file in the download pacakage? @Eduardo – No sorry not in SCSM 2010.. We are investigating when we can include business hours support (and in general better SLA management) in the SCSM product. Did you derive your workflow activity from our base activity class (WorkflowActivityBase)? @Gayathri Kandukuri – Service Level Management is built into SCSM 2012. Please see this blog post for details: blogs.technet.com/…/notifying-before-sla-breaches.aspx In step#1 in the deployment section above there is a link to a page on CodePlex where you can download the solution. There are a bunch of .dll files and the .xml file in that package. @Steffen – I looked into that bug about a month ago but couldnt figure out why it was happening. My hunch is that it happens when your SQL server is installed with a different locale than your management server or something like that. Could that be the case in your environment there? "Import the management pack Microsoft.Demo.IncidentSLAManagement.xml into Service Manager" How do you do this? Where is the XML file? Thanks Hi Travis, We have followed your instructions and were able to import the management pack. When we view the breached incidents view it is showing up as all our incidents being breached. We have checked the resolve by date on majority of these incidetns anf they are not breached. We would highly appreciate your assistance here please. @Petter – yes, likely this is the same date/time formmating issue that others have described in the comments here. I'll try to get this fixed in the next week or so and post a new release of the Incident SLA solution on CodePlex. Hello Travis, I have read this article in conjunction with another thread, “Using webservices in SCSM”. With the above article, I’m trying to build a workflow (with the VS 2010 Workflow Activity Library) which will call a webservice (or just do a simple http request) when an incident is updated in SCSM, and send incident properties such as Id, status, description, affectedUser. Could you possibly provide more detail on how to accomplish this? From the code example above, I don’t understand how to capture the properties of an Incident which is being updated and use them in the Execute method. Any help with this would be greatly appreciated! . Hi. I can't get incidents to automatically change their SLA status to 'breached', or get the automatic email notification. Also, where is the 'Service level agreement tracking' view? Any ideas? Thansk in advance! Thanks for the quick reply. Yes. I think I have done this correctly because I have the SLA options available to me in SCSM. Hi I have copied the DLLs to the right place and imported the MP whit no problem, but it dosent work? I can see the SLA Status field in the Extensions tab (it's blank)in the incident form. The folder and SLA views are created but empty, i have incidents that has gone over the treshold for both warning and breached. If i look in the workflow/status and open incident SLA management, under worlflow instaces that need attention is empty. What can be the problem? Thanx in advance. Regards Petter Hi Travis Yes it is the RTM version of SCSM installd. I have check the event log but i can not see any problem there. Can this have anything to do whit the date and time format, i use the following format: yyyy-MM-dd and HH:mm ? Hi Travis, I would love to use your extension too, but i have the same problem with the date/time bug so that the workflow won't run. Are you still working on this extension? Any chance to fix this issuse? Thanks @ Travis Hmm my first reply to your response is missing – strange. Well thanks for your answer, I will have to check that and will report back @ Travis local seems to be the same on both server – English. But I noticed, that SP1 for the SQL Server is not installed. Is that one needed? Cased Dimensions have also written an SLA Management Pack for Service Manager. The product works inside Service Manager as a Management Pack. A self-install wizard unpacks and installs the functionality Functions include additional features such as calendaring, Change and Problem SLA's, alerting should SLA's be exceeded and much more. For information, please visit This Management Pack is easy to deploy and wizard driven for configuration. Hi Travis, I know this is an old post but if you're still watching it, I've followed your instructions to try and make a new activity (to perform a different function) to use in the Authoring Tool. However, after I add my custom activity assembly, my activity does not show up in the activities list. Any quick ideas of why? Thanks, Rob @Travis Yes, Base Class is set to "Microsoft.EnterpriseManagement.Workflow.Common.WorkflowActivityBase" and the declaration is: public partial class IncidentProcessingActivity : WorkflowActivityBase I am using SCSM 2010 SP1. I copied the dll files and import the MP without error. When I go to Settings/Incident SLA management Setttings, I get the following error on the pop-up window: This task will run the following unverifiable code: Assembly: Microsoft.Demo.IncidentSLAManagement.SettingsForm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null Handler: SettingsConsoleCommand Would you like to comtinue? Any news on this working with SCSM 2010 SP1? @Fletcher I have installed this on SCSM2010 SP1 and it works great. No issues during installtion or use. @SAM many thanks, will give it a go. Thanks Hi, I'm new to SCSM and am currently demoing the product. I have the problem with SLA status not being updated to breached on incidents. There was talk of a fix, but I don't see anywhere to get it after reading through the comments. Has anyone figured out how to correct this? I can't use SCSM without this working. We have followed your instructions and import the management pack. When we view the breached incidents view it is showing up as all our incidents being breached. We have checked the resolve by date on majority of these incidetns and they are not breached. We would highly appreciate your assistance here please. How can i delete this solution, is it possible to reverse all changes, can you give an instruction, is it right to delete all MP and change all .dll that i changed for their original version from SP1 Hi friends, I would like to know if is possible stop the SLA/Resolution Time for incidents with the pending status. Can i stop the count when the status is set to pending? Thanks in advance, Best Regards, Eduardo Nóbrega i'm trying to import the management pack but the service manager console hangs for ever. i have to restart the Service manager service to be able to open the console again. i followed all the instructions and copied the dll files, what did i do wrong? no event is pointing out the problem. thanks Hi travis After importing Incident SLA Management pack i got an error when i am going to edit settings in administration tab ERROR "Could not load assembly file" i have SCSM 2010 SP1 CU2 installed. Hi, I have imported SLA management pack it works when i just imported and capture all breaching incidents but its not running after 15 minutes i am usin SCSM SP1 2010 CU2 kindly reply its urgent Hi Travis, I have the same issue with others. The workflow doesnt set the status to warnin neither breached. We have install the SQL with Latin_100 for Turkish support and the system locale on the server is EN (USA). Then we have changed the system locale to Turkey but this doent solve the issue neither. Any advice would be appreciated on how to operate the SLA MP solution. Regards ozge Hi Travis, We got SCSM 2012 in our environment, and I had configured SLA management by refering to site thelazyadmin.com/…/scsm-2012-sla-management-part-1. Email from due to SLA management are not getting triggered and looking at even log I find error as below.. "While processing notification templates (1): 50dc32c2-6517-e9ea-dd99-0455383cab17 for subscription 00000000-0000-0000-0000-000000000000, the System Center Data Access service client failed to find an e-mail address for the following recipients: (1): scsmSD " Weird part is email's are getting triggered when ticket being assigned to anyone or something like that. I have got SCSU as service account, and notification channel id is configured as support. Thanks & Regards, Vamshi Gupta Hi I've implemented this solution to our environment, and it seemed to work perfectly. However i've noticed that it is marking every open incident as 'Breached'. We use the entire System Center suite, but in particular SCSM 2010 SP1 v 7.0.6555.0 and we are in the UK. Could you give me a clue as to where i can start looking to find the answer to make this work? Could it be a simple setting, the locale, bug in source code etc? I'm about to download the source code to see if i can see anything in there. Thanks in advance Michael Dear SCSM team, Warm Greetings! We are in the evaluation process of SCSM for a prospective client. We tried this with SCSM 2012. We needed to trigger a workflow on SLA breach. Is this compatible with SCSM 2012, in the first place? Because, once the MPs are imported, Service Manager gets closed. It gives the following error: Description: Stopped working Problem signature: Problem Event Name: CLR20r3 Problem Signature 01: MIISDOYLP4JANZLHYCZWCU3FX1QY0RNK Problem Signature 02: 7.0.5000.0 Problem Signature 03: 4f31c199 Problem Signature 04: PresentationFramework Problem Signature 05: 3.0.0.0 Problem Signature 06: 4f350630 Problem Signature 07: 5861 Problem Signature 08: d Problem Signature 09: System.ArgumentException OS Version: 6.1.7601.2.1.0.274.10 Locale ID: 1033 Read our privacy statement online: go.microsoft.com/fwlink If the online privacy statement is not available, please read our privacy statement offline: C:Windowssystem32en-USerofflps.txt Stuck with this issue from a week. Please help! Regards, Gayathri Why is the auto assigning of priority based on Impact & Urgency only available on Incident and not on Change? We wrote the original SLA Management solution for SCSM 2010 when SLO didn’t exist in SCSM. We offer a more performing and extensive offering including the following features: – Easy to identify VIP’s & view VIP employees within Views – Ability to see SLA & OLA information – Write OLA’s for each Activity within a Change, Service Request or Release Management Work Item. IE: OLA for each Manual Activity Template, OLA for each Approval Activity Template whilst having an overarching SLA for the Work Item – Easier SLA administration as SLA’s and OLA’s are not written against Work Queues – See video at Top Microsoft Support solutions for the most common issues experienced when you use System Center 2012
https://blogs.technet.microsoft.com/servicemanager/2010/05/06/incident-sla-management-in-service-manager/
CC-MAIN-2016-30
refinedweb
3,262
54.63
Syntax: #include <string> istream& std::getline( istream& is, string& s, char delimiter = '\n' ); The C++ string header defines the global function getline() to read strings from an I/O stream. The getline() function, which is not part of the string class, reads a line from is and stores it into s. If a character delimiter is specified, then getline() will use delimiter to decide when to stop reading data. For example, the following code reads a line of text from stdin and displays it to stdout: string s; getline( cin, s ); cout << "You entered " << s << endl; After getting a line of data in a string, you may find that stringstreams are useful in extracting data from that string. For example, the following code reads numbers from standard input, ignoring any “commented” lines that begin with double slashes: // expects either space-delimited numbers or lines that start with // two forward slashes (//) string s; while( getline(cin,s) ) { if( s.size() >= 2 && s[0] == '/' && s[1] == '/' ) { cout << " ignoring comment: " << s << endl; } else { istringstream ss(s); double d; while( ss >> d ) { cout << " got a number: " << d << endl; } } } When run with a user supplying input, the above code might produce this output: // test ignoring comment: // test 23.3 -1 3.14159 got a number: 23.3 got a number: -1 got a number: 3.14159 // next batch ignoring comment: // next batch 1 2 3 4 5 got a number: 1 got a number: 2 got a number: 3 got a number: 4 got a number: 5 50 got a number: 50 Because the getline() function begins reading at the current file position, it can also be used to read the remainder of a line, or any characters up to the specified delimiter. Related Topics: get, getline, stringstream
http://www.cppreference.com/wiki/string/getline
crawl-002
refinedweb
293
62.51
res.* osv.osv objects may be read() before being fully initialized Bug Description trying to implement https:/ adding this code to account/account.py class users(osv.osv): _name = 'res.users' _inherit = 'res.users' _columns = { } users() causes this error - the period_id s not added. [2009-11-05 18:00:09,054] INFO:init:module account: creating or updating database tables [2009-11-05 18:00:09,858] DEBUG:sql:bad query: SELECT "menu. File "/home/ addons. File "/home/ r = load_module_ File "/home/ init_ File "/home/ result = obj._auto_init(cr, {'module': module_name}) File "/home/ default = self._defaults[ File "/home/ if user.company_id: File "/home/ return self[name] File "/home/ datas = self._table. File "/home/ result = super(users, self).read(cr, uid, ids, fields, context, load) File "/home/ result = self._read_flat(cr, user, select, fields, context, load) File "/home/ self._order), sub_ids) File "/home/ return f(self, *args, **kwargs) File "/home/ res = self._obj. psycopg2. LINE 1: SELECT "menu_id" many time I face similar problem , when I try to add new field to existing object server restart may solve this problem if problem persist first compile the source code with python , then update your module list and then upgarde particular module for compiling use python2.5 /path-to -addons/ hope this will solve your problem otherwise feel free to contact On Thu, Nov 5, 2009 at 11:33 PM, Jan Verlaan (Verit discussio > http:// > > -- > error trying to add column to class users(osv.osv) > https:/ > You received this bug notification because you are subscribed to > OpenObject Addons. > > Status in OpenObject Addons Modules: New > > Bug description: > trying to implement > > https:/ > > adding this code to account/account.py > > class users(osv.osv): > _columns = { > 'period_id': fields. > help='Jail for accounting date entry'), > } > users() > > causes this error - the period_id s not added. > > [2009-11-05 18:00:09,054] INFO:init:module account: creating or updating > database tables > [2009-11-05 18:00:09,858] DEBUG:sql:bad query: SELECT > "menu_id" > FROM "res_users" WHERE id IN (1) ORDER BY. > tools.config[ > File "/home/ > get_db_and_pool > addons. > File "/home/ > 728, in load_modules > r = load_module_ > File "/home/ > 581, in load_module_graph > init_module_ > File "/home/ > 366, in init_module_objects > result = obj._auto_init(cr, {'module': module_name}) > File "/home/ > _auto_init > default = self._defaults[ > File "/home/ > line 1306... @Jan - good point - I'll do that - I was just thinking about chroot - it's often called jail .... @Vinay - did try to do so - but one has to take care to export PYTHONPATH to places where all the modules to be imported are located. I never had this problem before. .../base/ I have never seen "__admin_ids = {}" in another class might this be the reason prhibiting the change ? class users(osv.osv): __admin_ids = {} _name = "res.users" #_log_access = False _columns = { solved: after moving class users(osv.osv): _name = 'res.users' _inherit = 'res.users' _columns = { } users() to a separate file and imorting this as the first in account module - no more error nevertheless I leave the bug open because - I do not understand why this pice of code must be placed at the beginning - as it was not used at all - it should get a better error message if it is really necessary Hello Ferdinand, its a problem because, read() of user is called prior to period_id is added as a column to table. Read is called due to defaults of account_tax. 'period_id' is in ir_model_fields, but not yet into database. We will sort this out sooner. Thanks. I still have another problem res.user needs write permission to make the period_id enterable. In res_user.py def write(self, cr, uid, ids, values, *args, **argv): if (ids == [uid]): ok = True for k in values.keys(): if k not in ('password' .... seems to overwrite the permissions ??? I copied this + period_id to my account_user.py but nevertheless the field was not enterable same is true for document_sftp - the user has no permission to add his keys. there is onother serious problem after adding the period field to the accounting module in ONE database it is necessary to update all databases concurrently otherways no login is possible - complains of not finding period_id in the table serious, because it is unlikely that it is possible to update all databases "at once " so it has to be done one by one and the server must be restarted to make the very database working, whilst making it impossible to login in other databases not having received the update IMHO the idea was that the server executes the code which lives IN the database for each database, but apparently the code outside the database (from filesystem) is executed for all loaded/installed modules regardless if the db has received the last update. hope this explains what I mean Hi Folks, Its a limitation of openerp probably. v shud go for another py file in this kind of situation. I reopen this bug because I encountered the issue when adding a new field to res.users. The issue here is that the method _get_company (setting the default value for company) is called before the new columns are created (depending on the ordering of creation, which is arbitrary as it depends on the iteration order of a Python dict), and it performs a browse() on res.users, which forces a read() on all the columns… based on the OpenERP model, which includes columns not-yet created in the DB. Not only is this a huge problem to create new colums on users (and other objects reading themselves to setup default values), this could break OpenERP if the iteration order of dicts changes with e.g. Python 2.7, or if someone ever manages to make OpenERP run on IronPython or Jython: the field 'menu_id' in 'res.users' is in _columns but not created in base.sql, which means it's generated when created initializing res.users (indeed it is if you check the debug logs of creating a new db) and it just happens that in the iteration order of a Python dict puts 'menu_id' before 'company_id'. If that ever changes, res.users will break hard. This could (and, in fact, should) be fixed by creating *all* new columns before setting up the default values, then setting up all defaults, and finally applying the constraints (e.g. not null). I hope that people will pay attentions to this bug... Here are another strike of it: http:// I would like to play down the importance of this "bug". Some tables like "res.users", "res.company" etc. are supposed to be called nearly at each ORM call, and therefore must be pre-initialized. Try to avoid adding columns in them, it is also a performance issue. I remember we have these 'property' fields, couldn't we use them instead, for the functionality you describe? Note that this bug is mostly mitigated in pg84, by the fact that browse() doesn't fetch all columns by default. may be we can use res_config_users (which IMHO should be called res_users_config) for such issues. waht do you think/recommend and add a (dummy) res_company_config for the same purpose I have some ideas like * address label position (in Austria the envelops have the address window on the left side - envelops with the window on the right side are non standard, less choice available and about 30% more expensive) it could be a seldom used one2one relation On Friday 24 December 2010, you wrote: > ** Changed in: openobject-server > Assignee: Ysa(Open ERP) (ysa-openerp) => OpenERP's Framework R&D > (openerp- Q: why do we consider such an important change for v5.0 (or even v6.0 which is frozen now) ? Please, let the framework stay as is. We should queue these things for v6.1 preferably. Keeping this bugreport in radar for framework improvements after v6.0 Hello Folks, any notable progress here? Congratulations by the way, this bug has just completed 3 years last month. we call it 'szczęśliwy dzień urodzenia' in Polish. P.s. : I will proudly say my son that, you are not the only one I have been involved in the making of! :D Oops, my bad...it should be 2 years discussion http:// openobject. com/wiki/ index.php/ English_ Improvements# A-Z
https://bugs.launchpad.net/openobject-server/+bug/475621
CC-MAIN-2017-09
refinedweb
1,360
64.3
CLASS file A compiled Java source file. compilation unit A Java source file. field A field inside a type. import container Represents a collection of import declarations. These can be seen in the Outline view. import declaration A single package import declaration. initializer A static or instance initializer inside a type. JAR file JAR (Java archive) files are containers for compiled Java source files. They can be associated with an archive (such as, ZIP, JAR) as a source attachment. The children of JAR files are packages. JAR files can be either compressed or uncompressed. JAVA elements Java elements are Java projects, packages, compilation units, class files, types, methods and fields.JAVA file An editable file that is compiled into a byte code (CLASS) file. Java projects Projects which contain compilable Java source code and are the containers for source folders or packages. JDT Java development tools. Workbench components that allow you to write, edit, execute, and debug Java code. JRE Java runtime environment (for example, J9, JDK, and so on). method A method or constructor inside a type. package declaration The declaration of a package inside a compilation unit. packages A group of types that contain Java compilation units and CLASS files. refactoring A comprehensive code editing feature that helps you improve, stabilize, and maintain your Java code. It allows you to make a system-wide coding change without affecting the semantic behavior of the system. type A type inside a compilation unit or CLASS file. source folder A folder that contains Java packages. VCM Version control management. This term refers to the various repository and versioning features in the workbench. VM Virtual machine. Java development tools (JDT) Frequently asked questions on JDT
https://help.eclipse.org/oxygen/topic/org.eclipse.jdt.doc.user/reference/ref-jdt-glossary.htm
CC-MAIN-2018-30
refinedweb
283
61.33
You are here: Home » Articles » Hit The Ground Running With Vue.js And Firestore Firestore can directly be accessed using normal HTTP methods which makes it a full backend-as-a-service solution in which you don’t have to manage any of your own servers but still store data online. Sounds powerful and daunting, but no sweat, I’ll guide you through the steps of creating and hosting this new web app. Notice how big the scrollbar is on this page; there’s not a huge amount of steps to it. Also, if you want to know where to put each of the code snippets in a code repository, you can see a fully running version of Amazeballs on github. We’re starting out with Vue.js. It’s great for Javascript beginners, as you start out with HTML and gradually add logic to it. But don’t underestimate; it packs a lot of powerful features. This combination makes it my first choice for a front-end framework. Vue.js has a command-line interface (CLI) for scaffolding projects. We’ll use that to get the bare-bones set-up quickly. First, install the CLI, then use it to create a new project based on the “webpack-simple” template. npm install -g vue-cli vue init webpack-simple amazeballs If you follow the steps on the screen (npm install and npm run dev) a browser will open with a big Vue.js logo. npm install npm run dev Congrats! That was easy. Next up, we need to create a Firebase project. Head on over to and create a project. A project starts out in the free Spark plan, which gives you a limited database (1 GB data, 50K reads per day) and 1 GB of hosting. This is more than enough for our MVP, and easily upgradable when the app gains traction. Click on the ‘Add Firebase to your web app’ to display the config that you need. We’ll use this config in our application, but in a nice Vue.js manner using shared state. First npm install firebase, then create a file called src/store.js. This is the spot that we’re going to put the shared state in so that each Vue.js component can access it independently of the component tree. Below is the content of the file. The state only contains some placeholders for now. npm install firebase import Vue from 'vue'; import firebase from 'firebase/app'; import 'firebase/firestore'; // Initialize Firebase, copy this from the cloud console // Or use mine 🙂 var config = { apiKey: "AIzaSyDlRxHKYbuCOW25uCEN2mnAAgnholag8tU", authDomain: "amazeballs-by-q42.firebaseapp.com", databaseURL: "", projectId: "amazeballs-by-q42", storageBucket: "amazeballs-by-q42.appspot.com", messagingSenderId: "972553621573" }; firebase.initializeApp(config); // The shared state object that any vue component can get access to. // Has some placeholders that we’ll use further on! export const store = { ballsInFeed: null, currentUser: null, writeBall: (message) = console.log(message) }; Now we’ll add the Firebase parts. One piece of code to get the data from the Firestore: // a reference to the Balls collection const ballsCollection = firebase.firestore() .collection('balls'); // onSnapshot is executed every time the data // in the underlying firestore collection changes // It will get passed an array of references to // the documents that match your query ballsCollection .onSnapshot((ballsRef) = { const balls = []; ballsRef.forEach((doc) = { const ball = doc.data(); ball.id = doc.id; balls.push(ball); }); store.ballsInFeed = balls; }); And then replace the writeBall function with one that actually executes a write: writeBall writeBall: (message) = ballsCollection.add({ createdOn: new Date(), author: store.currentUser, }) Notice how the two are completely decoupled. When you insert into a collection, the onSnapshot is triggered because you’ve inserted an item. This makes state management a lot easier. onSnapshot Now you have a shared state object that any Vue.js component can easily get access to. Let’s put it to good use. First, let’s find out who the current user is. Firebase has authentication APIs that help you with the grunt of the work of getting to know your user. Enable the appropriate ones on the Firebase Console in Authentication → Sign In Method. For now, I’m going to use Google Login — with a very non-fancy button. Firebase doesn’t give you any interface help, so you’ll have to create your own “Login with Google/Facebook/Twitter” buttons, and/or username/password input fields. Your login component will probably look a bit like this: template div button @click.prevent="signInWithGoogle"Log in with Google/button /div /template script import firebase from 'firebase/app'; import 'firebase/auth'; export default { methods: { var provider = new firebase.auth.GoogleAuthProvider(); firebase.auth().signInWithPopup(provider); } } } /script Now there’s one more piece of the login puzzle, and that’s getting the currentUser variable in the store. Add these lines to your store.js: currentUser // When a user logs in or out, save that in the store firebase.auth().onAuthStateChanged((user) = { store.currentUser = user; }); Due to these three lines, every time the currently-logged-in user changes (logs in or out), store.currentUser also changes. Let’s post some Balls! store.currentUser The input form is a separate Vue.js component that is hooked up to the writeBall function in our store, like this: template form @submit.prevent="formPost" textarea v-model="message" / input type="submit" value="DUNK!" / /form /template script import { store } from './store'; export default { data() { return { message: null, }; }, methods: { formPost() { store.writeBall(this.message); } }, } /script Awesome! Now people can log in and start posting Balls. But wait, we’re missing authorization. We want you to only be able to post Balls yourself, and that’s where Firestore Rules come in. They’re made up of Javascript-ish code that defines access privileges to the database. You can enter them via the Firestore console, but you can also use the Firebase CLI to install them from a file on disk. Install and run it like this: npm install -g firebase-tools firebase login firebase init firestore You’ll get a file named firestore.rules where you can add authorization for your app. We want every user to be able to insert their own balls, but not to insert or edit someone else’s. The below example do nicely. It allows everyone to read all documents in the database, but you can only insert if you’re logged in, and the inserted resource has a field “author” that is the same as the currently logged in user. service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read: if true; allow create: if request.auth.uid != null request.auth.uid == request.resource.data.author; } } } It looks like just a few lines of code, but it’s very powerful and can get complex very quickly. Firebase is working on better tooling around this part, but for now, it’s trial-and-error until it behaves the way you want. If you run firebase deploy, the Firestore rules will be deployed and securing your production data in seconds. firebase deploy On your homepage, you want to see a timeline with your friends’ Balls. Depending on how you want to determine which Balls a user sees, performing this query directly on the database could be a performance bottleneck. An alternative is to create a Firebase Cloud Function that activates on every posted Ball and appends it to the walls of all the author’s friends. This way it’s asynchronous, non-blocking and eventually consistent. Or in other words, it’ll get there. To keep the examples simple, I’ll do a small demo of listening to created Balls and modifying their message. Not because this is particularly useful, but to show you how easy it is to get cloud functions up-and-running. const functions = require('firebase-functions'); exports.createBall = functions.firestore .document('balls/{ballId}') .onCreate(event = { var createdMessage = event.data.get('message'); return event.data.ref.set({ message: createdMessage + ', yo!' }, {merge: true}); }); Oh, wait, I forgot to tell you where to write this code. firebase init functions This creates the functions directory with an index.js. That’s the file you can write your own Cloud Functions in. Or copy-paste mine if you’re very impressed by it. Cloud Functions give you a nice spot to decouple different parts of your application and have them asynchronously communicate. Or, in architectural drawing style: Firebase has its Hosting option available for this, and you can use it via the Firebase CLI. firebase init hosting Choose distas a public directory, and then ‘Yes’ to rewrite all URLs to index.html. This last option allows you to use vue-router to manage pretty URLs within your app. dist index.html Now there’s a small hurdle: the dist folder doesn’t contain an index.html file that points to the right build of your code. To fix this, add an npm script to your package.json: package.json { "scripts": { "deploy": "npm run build mkdir dist/dist mv dist/*.* dist/dist/ cp index.html dist/ firebase deploy" } } Now just run npm deploy, and the Firebase CLI will show you the URL of your hosted code! npm deploy This setup is perfect for an MVP. By the third time you’ve done this, you’ll have a working web app in minutes — backed by a scalable database that is hosted for free. You can immediately start building features. Also, there’s a lot of space to grow. If Cloud Functions aren’t powerful enough, you can fall back to a traditional API running on docker in Google Cloud for instance. Also, you can upgrade your Vue.js architecture with vue-router and vuex, and use the power of webpack that’s included in the vue-cli template. vue-router vuex It’s not all rainbows and unicorns, though. The most notorious caveat is the fact that your clients are immediately talking to your database. There’s no middleware layer that you can use to transform the raw data into a format that’s easier for the client. So, you have to store it in a client-friendly way. Whenever your clients request change, you’re going to find it pretty difficult to run data migrations on Firebase. For that, you’ll need to write a custom Firestore client that reads every record, transforms it, and writes it back. Take time to decide on your data model. If you need to change your data model later on, data migration is your only option. Take time to decide on your data model. If you need to change your data model later on, data migration is your only option. So what are examples of projects using these tools? Amongst the big names that use Vue.js are Laravel, GitLab and (for the Dutch) nu.nl. Firestore is still in beta, so not a lot of active users there yet, but the Firebase suite is already being used by National Public Radio, Shazam, and others. I’ve seen colleagues implement Firebase for the Unity-based game Road Warriors that was downloaded over a million times in the first five days. It can take quite some load, and it’s very versatile with clients for web, native mobile, Unity, and so on. If you want to learn more, consider the following resources: Happy coding! (da,.
http://www.webhostingreviewsbynerds.com/hit-the-ground-running-with-vue-js-and-firestore/
CC-MAIN-2018-17
refinedweb
1,885
66.44
Hi, I recently set about making a simple application using python with some 3d components, i switched from PyOpenGL, because it was a little bit to complex for what I wanted to do, to VPython, which based on the YouTube video's looks very easy and simple... which is exactly what i want. But, whenever I try to import the visual module i get: from visual import * Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> from visual import * File "C:\Python26\lib\site-packages\visual\__init__.py", line 1, in <module> from .visual_all import * File "C:\Python26\lib\site-packages\visual\visual_all.py", line 1, in <module> from vis import version File "C:\Python26\lib\site-packages\vis\__init__.py", line 3, in <module> from . import cvisual ImportError: DLL load failed: %1 is not a valid Win32 application. this also happens with the examples that come with it. I'm running python26 with 64-bit windows 7. Thanks for any help
https://www.daniweb.com/programming/software-development/threads/344114/vpython-importing-error
CC-MAIN-2018-43
refinedweb
165
67.04
I can do most things with my laptop, why can’t I make it cook? I’ve attached sensors, motors, NMR, cameras, etc. why not a heater and a thermometer? Sous Vide, or immersion cooking produces great tasting food. It is also an interesting representative problem of closed loop temperature control. With numerous people trying to provide an open source or DIY solution for Sous Vide cooking, I figured I’d add to that body of work in my own way. I’d write a software simulation of an immersion cooker to help people develop better hardware. I don’t know what the time constants in the simulation might be, but you can set them, and learn PID control. I also might hook up a relay, a heater, and a thermo couple and actually do this, but mostly I figured I’d help others study basic PID control. PID control loops (Proportional, Integral, Derivative) are a basic form of closed loop control, meaning the error is fed back into the control loop and used to change how control is performed as opposed to open loop. In a PID loop, an error is calculated, and then three different terms are computed and summed to form a correction. The incoming error term may have known properties based on how the measurement was made or changes to the goal value, so sometimes pre-filtering is performed (FIR/IIR). The integral sometimes isn’t truly just adding up the errors but sometimes decays so it has a limited memory of past errors. The derivative term may be subtracting two noisy errors that are similar producing a large value that is mostly noise so sometimes the derivative value is filtered (FIR /IIR, outlier rejection, boxcar, etc.). Finally each of these terms may have a dead band, and the sum may too. A dead band means don’t adjust unless over +X threshold amount, or under –Y threshold amount. Further the control applied may also be filtered to remove control changes that would cause a harmonic pattern, such as oscillation. So with this in mind, a generic PID may have a large set of features (pre/post filters), dead bands, and pre /post conditioning filters, and a variety of integration like effects. In general, a PID filter can be thought of as a corrective loop, where you move closer to the goal proportional to the error perceived. In many cases a proportional gain is what’s needed. For example for servo motion where there is a large motor and a tiny weight, driving to position requires only a P term. If there is consistent pressure (weight) or loss (heat loss) proportional control may not be enough. The integral term adds up tiny errors, and corrects better than proportional when the error is small. The integral term may accelerate too much resulting in over correction and even oscillation, so the derivative term is then used like a break. There are several tuning techniques, the author prefers starting with Ziegler-Nichols. I set the proportional gain till it over controls resulting in oscillations I can measure. When the system is mostly linear, the oscillations will have fixed period. This proportional gain is the “ultimate” gain or Ku, and the period is Pu. From there: P only: P = 0.5*Ku PI only: P = 0.45*Ku, I = 0.54*Ku / Pu. PID: P = 0.6*Ku, I= 1.2*Ku/Pu, D = 0.075*Ku*Pu In most cases, this is close to good enough. In the case of a Sous Vide, overshoot (going too hot while attaining a temperature) is bad, and consistent undershoot is bad. It can take a known time to reach stability before we put the food in is ok. For this reason, backing off on I and D terms, and using a decaying integral are likely good ideas. There are many systems to compute “ideal” coefficients but they don’t arrive at the same answer, go figure. Ideal is based on your particular requirements, and simulation helps a lot. Integrating with the real system then tells you how much more work to do, it usually isn’t a check the box test unless you’re lucky or the control system was simulated perfectly, or it is relatively linear and or simple. Most problems I’ve used PID on started simple, then weight was cut, materials changed, etc. and at some point simulation became just a starting point. At some point PID stops working and a lookup table based on measurements for coefficients to interpolate from is required. That is the essence of an autopilot because that kind of algorithm can model non-linear processes that appear linear or quadratic over short numerical regions (perhaps a different article). My point is, PID usually can solve the problem if the problem is reasonable but there are other solutions that sometimes work better. If your problem seems too hard to solve because small changes in gains cause the system to behave strangely then likely there is a non-linear response to the correction and PID might not be the choice to use. For Sous Vide cooking, temperature isn’t linear in time (exponential) but it is a smooth effect, and over any short region of change if we treat it as linear, the error term isn’t huge or suddenly change sign. For those reasons PID will work, perhaps not ideally converging with zero overshoot but it works very well and is probably the most common way to handle heating control. The key thing is to bring food up to a target temperature ideal for that food, and hold it there for a period of time. For example to cook an egg so only certain proteins coagulate (perfect poached egg), or to make the perfect steak, or carrots, the food is cooked longer than needed at no more than the set temperature, and as close to the set temperature as possible. Above certain temperatures the heat only breaks down flavor and makes the food tougher for certain foods. Temperature: Min, Max. 1000F to 2200F (roughly 500C to 1000C) Accuracy 0.250F (threshold) 0.10F (goal) Stability Gaussian 1-sigma of accuracy to time constant of heat transfer. Overshoot Initial overshoot of water ok if food isn’t present. Need to know when food started to be at temperature to know how long to cook it. Physical Control: Either proportionally or pulse an AC heater. Pulsing with a solid state relay is probably cheapest, but the frequency of the pulses need to be realistic because they affect how well the heating element will accurately respond and the life of the heating element. Model Assumptions Slow -> Container/Air -> Container/Water -> Medium ->Bag/Food -> Others -> Fast Mathematics of Physics and Modern Engineering, McGraw hill publishing, 1966, by I.S. Sokolnikoff & R.M. Redheffer, p. 432. Indroduction to Applied Mathematics, Wellesly-Cambridge Press, 1986, by Gilbert Strang, p. 461, 536. The model can be describes as a set of heat transfers. Yes, the specific heat and energy could be modeled with a more classical thermodynamic model, but in the end the math reduces more or less to time constants and transfer from one singular thermal body to another. The heat escape path is: Water-> Container -> Air && Water->Air. The add path is: Heater-> Water The measurement path is: Water-> Sensor We can turn what could be a wacky looking differential equation into a set of difference equations . By making the simulation time arbitrarily small, the error is arbitrarily small, and computers are good at rapid repeated calculations. For this reason, FEA modeling or differential equations are just not needed (although a lot of fun, but not in this article). In short we can simulate multiple simultaneous heat transfers as heat adding or being lost across a given boundary, rewriting as a difference: Because the volume of water is varying, assuming a pot or rice cooker we can adjust the time constant based on the surface area to volume ratio and simulate those affects. We can also run the adjustment times at a different rate to the simulation time delta, and set weather control is proportional or pulsed and compare the results. Water volume effect: private void simulateTime(double dt, double percentHeat, ref double water, ref double container, <br /> ref double sensor, ref double food, Parameters p, PID pid, bool usePID) { // Limit to the max / min. percentHeat = percentHeat < 0 ? 0 : percentHeat > 100 ? 100 : percentHeat; // If binary, heater is on/off in which case threshold. if (p.Binary) { percentHeat = percentHeat > 25 ? 100 : 0; } double heaterAdded = percentHeat * p.HeaterWatts * heaterSpecificHeatFactor; // surface area is constant but thermal mass of the water isn't. double effectiveWaterContainer = p.TWC * p.WaterRadius * p.WaterDepth / (p.WaterRadius + 2 * p.WaterDepth); double effectiveWaterAir = p.TWA * p.WaterDepth; // Heat added from heater to water. double heatAddedToWater = (heaterAdded - water) * (1 – (1/ p.TWH) * System.Math.Exp(-dt / p.TWH)); heatAddedToWater = heatAddedToWater < 0 ? 0 : heatAddedToWater; // Heat lost to the sensor. double heatLostToSensor = (water - sensor) * (1-System.Math.Exp(-dt / p.TWS))/p.TWS; // Heat lost to the food. double heatToFood = (water - food) * (1 - System.Math.Exp(-dt / p.TWF)) / p.TWF; // Heat from water to container. double heatLostWaterContainer = (water - container) * (1 - System.Math.Exp(-dt / effectiveWaterContainer))/effectiveWaterContainer; // Heat water to air. double heatLostWaterAir = (water - p.Air) * (1 - System.Math.Exp(-dt / effectiveWaterAir))/effectiveWaterAir; // Heat Container to air. double heatLostContainerAir = (container - p.Air) * (1 - System.Math.Exp(-dt / p.TCA))/p.TCA; // Update. food = food + heatToFood; water = water + heatAddedToWater - heatLostWaterContainer – heatLostWaterAir - heatLostToSensor - heatToFood; sensor = sensor + heatLostToSensor; container = container + heatLostWaterContainer - heatLostContainerAir; } public class PID { double m_p = 0, m_i = 0, m_d = 0, m_g = 0, integral = 0, last = 0; bool first = true; public PID(double setPoint, double proportional, double integral, double derivative) { m_g = setPoint; m_p = proportional; m_i = integral; m_d = derivative; } public double Update(double sensor, double dt) { double error = m_g - sensor; integral = (0.9 * integral) + error; double derivative = first ? 0 : (sensor - last) / dt; last = sensor; first = false; return (m_p * error) + (m_i * integral) + (m_d * derivative); } } The following time constants in seconds were guessed at to produce are somewhat realistic simulation: Water-heater 600 Water-sensor 2 Water-container 1000 Container-air 1000 Water-food 20 Water-air 1000 Sure the time constants are made up. After gathering actual data, make educated guesses. For anything I’ve worked on (missiles, GPS motion, thermal control) it was always an estimate, a guess, the reality is even if you measure the exact value, when you get to production there is enough variation for the exact value not to matter. Simulation tied to real data ensures that if the production values vary, the gains provide for robust control anyways. One of the best ways to do this for real would be to turn the heater on at various fixed values and measure the steady state water and container temperatures, and look up the time constant for the thermocouple used, then make the model look like the curves seen for real, double checking with heat loss vs. heat added. Pure math often won’t do all the work unless your system is simple and well known (density of the plastic container, exact CAD model for shape, calibrated heater wattage, losses in switching on/off, etc.). It took a proportional gain of over 100 to start to see an initial overshoot, the inherent decay meant there is no real gain that will cause an oscillation. Using Ziegler-Nichols, and looking at the overshoot, the time to decay from an overshoot is in tens of seconds so IF Pu did exist it would be on the order of 5-20 seconds, and our gain ultimate (Ku) can be large (10 – 50). This provides ball park initial values to setup and study (Ku = 30, Pu = 10). P = 0.6*Ku, I= 1.2*Ku/Pu, D = 0.075*Ku*Pu P = 18, I = 3.6, D = 22.5 This resulted in the following graph: The problem is it was 0.2 degrees too cool for the second half of cook time, clearly we need more integral. Doubling the gains brought the system closer (62.69). Note what happened when I used non-proportional pulsed control: Because the food provide a sort of temperature buffer, it takes time to transfer water to food through the bag the food is in, a little water overshoot is desirable if accuracy is improved. For this reason we can play with the numbers and improve performance. If this was more than an intellectual exercise, the next step would be to randomly generate start water temperatures (which also has the affect of spontaneously adding food a different temperature to the bath after reaching temperature) as well as varying water-food time constant (simulate different volumes of foods, marinades in the food bag). Then show that for a given set of gains there is little overshoot, and very stable performance. For the most part, most gain choices will be stable enough, but some will get the water to the desired temperature faster than others, and in a commercial kitchen producing product on a time schedule that would mater. For teaching your lap top how to make tuna confit, or perfect harcot verts, a little simulation and some trial and error should be sufficient. The key result from the simulation suggests using a PID with a simple relay would work very well, and thus a rice cooker plugged into a relay controlled by a PID should (in theory) be.
https://www.codeproject.com/Articles/329012/SousVidePID?fid=1685414&df=90&mpp=10&sort=Position&spc=None&tid=4155277&noise=1&prof=True&view=Expanded
CC-MAIN-2017-39
refinedweb
2,246
53.51
Asynchronous programming has been gaining a lot of traction in the past few years, and for good reason. Although it can be more difficult than the traditional linear style, it is also much more efficient. For example, instead of waiting for an HTTP request to finish before continuing execution, with Python async coroutines you can submit the request and do other work that's waiting in a queue while waiting for the HTTP request to finish. It might take a bit more thinking to get the logic right, but you'll be able to handle a lot more work with less resources. Even then, the syntax and execution of asynchronous functions in languages like Python actually aren't that hard. Now, JavaScript is a different story, but Python seems to execute it fairly well. Asynchronicity seems to be a big reason why Node.js so popular for server-side programming. Much of the code we write, especially in heavy IO applications like websites, depends on external resources. This could be anything from a remote database call to POSTing to a REST service. As soon as you ask for any of these resources, your code is waiting around with nothing to do. With asynchronous programming, you allow your code to handle other tasks while waiting for these other resources to respond. Coroutines An asynchronous function in Python is typically called a 'coroutine', which is just a function that uses the async keyword, or one that is decorated with @asyncio.coroutine. Either of the functions below would work as a coroutine and are effectively equivalent in type: import asyncio async def ping_server(ip): pass @asyncio.coroutine def load_file(path): pass These are special functions that return coroutine objects when called. If you're familiar with JavaScript Promises, then you can think of this returned object almost like a Promise. Calling either of these doesn't actually run them, but instead a coroutine object is returned, which can then be passed to the event loop to be executed later on. In case you ever need to determine if a function is a coroutine or not, asyncio provides the method asyncio.iscoroutinefunction(func) that does exactly this for you. Or, if you need to determine if an object returned from a function is a coroutine object, you can use asyncio.iscoroutine(obj) instead. Yield from There are a few ways to actually call a coroutine, one of which is the yield from method. This was introduced in Python 3.3, and has been improved further in Python 3.5 in the form of async/await (which we'll get to later). The yield from expression can be used as follows: import asyncio @asyncio.coroutine def get_json(client, url): file_content = yield from load_file('/Users/scott/data.txt') As you can see, yield from is being used within a function decorated with @asyncio.coroutine. If you were to try and use yield from outside this function, then you'd get error from Python like this: File "main.py", line 1 file_content = yield from load_file('/Users/scott/data.txt') ^ SyntaxError: 'yield' outside function In order to use this syntax, it must be within another function (typically with the coroutine decorator). Async/await The newer and cleaner syntax is to use the async/await keywords. Introduced in Python 3.5, async is used to declare a function as a coroutine, much like what the @asyncio.coroutine decorator does. It can be applied to the function by putting it at the front of the definition: async def ping_server(ip): # ping code here... To actually call this function, we use await, instead of yield from, but in much the same way: async def ping_local(): return await ping_server('192.168.1.1') Again, just like yield from, you can't use this outside of another coroutine, otherwise you'll get a syntax error. In Python 3.5, both ways of calling coroutines are supported, but the async/await way is meant to be the primary syntax. Running the event loop None of the coroutine stuff I described above will matter (or work) if you don't know how to start and run an event loop. The event loop is the central point of execution for asynchronous functions, so when you want to actually execute the coroutine, this is what you'll use. The event loop provides quite a few features to you: - Register, execute, and cancel delayed calls (asynchronous functions) - Create client and server transports for communication - Create subprocesses and transports for communication with another program - Delegate function calls to a pool of threads While there are actually quite a few configurations and event loop types you can use, most of the programs you write will just need to use something like this to schedule a function: import asyncio async def speak_async(): print('OMG asynchronicity!') loop = asyncio.get_event_loop() loop.run_until_complete(speak_async()) loop.close() The last three lines are what we're interested in here. It starts by getting the default event loop ( asyncio.get_event_loop()), scheduling and running the async task, and then closing the loop when the loop is done running. The loop.run_until_complete() function is actually blocking, so it won't return until all of the asynchronous methods are done. Since we're only running this on a single thread, there is no way it can move forward while the loop is in progress. Now, you might think this isn't very useful since we end up blocking on the event loop anyway (instead of just the IO calls), but imagine wrapping your entire program in an async function, which would then allow you to run many asynchronous requests at the same time, like on a web server. You could even break off the event loop in to its own thread, letting it handle all of the long IO requests while the main thread handles the program logic or UI. An example Okay, so let's see a slightly bigger example that we can actually run. The following code is a pretty simple asynchronous program that fetches JSON from Reddit, parses the JSON, and prints out the top posts of the day from /r/python, /r/programming, and /r/compsci. The first method shown, get_json(), is called by get_reddit_top() and just creates an HTTP GET request to the appropriate Reddit URL. When this is called with await, the event loop can then continue on and service other coroutines while waiting for the HTTP response to get back. Once it does, the JSON is returned to get_reddit_top(), gets parsed, and is printed out. import signal import sys import asyncio import aiohttp import json loop = asyncio.get_event_loop() client = aiohttp.ClientSession(loop=loop) async def get_json(client, url): async with client.get(url) as response: assert response.status == 200 return await response.read() async def get_reddit_top(subreddit, client): data1 = await get_json(client, '' + subreddit + '/top.json?sort=top&t=day&limit=5') j = json.loads(data1.decode('utf-8')) for i in j['data']['children']: score = i['data']['score'] title = i['data']['title'] link = i['data']['url'] print(str(score) + ': ' + title + ' (' + link + ')') print('DONE:', subreddit + '\n') def signal_handler(signal, frame): loop.stop() client.close() sys.exit(0) signal.signal(signal.SIGINT, signal_handler) asyncio.ensure_future(get_reddit_top('python', client)) asyncio.ensure_future(get_reddit_top('programming', client)) asyncio.ensure_future(get_reddit_top('compsci', client)) loop.run_forever() This is a bit different than the sample code we showed earlier. In order to get multiple coroutines running on the event loop, we're using asyncio.ensure_future() and then run the loop forever to process everything. To run this, you'll need to install aiohttp first, which you can do with PIP: $ pip install aiohttp Now just make sure you run it with Python 3.5 or higher, and you should get an output like this: $ python main.py 46: Python async/await Tutorial () 16: Using game theory (and Python) to explain the dilemma of exchanging gifts. Turns out: giving a gift probably feels better than receiving one... () 56: Which version of Python do you use? (This is a poll to compare the popularity of Python 2 vs. Python 3) () DONE: python 71: The Semantics of Version Control - Wouter Swierstra () 25: Favorite non-textbook CS books () 13: CompSci Weekend SuperThread (December 18, 2015) () DONE: compsci 1752: 684.8 TB of data is up for grabs due to publicly exposed MongoDB databases () 773: Instagram's Million Dollar Bug? () 387: Amazingly simple explanation of Diffie-Hellman. His channel has tons of amazing videos and only a few views :( thought I would share! () DONE: programming Notice that if you run this a few times, the order in which the subreddit data is printed out changes. This is because each of the calls we make releases (yields) control of the thread, allowing another HTTP call to process. Whichever one returns first gets printed out first. Conclusion Although Python's built-in asynchronous functionality isn't quite as smooth as JavaScript's, that doesn't mean you can't use it for interesting and efficient applications. Just take 30 minutes to learn its ins and outs and you'll have a much better sense as to how you can integrate this in to your own applications. What do you think of Python's async/await? How have you used it in the past? Let us know in the comments!
http://stackabuse.com/python-async-await-tutorial/
CC-MAIN-2018-26
refinedweb
1,550
63.39
§Play 2.3 Migration Guide This is a guide for migrating from Play 2.2 to Play 2.3. If you need to migrate from an earlier version of Play then you must first follow the Play 2.2 Migration Guide. §Activator In Play 2.3 the play command has become the activator command. Play has been updated to use Activator. changes §sbt Play uses sbt 0.13.5. If you’re updating an existing project, change your project/build.properties file to: sbt.version=0.13.5 §Plugin changes Change the version of the Play plugin in project/plugins.sbt: addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.3.XXX") Where 2.3.XXX is the version of Play you want to use. You will also need to add some sbt-web plugins, see the sbt-web section below. §Auto Plugins and plugin settings sbt 0.13.5 brings a new feature named “auto plugins”. Auto plugins permit sbt plugins to be declared in the project folder (typically the plugins.sbt) as before. What has changed though is that plugins may now declare their requirements of other plugins and what triggers their enablement for a given build. Before auto plugins, plugins added to the build were always available; now plugins are enabled selectively for given modules. What this means for you is that declaring addSbtPlugin may not be sufficient for plugins that now utilize to the auto plugin functionality. This is a good thing. You may now be selective as to which modules of your project should have which plugins e.g.: lazy val root = (project in file(".")).enablePlugins(SbtWeb) The above example shows SbtWeb being added to the root project of a build. In the case of SbtWeb there are other plugins that become enabled if it is e.g. if you also had added the sbt-less-plugin via addSbtPlugin then it will become enabled just because SbtWeb has been enabled. SbtWeb is thus a “root” plugin for that category of plugins. Play itself is now added using the auto plugin mechanism. The mechanism used in Play 2.2 where playJavaSettings and playScalaSettings were used has been removed. You now use one of the following instead: lazy val root = (project in file(".")).enablePlugins(PlayJava) or lazy val root = (project in file(".")).enablePlugins(PlayScala) If you were previously using play.Project, for example a Scala project: object ApplicationBuild extends Build { val appName = "myproject" val appVersion = "1.0-SNAPSHOT" val appDependencies = Seq() val main = play.Project(appName, appVersion, appDependencies).settings( ) } …then you can continue to use a similar approach via native sbt: object ApplicationBuild extends Build { val appName = "myproject" val appVersion = "1.0-SNAPSHOT" val appDependencies = Seq() val main = Project(appName, file(".")).enablePlugins(play.PlayScala).settings( version := appVersion, libraryDependencies ++= appDependencies ) } By moving to the above style settings are now automatically imported when a plugin is enabled. The keys provided by Play must now also be referenced within the PlayKeys object. For example to reference playVersion you must do so either by importing: import PlayKeys._ or qualifying it with PlayKeys.playVersion. Outside of using a .sbt file i.e. if you’re using Scala to describe your build then you may do the following to have PlayKeys within scope: import play.Play.autoImport._ import PlayKeys._ §Explicit scalaVersion Play 2.3 supports both Scala 2.11 and Scala 2.10. The Play plugin previously set the scalaVersion sbt setting for you. Now you should indicate which version of Scala you wish to use. Update your build.sbt or Build.scala to include the Scala version: For Scala 2.11: scalaVersion := "2.11.1" For Scala 2.10: scalaVersion := "2.10.4". There are other advantages including the fact that sbt-web plugins are able to run within the JVM via Trireme, or natively using Node.js. Note that sbt-web is a development environment and does not participate in the execution of a Play application. Trireme is used by default, but if you have Node.js installed and want blistering performance for your builds then you can provide a system property via sbt’s SBT_OPTS environment variable. For example: export SBT_OPTS="$SBT_OPTS -Dsbt.jse.engineType=Node" A feature of sbt-web is that it is not concerned whether you use “javascripts” or “stylesheets” as your folder names. Any files with the appropriate filename extensions are filtered from within the app/assets folder. A nuance with sbt-web is that all assets are served from the public folder. Therefore if you previously had assets reside outside of the public folder i.e. you used the playAssetsDirectories setting as per the following example: playAssetsDirectories <+= baseDirectory / "foo" …then you should now use the following: unmanagedResourceDirectories in Assets += baseDirectory.value / "foo" …however note that the files there will be aggregated into the target public folder. This means that a file at “public/a.js” will be overwritten with the file at “foo/a.js”. Alternatively use sub folders off your project’s public folder in order to namespace them. The following lists all sbt-web related components and their versions at the time of releasing Play 2.3. §Libraries "com.typesafe" %% "webdriver" % "1.0.0" "com.typesafe" %% "jse" % "1.0.0" "com.typesafe" %% "npm" % "1.0.0" §sbt plugins "com.typesafe.sbt" % "sbt-web" % "1.0.0" "com.typesafe.sbt" % "sbt-webdriver" % "1.0.0" "com.typesafe.sbt" % "sbt-js-engine" % "1.0.0" "com.typesafe.sbt" % "sbt-coffeescript" % "1.0.0" "com.typesafe.sbt" % "sbt-digest" % "1.0.0" "com.typesafe.sbt" % "sbt-gzip" % "1.0.0" "com.typesafe.sbt" % "sbt-less" % "1.0.0" "com.typesafe.sbt" % "sbt-jshint" % "1.0.0" "com.typesafe.sbt" % "sbt-mocha" % "1.0.0" "com.typesafe.sbt" % "sbt-rjs" % "1.0.1" §WebJars WebJars now play an important role in the provision of assets to a Play application. For example you can declare that you will be using the popular Bootstrap library simply by adding the following dependency in your build file: libraryDependencies += "org.webjars" % "bootstrap" % "3.2 extract WebJar assets, the requirejs folder corresponds to the WebJar artifactId, and the require.js refers to the required asset at the root of the WebJar. §npm npm can be used as well as WebJars by declaring a package.json file in the root of your project. Assets from npm packages are extracted into the same lib folder as WebJars so that, from a code perspective, there is no concern whether the asset is sourced from a WebJar or from an npm package. From your perspective we aim to offer feature parity with previous releases of Play. While things have changed significantly under the hood the transition for you should be minor. The remainder of this section looks at each part of Play that has been replaced with sbt-web and describes what should be changed. §CoffeeScript You must now declare the plugin, typically in your plugins.sbt file: addSbtPlugin("com.typesafe.sbt" % "sbt-coffeescript" % "1.0.0") Coffeescript options have changed. The new options are: sourceMapsWhen set, generates sourceMap files. Defaults to true. CoffeeScriptKeys.sourceMaps := true bareWhen set, generates JavaScript without the top-level function safety wrapper. Defaults to false. CoffeeScriptKeys.bare := false For more information please consult the plugin’s documentation. §LESS You must now declare the plugin, typically in your plugins.sbt file: addSbtPlugin("com.typesafe.sbt" % "sbt-less" % "1.0.0") Entry points are now declared using a filter. For example, to declare that foo.less and bar.less are required: includeFilter in (Assets, LessKeys.less) := "foo.less" | "bar.less" If you previously used the behavior where files with an underscore preceding the less filename were ignored but all other less files were compiled then use the following filters: includeFilter in (Assets, LessKeys.less) := "*.less" excludeFilter in (Assets, LessKeys.less) := "_*.less" Unlike Play 2.2, the sbt-less plugin allows any user to download the original LESS source file and generated source maps. It allows easier debugging in modern web browsers. This feature is enabled even in production mode. The plugin’s options are: For more information please consult the plugin’s documentation. §Closure Compiler The Closure Compiler has been replaced. Its two important functions of validating JavaScript and minifying it have been factored out into JSHint and UglifyJS 2 respectively. To use JSHint you must declare it, typically in your plugins.sbt file: addSbtPlugin("com.typesafe.sbt" % "sbt-jshint" % "1.0.0") Options can be specified in accordance with the JSHint website and they share the same set of defaults. To set an option you can provide a .jshintrc file within your project’s base directory. If there is no such file then a .jshintrc file will be searched for in your home directory. This behaviour can be overridden by using a JshintKeys.config setting for the plugin. JshintKeys.config is used to specify the location of a configuration file. For more information please consult the plugin’s documentation. UglifyJS 2 is presently provided via the RequireJS plugin (described next). The intent in future is to provide a standalone UglifyJS 2 plugin also for situations where RequireJS is not used. §RequireJS The RequireJS Optimizer (rjs) has been entirely replaced with one that should be a great deal easier to use. The new rjs is part of sbt-web’s asset pipeline functionality. Unlike its predecessor which was invoked on every build, the new one is invoked only when producing a distribution via Play’s stage or dist tasks. To use rjs you must declare it, typically in your plugins.sbt file: addSbtPlugin("com.typesafe.sbt" % "sbt-rjs" % "1.0.1") To add the plugin to the asset pipeline you can declare it as follows: pipelineStages := Seq(rjs) We also recommend that sbt-web’s sbt-digest and sbt-gzip plugins are included in the pipeline. sbt-digest will provide Play’s asset controller with the ability to fingerprint asset names for far-future caching. sbt-gzip produces a gzip of your assets that the asset controller will favor when requested. Your plugins.sbt file for this configuration will then look like: addSbtPlugin("com.typesafe.sbt" % "sbt-digest" % "1.0.0") addSbtPlugin("com.typesafe.sbt" % "sbt-gzip" % "1.0.0") and your pipeline configuration now becomes: pipelineStages := Seq(rjs, digest, gzip) The order of stages is significant. You first want to optimize the files, produce digests of them and then produce gzip versions of all resultant assets. The options for RequireJs optimization have changed entirely. The plugin’s options are: For more information please consult the plugin’s documentation. §Default ivy local repository and cache Due to Play now using Activator as a launcher, it now uses the default ivy cache and local repository. This means anything previously published to your Play ivy cache that you depend on will need to be published to the local ivy repository in the .ivy2 folder in your home directory. §Results restructure In Play 2.2, a number of result types were deprecated, and to facilitate migration to the new results structure, some new types introduced. Play 2.3 finishes this restructuring. §Scala results The following deprecated types and helpers from Play 2.1 have been removed: play.api.mvc.PlainResult play.api.mvc.ChunkedResult play.api.mvc.AsyncResult play.api.mvc.Async If you have code that is still using these, please see the Play 2.2 Migration Guide to learn how to migrate to the new results structure. As planned back in 2.2, 2.3 has renamed play.api.mvc.SimpleResult to play.api.mvc.Result (replacing the existing Result trait). A type alias has been introduced to facilitate migration, so your Play 2.2 code should be source compatible with Play 2.3, however we will eventually remove this type alias so we have deprecated it, and recommend switching to Result. §Java results The following deprecated types and helpers from Play 2.1 have been removed: play.mvc.Results.async play.mvc.Results.AsyncResult If you have code that is still using these, please see the Play 2.2 Migration Guide to learn how to migrate to the new results structure. As planned back in 2.2, 2.3 has renamed play.mvc.SimpleResult to play.mvc.Result. This should be transparent to most Java code. The most prominent places where this will impact is in the Global.java error callbacks, and in custom actions. §Templates The template engine is now a separate project, Twirl. §Content types The template content types have moved to the twirl package. If the play.mvc.Content type is referenced then it needs to be updated to play.twirl.api.Content. For example, the following code in a Play Java project: import play.mvc.Content; Content html = views.html.index.render("42"); will produce the error: [error] ...: incompatible types [error] found : play.twirl.api.Html [error] required: play.mvc.Content and requires play.twirl.api.Content to be imported instead. §sbt settings The sbt settings for templates are now provided by the sbt-twirl plugin. Adding additional imports to templates was previously: templatesImport += "com.abc.backend._" and is now: TwirlKeys.templateImports += "org.abc.backend._" Specifying custom template formats was previously: templatesTypes += ("html" -> "my.HtmlFormat.instance") and is now: TwirlKeys.templateFormats += ("html" -> "my.HtmlFormat.instance") For sbt builds that use the full scala syntax, TwirlKeys can be imported with: import play.twirl.sbt.Import._ §Html.empty replaced by HtmlFormat.empty If you were using before Html.empty ( play.api.templates.Html.empty), you must now use play.twirl.api.HtmlFormat.empty. §Play WS The WS client is now an optional library. If you are using WS in your project then you will need to add the library dependency. For Java projects you will also need to update to a new package. §Java projects Add library dependency to build.sbt: libraryDependencies += javaWs Update to the new library package in source files: import play.libs.ws.*; §Scala projects Add library dependency to build.sbt: libraryDependencies += ws In addition, usage of the WS client now requires a Play application in scope. Typically this is achieved by adding: import play.api.Play.current The WS API has changed slightly, and WS.client now returns an instance of WSClient rather than the underlying AsyncHttpClient object. You can get to the AsyncHttpClient by calling WS.client.underlying. §Anorm There are various changes included for Anorm in this new release. For improved type safety, type of query parameter must be visible, so that it can be properly converted. Now using Any as parameter value, explicitly or due to erasure, leads to compilation error No implicit view available from Any => anorm.ParameterValue. // Wrong val p: Any = "strAsAny" SQL("SELECT * FROM test WHERE id={id}"). on('id -> p) // Erroneous - No conversion Any => ParameterValue // Right val p = "strAsString" SQL("SELECT * FROM test WHERE id={id}").on('id -> p) // Wrong val ps = Seq("a", "b", 3) // inferred as Seq[Any] SQL("SELECT * FROM test WHERE (a={a} AND b={b}) OR c={c}"). on('a -> ps(0), // ps(0) - No conversion Any => ParameterValue 'b -> ps(1), 'c -> ps(2)) // Right val ps = Seq[anorm.ParameterValue]("a", "b", 3) // Seq[ParameterValue] SQL("SELECT * FROM test WHERE (a={a} AND b={b}) OR c={c}"). on('a -> ps(0), 'b -> ps(1), 'c -> ps(2)) If passing value without safe conversion is required, anorm.Object(anyVal) can be used to set an opaque parameter. Moreover, erasure issues about parameter value is fixed: type is no longer ParameterValue[_] but simply ParameterValue. Types for parameter names are also unified (when using .on(...)). Only String and Symbol are now supported as name. Type Pk[A] has been deprecated. You can still use it as column mapping, but need to explicitly pass either Id[A] or NotAssigned as query parameter (as consequence of type safety improvements): // Column mapping, deprecated but Ok val pk: Pk[Long] = SQL("SELECT id FROM test WHERE name={n}"). on('n -> "mine").as(get[Pk[Long]].single) // Wrong parameter val pkParam: Pk[Long] = Id(1l) val name1 = "Name #1" SQL"INSERT INTO test(id, name) VALUES($pkParam, $name1)".execute() // ... pkParam is passed as Pk in query parameter, // which is now wrong as a parameter type (won't compile) // Right parameter Id val idParam: Id[Long] = Id(2l) // same as pkParam but keep explicit Id type val name2 = "Name #2" SQL"INSERT INTO test(id, name) VALUES($idParam, $name2)".execute() // Right parameter NotAssigned val name2 = "Name #3" SQL"INSERT INTO test(id, name) VALUES($NotAssigned, $name2)".execute() As deprecated Pk[A] is similar to Option[A], which is supported by Anorm in column mapping and as query parameter, it’s preferred to replace Id[A] by Some[A] and NotAssigned by None: // Column mapping, deprecated but Ok val pk: Option[Long] = SQL("SELECT id FROM test WHERE name={n}"). on('n -> "mine").as(get[Option[Long]].single) // Assigned primary key as parameter val idParam: Option[Long] = Some(2l) val name1 = "Id" SQL"INSERT INTO test(id, name) VALUES($idParam, $name1)".execute() // Right parameter NotAssigned val name2 = "NotAssigned" SQL"INSERT INTO test(id, name) VALUES($None, $name2)".execute() §Bootstrap The in-built Bootstrap field constructor has been deprecated, and will be removed in a future version of Play. There are a few reasons for this, one is that we have found that Bootstrap changes too drastically between versions and too frequently, such that any in-built support provided by Play quickly becomes stale and incompatible with the current Bootstrap version. Another reason is that the current Bootstrap requirements for CSS classes can’t be implemented with Play’s field constructor alone, a custom input template is also required. Our view going forward is that if this is a feature that is valuable to the community, a third party module can be created which provides a separate set of Bootstrap form helper templates, specific to given Bootstrap versions, allowing a much better user experience than can currently be provided. §Session timeouts The session timeout configuration item, session.maxAge, used to be an integer, defined to be in seconds. Now it’s a duration, so can be specified with values like 1h or 30m. Unfortunately, the default unit if specified with no time unit is milliseconds, which means a config value of 3600 was previously treated as one hour, but is now treated as 3.6 seconds. You will need to update your configuration to add a time unit. §Java JUnit superclasses The Java WithApplication, WithServer and WithBrowser JUnit test superclasses have been modified to define an @Before annotated method. This means, previously where you had to explicitly start a fake application by defining: @Before public void setUp() { start(); } Now you don’t need to. If you need to provide a custom fake application, you can do so by overriding the provideFakeApplication method: @Override protected FakeApplication provideFakeApplication() { return Helpers.fakeApplication(Helpers.inMemoryDatabase()); } §Session and Flash implicits The Scala Controller provides implicit Session, Flash and Lang parameters, that take an implicit RequestHeader. These exist for convenience, so a template for example can take an implicit argument and they will be automatically provided in the controller. The name of these was changed to avoid conflicts where these parameter names might be shadowed by application local variables with the same name. session became request2Session, flash became flash2Session, lang became lang2Session. Any code that invoked these explicitly consequently will break. It is not recommended that you invoke these implicit methods explicitly, the session, flash and lang parameters are all available on the RequestHeader, and using the RequestHeader properties makes it much clearer where they come from when reading the code. It is recommended that if you have code that uses the old methods, that you modify it to access the corresponding properties on RequestHeader directly. Next: Play 2.2 migration guide.
https://www.playframework.com/documentation/tr/2.4.x/Migration23
CC-MAIN-2019-22
refinedweb
3,296
51.65