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
Every year or so for the past couple of decades I've seen new products appear that claim to let you create software without having to know how to code. And every time the next one comes out, I roll my eyes, because they always fail to deliver as promised. Usually the concept is the same: You use a tool to design your data, and some other tool to draw out the screens. Then you get a program. The program automatically gets the basic database functionality: A data browser, a data entry form, a search form. But the problem is the moment you want to take the app to the next level and add more sophisticated features, you hit a roadblock. I've seen this all too many times, from tools that claim to be for non-programmers, to more sophisticated tools that claim to be RAD (Rapid Application Design). Last week, Microsoft released yet another product into this space. It's called Lightswitch, and it actually runs inside Visual Studio. When I heard about it, I downloaded it, installed it, tried a couple quick tests, and was tempted to write a three-word review: This product sucks. But then I started using it more, trying out more things. And I became a bit more intrigued. Now I have to be honest: My ego really wants to hate this thing. I really want to say that this thing is a joke and will bomb. But to be totally honest, it's actually proving to be pretty nice. (As for whether it'll bomb, that's something separate. I think it will, because tools like this rarely survive. History is not on Microsoft's side here.) Before I get into it, here's the biggest reason I've decided it's actually pretty good: At heart, it's just a RAD tool sitting on top of Visual Studio, and underneath you still have an actual C# project. And at any time you're free to go down into it and write real, live C# code. In other words, you don't have the roadblock you have with other tools. (And just to be clear, among the plethora of other tools, many of them claim to let you drop down and write code, but too many of them force you to use a proprietary language that's little more than a toy, and not something that you can use for real development.) But now the downside: Although it's C#, unfortunately the app you're building runs inside of Silverlight. On one hand, Silverlight lets you run the app either on the desktop or in a browser. But, frankly, I don't care much for Silverlight. (If I want to target the web, right now my two favorite platforms are Node.js and ASP.NET MVC.) Now one more point: Lightswitch isn't free. It's retailing at $299, but I've seen a few deals around where you can get it for less; at the time of this writing, Microsoft is selling it in their online store for $199 at . (But you don't need to purchase Visual Studio separately, although if you do already have Visual Studio installed, Lightswitch will install itself into your existing Visual Studio. And it'll exist as a project type, so the rest of Visual Studio will still function as it always did.) So now let's take a look at this thing and see what it can do. Creating a New Application Creating a new application with Lightswitch works very much like creating any other application in Visual Studio. You create a new project, but choose a Lightswitch application. And you can choose Visual Basic or C#. That's the only option you get initially. But the next step looks nothing like the usual Visual Studio. Instead of getting a project with files in it and a code editor, you get a start screen with two links on it: Create New Table and Attach to External Data Source. (Although you don't find out until later, the Create New Table requires that you have SQL Server Express installed and running, as that's where the tables end up.) If instead you choose to attach to an external data source, a window pops up asking if you want to attach to a database (such as SQL Server), or a Sharepoint system, or a WCF RIA Service. The WCF RIA one is particularly interesting because it's a newer data system intended for Silverlight. I'm not going to explore it here since there's not enough space, but if you want to read about it, you can start here . For this initial application, I'm choosing the Create New Table option so I can show you how that works. Here's what it looks like; you can see that you just fill in the table, providing field names and types: Easy enough. You can use the Properties box on the right to set properties for the fields, as well as the name the table itself. I called this one Employee. Then you can add a screen. To add a screen for this data, you can click the Screen button at the top of the table editor. Or you can right-click in the Solution Explorer, and click Add Screen. Here's the Add Screen dialog: You can choose between a Details Screen, an Editable Grid Screen, List and Details Screen, New Data Screen, and Search Data Screen. You can see where you choose the table the screen works with, and you can name it. I created two screens, one for an Editable Grid Screen, and one for a New Data Screen. After the screens are generated, you get the screen editor, which looks like this: You can configure both the layout and the command bar on the screen by clicking around in this window. It's pretty self-explanatory. If you try it out, you can fuss with it without me showing you here. You'll figure it out. For now, then, I'm just running them to see what the basic app looks like.The Running Program Although the running program is a Silverlight program, it looks like a traditional desktop program: This app required no coding whatsoever. Instead, I filled in wizards and ran it. It's nice looking, and it includes an interesting Export to Excel feature, which basically launches Excel and pastes the grid of data into it. The program is fully-functional, with browser views, and I can easily add other features like data entry forms, again with no coding.Two Solution Views This is one thing I really like: By default, the Solution Explorer looks quite different from a usual Visual Studio project: This is a more intuitive view that a non-programmer might like. But for those of us who want to take the project up a notch and go into the actual code, we can switch back to the usual Solution Explorer by clicking the right-most button in the toolbar. Then it looks like this: Inside this solution you can see what's really going on behind the scenes. In fact, you can see there are actually three distinct projects. One is called Client, and it's a Silverlight app. Another is called Common, and it's a Lightswitch-specific project containing some configuration stuff. And then there's a server app. Now just to be clear, I should probably mention that I called the first project a Silverlight project, and indeed under the hood that's what it is. However, Microsoft has created a special runtime for Lightswitch that runs on top of Silverlight. As such, the Client, while certainly a Silverlight project, is also a Lightswitch project. If you look at the References, you'll see a whole set of libraries with the name Lightswitch in them. But alongside those libraries are the standard .NET libraries like mscorlib—but, these are the Silverlight versions.Custom Code If you want, you can write custom code without digging into the actual solution. There are plenty of places to add in your own custom code. Typically these code spots correspond to events. For example, a screen has several events that you can tie code to, and you access these events by clicking the dropdown in the upper-right corner of the screen. For example, I clicked the Closing event and was taken to the code editor, just like with a regular C# program: namespace LightSwitchApplication { public partial class EditableEmployeesGrid { partial void EditableEmployeesGrid_Closing(ref bool cancel) { // Write your code here. } } } You can also attach code to buttons and other controls, just as you can in regular C#. For me, adding code like this is an important feature, because it means I can get down into "real" programming in C#, and I'm not stuck working with some badly designed, proprietary language.Data Access Now about that earlier option where you could choose between creating a new table or attaching to an existing database. I tried attaching to an existing SQL Server database. On my system I'm using this on, I have both SQL Express, as well as the developer version of SQL Server. I attached to the Microsoft Northwind sample database on my developer version. SQL Express was turned off. But when I attached, I had to choose which tables in Northwind that I wanted to "import". That struck me as odd, because I didn't want to import anything; I just wanted to use that database. So I imported three tables, Customer, Category, and Product. I then created a browser screen for the Employee table; my intention was to run it, change some data from within my test program, and then check the database itself to see if the data changed – or if Lightswitch indeed had "imported" the tables and I was modifying a local copy. Fortunately, I really was connected to SQL Server and not a local copy. I made changes and they were there. Yet, oddly, when I first tried running my Silverlight app, it refused to launch, with Visual Studio giving me an error that it couldn't connect to SQL Express. Why do I need that? I did some hacking, and I found there's a database sitting in the bin\data directory. After some work, I managed to get it open in SQL Management Studio. The tables in it were related to membership. They had names like Membership, Profile, Roles, Users. So the default membership is embedded inside the SQL Express database file in the project. Conclusion That's a quick rundown of it. You can create tables in SQL Express, or you can attach to existing tables in an actual database server. You can create screens very easily. You can attach code, and if you want to you can dive down into the actual solution itself. So is this thing good or bad? And will it survive? I'm torn. On one hand I think it's pretty cool, and I think Microsoft nailed it on how you can go into the actual app and work on real C# code. That's better than somebody handing us an old Access application and asking us to add a ton of features Access was never meant to handle. But on the other hand, as a developer, I would personally never use a tool like this. I just don't need it. I have everything I need with either node.js or ASP.NET MVC3, and I see no reason to quickly design applications like this—especially since it's a Silverlight app, which I'm really not fond of. I'd rather I get a real Ajax-powered web app. But here's another thought: Microsoft is attempting to fill a void here. With Access, they have hit some major problems moving forward. Access is simply not built for the web. It includes some tools that let you supposedly migrate an Access app to the web, but in fact, they're barely usable and you need to invest in Sharepoint to get Access onto the web. Access developers have themselves reached a point of frustration, because their clients want web-based software. And Visual Lightswitch may well fill that void. It's as easy to use as Access. And you can build an app that runs either locally on a desktop or in a web browser. But even better, you're not stuck with some half-baked programming language. Instead, under the hood is the full C# and .NET framework. But like I said, I personally don't need it. What do you think?
https://www.daniweb.com/programming/databases/reviews/377846/review-lightswitch-for-databases-and-rapid-application-design
CC-MAIN-2018-47
refinedweb
2,122
71.85
GH: Provides the standard warnings plus Turns on all warning options that indicate potentially suspicious code. The warnings that are not enabled by -Wall are Turns on warnings that will be enabled by default in the future, but remain off in normal compilations for the time being. This allows library authors eager to make their code future compatible to adapt to new features before they even generate warnings. This currently enables Disables all warnings enabled by -Wcompat. Turns off all warnings, including the standard ones and those that -Wall doesn’t enable. Makes any warning into a fatal error. Useful so that you don’t miss warnings when doing batch compilation. Warnings are treated only as warnings, not as errors. This is the default, but can be useful to negate a -Werror flag. When a warning is emitted, the specific warning flag which controls it is shown.-)*. Enables warnings when the compiler encounters a -W... flag that is not recognised. This warning is on by default. Determines whether the compiler reports typed holes warnings. Has no effect unless typed holes errors are deferred until runtime. See Typed Holes and Deferring type errors to runtime This warning is on by default. Causes a warning to be reported when a type error is deferred until runtime. See Deferring type errors to runtime This warning is on by default.. Determines whether the compiler reports holes in partial type signatures as warnings. Has no effect unless -XPartialTypeSignatures is enabled, which controls whether errors should be generated for holes in types or not. See Partial Type Signatures. This warning is on by default. When a name or package is not found in scope, make suggestions for the name or package you might have meant instead. This option is on by default.. Emits a warning if GHC cannot specialise an overloaded function, usually because the function needs an INLINEABLE pragma. The “all” form reports all such situations whereas the “non-all” form only reports when the situation arises during specialisation of an imported function. The “non-all” form is intended to catch cases where an imported function that is marked as INLINEABLE (presumably to enable specialisation) cannot be specialised as it calls other functions that are themselves not specialised. Note that these warnings will not throw errors if used with -Werror. These options are both off by default. Causes a warning to be emitted when a module, function or type with a WARNING or DEPRECATED pragma is used. See WARNING and DEPRECATED pragmas for more details on the pragmas. This option is on by default. This option is deprecated. Caused a warning to be emitted when a definition was in conflict with the AMP (Applicative-Monad proosal). Warn if noncanonical Applicative or Monad instances declarations are detected. When this warning is enabled, the following conditions are verified: In Monad instances declarations warn if any of the following conditions does not hold: - If return is defined it must be canonical (i.e. return = pure). - If (>>) is defined it must be canonical (i.e. (>>) = (*>)). Moreover, in Applicative instance declarations: - Warn if pure is defined backwards (i.e. pure = return). - Warn if (*>) is defined backwards (i.e. (*>) = (>>)). This option is off by default. Warn if noncanonical Monad or MonadFail instances declarations are detected. When this warning is enabled, the following conditions are verified: In Monad instances declarations warn if any of the following conditions does not hold: - If fail is defined it must be canonical (i.e. fail = Control.Monad.Fail.fail). Moreover, in MonadFail instance declarations: - Warn if fail is defined backwards (i.e. fail = Control.Monad.fail). See also -Wmissing-monadfail-instances. This option is off by default. Warn if noncanonical Semigroup or Monoid instances declarations are detected. When this warning is enabled, the following conditions are verified: In Monoid instances declarations warn if any of the following conditions does not hold: - If mappend is defined it must be canonical (i.e. mappend = (Data.Semigroup.<>)). Moreover, in Semigroup instance declarations: - Warn if (<>) is defined backwards (i.e. (<>) = mappend). This warning is off by default. However, it is part of the -Wcompat option group. Warn when a failable pattern is used in a do-block that does not have a MonadFail instance. See also -Wnoncanonical-monadfail-instances. Being part of the -Wcompat option group, this warning is off by default, but will be switched on in a future GHC release, as part of the MonadFail Proposal (MFP). Warn when definitions are in conflict with the future inclusion of Semigroup into the standard typeclasses. - Instances of Monoid should also be instances of Semigroup - The Semigroup operator (<>) will be in Prelude, which clashes with custom local definitions of such an operator Being part of the -Wcompat option group, this warning is off by default, but will be switched on in a future GHC release. Causes a warning to be emitted when a deprecated command-line flag is used. This option is on by default. Causes a warning to be emitted for foreign declarations that use unsupported calling conventions. In particular, if the stdcall calling convention is used on an architecture other than i386 then it will be treated as ccall.. Causes a warning to be emitted when a datatype T is exported with all constructors, i.e. T(..), but is it just a type synonym. Also causes a warning to be emitted when a module is re-exported, but that module exports nothing. Causes a warning to be emitted in the following cases: Causes a warning to be emitted if a literal will overflow, e.g. 300 :: Word8. Causes a warning to be emitted if an enumeration is empty, e.g. [5 .. 3]. Have the compiler warn about duplicate constraints in a type signature. For example f :: (Eq a, Show a, Eq a) => a -> a The warning will indicate the duplicated Eq a constraint. This option is now deprecated in favour of -Wredundant-constraints. Have the compiler warn about redundant constraints in a type signature. In particular: A redundant constraint within the type signature itself: f :: (Eq a, Ord a) => a -> a The warning will indicate the redundant Eq a constraint: it is subsumed by the Ord a constraint. A constraint in the type signature is not used in the code it covers: f :: Eq a => a -> a -> Bool f x y = True The warning will indicate the redundant Eq a constraint: : it is not used by the definition of f.) Similar warnings are given for a redundant constraint in an instance declaration. This option is on by default. As usual. Causes the compiler to emit a warning when a Prelude numeric conversion converts a type T to the same type T; such calls are probably no-ops and can be omitted. The functions checked for are: toInteger, toRational, fromIntegral, and realToFrac.. The option -Wincomplete-patterns warns about places where a pattern-match might fail at runtime. The function g below will fail when applied to non-empty lists, so the compiler will emit a warning about this when -Wincomplete-patterns. The flag -Wincomplete-uni-patterns is similar, except that it applies only to lambda-expressions and pattern bindings, constructs that only allow a single pattern: h = \[] -> 2 Just k = f y. The function f below will fail when applied to Bar, so the compiler will emit a warning about this when -Wincomplete-record-updates is enabled. data Foo = Foo { x :: Int } | Bar f :: Foo -> Foo f foo = foo { x = 6 } This option isn’t enabled by default because it can be very noisy, and it often doesn’t indicate a bug in the program.. This flag warns if you use an unqualified import declaration that does not explicitly list the entities brought into scope. For example module M where import X( f ) import Y import qualified Z p x = f x x The -Wmissing-import-lists flag will warn about the import of Y but not X If module Y is later changed to export (say) f, then the reference to f in M will become ambiguous. No warning is produced for the import of Z because extending Z‘s exports would be unlikely to produce ambiguity in M.Fn or _simpleFn. The MINIMAL pragma can be used to change which combination of methods will be required for instances of a particular class. See MINIMAL pragma. If you would like GHC to check that every top-level function/value has a type signature, use the -Wmissing-signatures option. As part of the warning GHC also reports the inferred type. The option is off by default. This option is now deprecated in favour of -Wmissing-exported-signatures. If you would like GHC to check that every exported top-level function/value has a type signature, but not check unexported values, use the -Wmissing-exported-signatures option. This option takes precedence over -Wmissing-signatures. As part of the warning GHC also reports the inferred type. The option is off by default. This option is now deprecated in favour of -Wmissing-local-signatures. If you use the -Wmissing-local-signatures flag GHC will warn you about any polymorphic local bindings. As part of the warning GHC also reports the inferred type. The option is off by default. If you would like GHC to check that every pattern synonym has a type signature, use the -Wmissing-pattern-synonym-signatures option. If this option is used in conjunction with -Wmissing-exported-signatures then only exported pattern synonyms must have a type signature. GHC also reports the inferred type. capture of what would be a recursive call in f = ... let f = id in ... f .... The warning is suppressed for names beginning with an underscore. For example f x = do { _ignore <- this; _ignore <- that; return (the other) } warns about user-written orphan rules or instances.. Have the compiler warn if there are tabs in your source file. to be given the type Int, whereas Haskell 98 and later defaults it to Integer. This may lead to differences in performance and behaviour, hence the usefulness of being non-silent about this. This warning is off by default.. Warn when using -fllvm with an unsupported version of LLVM. Warn if a promoted data constructor is used without a tick preceding its name. For example: data Nat = Succ Nat | Zero data Vec n s where Nil :: Vec Zero a Cons :: a -> Vec n a -> Vec (Succ n) a Will raise two warnings because Zero and Succ are not written as 'Zero and 'Succ. This warning is is enabled by default in -Wall mode. Report any function definitions (and local bindings) which are unused. An alias for Report any local definitions which are unused. For example: module A (f) where f = let (p,q) = rhs1 in t p -- Warning: q is unused g = h x -- No warning: g is unused, but is a top-level binding Warn if a pattern binding binds no variables at all, unless it is a lone, possibly-banged, wild-card pattern. For example: Just _ = rhs3 -- Warning: unused pattern binding (_, _) = rhs4 -- Warning: unused pattern binding _ = rhs3 -- No warning: lone wild-card pattern !_ = rhs4 -- No warning: banged wild-card pattern; behaves like seq The motivation for allowing lone wild-card patterns is they are not very different from _v = rhs3, which elicits no warning; and they can be useful to add a type constraint, e.g. _ = x::Int. A lone banged wild-card pattern is useful as an alternative (to seq) way to force evaluation. Report any modules that are explicitly imported but never used. However, the form import M() is never reported as an unused import, because it is a useful idiom for importing instance declarations, which are anonymous in Haskell. Report all unused variables which arise from term-level pattern matches, including patterns consisting of a single variable. For instance f x y = [] would report x and y as unused. The warning is suppressed if the variable name begins with an underscore, thus: f _x = True Note that -Wunused-matches does not warn about variables which arise from type-level patterns, as found in type family and data family instances. This must be enabled separately through the -Wunused-type-patterns flag. Report expressions occurring in do and mdo blocks that appear to silently throw information away. For instance do { mapM popInt xs ; return 10 } would report the first statement in the do block } Report all unused type variables which arise from patterns in type family and data family instances. For instance: type instance F x y = [] would report x and y as unused. The warning is suppressed if the type variable name begins with an underscore, like so: type instance F _x _y = [] Unlike -Wunused-matches, -Wunused-type-variables is not implied by -Wall. The rationale for this decision is that unlike term-level pattern names, type names are often chosen expressly for documentation purposes, so using underscores in type names can make the documentation harder to read. Report all unused type variables which arise from explicit, user-written forall statements. For instance: g :: forall a b c. (b -> b) would report a and c as unused. Report expressions occurring in do and mdo blocks that appear to lack a binding. For instance do { return (popInt 10) ; return 10 } would report the first statement in the do block } Warn if a rewrite RULE might fail to fire because the function might be inlined before the rule has a chance to fire. See How rules interact with INLINE/NOINLINE pragmas. If you’re feeling really paranoid, the -dcore-lint option is a good choice. It turns on heavyweight intra-pass sanity-checking within GHC. (It checks GHC’s sanity, not yours.)
https://downloads.haskell.org/~ghc/8.0.2/docs/html/users_guide/using-warnings.html
CC-MAIN-2018-34
refinedweb
2,281
63.8
This article explains how to use Web Service Enhancements version 2.0 and the ASP.NET built in Handler to create a custom one way asynchronous Web Service. The major purpose of this exercise is to demonstrate a quick and dirty way to implement a �Remote Procedure Call� modeled one way and a normal two way web service. It is by no means a recommended way to implement a production web service being utilized in a Business to Business (B2B) e-commerce application and this article will explain why. With Service Oriented Architecture being the future paradigm in Software Design patterns, it is necessary to discuss what ASP.NET 1.1 and WSE v2.0 gives today in order to prepare for tomorrow�s Indigo and other wave of SOA systems. Let�s get started by explaining what WSE is, then we�ll venture into the world of ASP.NET and its technologies, specifically HTTP Handlers. Afterwards, we�ll dive into a decent depth of WSE and how to implement the web service. WSE stands for Web Service Enhancements. To keep this intro quick and simple, it�s a .NET Shared Component that can be downloaded and installed into current versions of the .NET Framework. Currently, it�s in version 2.0 of its official release, with its next version probably to be released fairly soon. Behind the scenes, the component is implemented through many different namespaces and classes within that allow a developer to add Industry security Standards; to create industry SOAP message formats that allow easier interop between different systems such as Java Web Services, IBM web services and BEA Web Services; and to apply other community standards normally referred to as a set of specifications called WS-* (WS-Security, WS-I, WS-Addressing, WS-Messaging, etc�). WSE is a Soap Extension that manipulates SOAP messages on both the client side and the server side if implemented in both. ASP.NET is Microsoft�s successor to ASP, it�s a dynamic way to generate web pages back to a Web Browser such as Internet Explorer, FireFox and Netscape, using Microsoft. NET. With the advent of the concept of dynamic web pages came the birth of Web Services. A web service is a component that you can access using the HTTP model to send data and commands, normally called messages, to it. If you were to take the abstract of Web Services, it would yield you into the world of Service Oriented Architecture (SOA). ASP.NET Web Services are one way to implement Services in SOA. To keep to the point here, ASP.NET Web Services normally use XML as its format to send and receive messages. Specifically speaking, it uses a SOAP XML format. ASP.NET makes it easy for developers to use this concept to create web services. It has a technology called "ASMX" that allows these SOAP messages to be automatically parsed and generated to access the remote component. ASP.NET implements this and other technologies like this through the use of HTTP Handlers and Soap Extensions (see machine.config snippet). An ASP.NET HTTP Handler would be equivalent to what an IIS Filter could do (for those C++ developers out there.) The HTTP Handler has the job of handling HTTP Requests and HTTP Responses that come in and out of ASP.NET. It can modify the Response/Request, by adding to it, removing from it, or totally creating a new object of data. An HTTP Handler is usually registered to ASP.NET by the HTTP verb (GET, POST, PUT, etc.), the path (*-all, *.asmx- files ending in .asmx, etc.), and the component that contains the code to execute to modify or parse the Response/Requests (.NET Assembly). This setting is set through an Application�s configuration file. For more robust custom implementations, an ASP.NET HTTP Handler may also need to be registered to IIS, see Watermark Website Images At Runtime by KingLion. ASP.NET already comes with some HTTP Handlers and HTTP Handler Factories. A HttpHandlerFactory is a class whose job is to create instances of Handlers based off of some logical coded criteria. To create a HttpHandlerFactory, create a class that implements the IHttpHandlerFactory. This class has two methods to implement. IHttpHandler GetHandler(HttpContext currentcontext, string reqType, string url, string pathTranslated); void ReleaseHandler(System.Web.IHttpHandler handlerToRelease); These factories are registered the same way a HttpHandler is registered, thus I won�t spend too much time on those. We have HttpHandlers that deal with security, such as the FormsAuthenticationHandler. We also have some handlers that deal with restricting access to certain types of files such as the HttpForbiddenHandler. There is also, the all important PageHandler that handles ASP.NET Web Form Pages and the WebServiceHandler that handles .asmx pages (ASP.NET web services). There is also a SimpleHandlerFactory that is mapped/registered to .ashx file extensions. We also have the ability to create our own custom HTTP Handler mapped to our own extensions. (see machine.config snippet) The SimpleHandlerFactory allows a developer to create a HTTP Handler just like creating an ASP.NET web page, check it out: In VS.NET, create a class library project, add a reference to System.Web.Dll, create a class such as this: Class1.cs using System.Web; using System.Web.SessionState; namespace TimeStampRequests { /// <summary> /// Summary description for Class1. /// </summary> public class TimeStampReq : IHttpHandler , IRequiresSessionState { public TimeStampReq(){} public void ProcessRequest(HttpContext ctxt) { //ctxt.Application - HttpApplicationState //ctxt.Server //ctxt.Session - SessionState // (Requires IRequiresSessionState implementation) //ctxt.Cache - Cache Object //ctxt.Request - HttpRequest //ctxt.Response - HttpResponse //Perform any operation you want... } public bool IsReusable { get { return true; //No State between requests } } } } This next part is optional, you can create a Page.ashx file if you�d like. However, it's not necessary: Page1.ashx: <%@ WebHandler Language="�c#�" class=�TimeStampRequests.TimeStampReq� %> You could also use code-behind, or include the source in the same file just like in ASP.NET Web Form Pages. The next part is to register the Simple Handler in a Web Config file like this: <system.web> <httpHandlers> <add verb=�*� path=�*.ashx� type=�TimeStampRequests.TimeStampReq, TimeStampRequest�/> </httpHandlers> </system.web> The code explanation goes as follows, create a class and implement the IHttpHandler interface. This interface has one function and one property you must implement. The method is called ProcessMessage. Here is the signature: void ProcessMessage(HttpContext context) This method is called when the ASP.NET worker process hands off the Request or Response to be processed. It passes into this method the current Web environment data in the form of an object called HttpContext. This HttpContext object can be used to read Server variables, Session data, Response specific data, Request data and the Application object pool of data as well. The next implementation is the property called IsReusable, its signature looks like this: bool IsReusable { get; } This property determines whether or not you want to maintain state between requests. Once you implement this method and property, a HttpHandlerFactory can create an instance of the Handler and let ASP.NET worker process call into it to process the Request or Response. There was a Microsoft Web cast (,) as well as a CodeProject article "Watermark Website Images At Runtime" by KingLeon where HTTP Handlers were used to create watermarks on images. This is the basic blue print for utilizing your own custom built Handler using the SimpleHandlerFactory. There are other more complex ways to create a Custom handler, however, the steps don�t differ that much at all. The built in SimpleHandlerFactory will create an instance of your Handler when ever a request for a .ashx page comes to the ASP.NET virtual directory application. Your code will then execute its ProcessRequest method and run. Here is a snippet of the Machine.config file for .NET 1.1, again showing some available HTTP Handlers: <httpHandlers> <add verb="*" path="*.vjsproj" type="System.Web.HttpForbiddenHandler"/> <add verb="*" path="*.java" type="System.Web.HttpForbiddenHandler"/> <add verb="*" path="*.jsl" type="System.Web.HttpForbiddenHandler"/> <!--<add verb="*" path="*.vsdisco" type="System.Web.Services.Discovery.DiscoveryRequestHandler, System.Web.Services, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" validate="false"/>--> <add verb="*" path="trace.axd" type="System.Web.Handlers.TraceHandler"/> <add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory"/> <add verb="*" path="*.ashx" type="System.Web.UI. <add verb="*" path="*.soap" type="System.Runtime.Remoting.Channels.Http.HttpRemotingHandlerFactory, System.Runtime.Remoting, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" validate="false"/> WSE v2.0 has some classes that allow standardized SOAP messages to be sent based off of WS-Addressing, WS-Messaging and the rest of WS-* specifications (see,). In particular, we�re going to focus on the communication implementations of WSE, SoapSenders / SoapReceivers and SoapClients / SoapServices. The most interesting part about these classes is that a SoapService class inherits from a SoapReceiver class. A SoapReceiver class implements the IHttpHandler interface. This means that if you create a class inheriting from SoapReceiver or SoapService class, it can be used with the SimpleHandlerFactory to allow you to process the Request or Response. If the Request/Response has a SOAP message inside its body section, you have just effectively implemented a Web Service, which is exactly how WebServiceHandler works. Let�s see if we can achieve this goal, here�s the code below: using Microsoft.Web.Services2; using Microsoft.Web.Services2.Messaging; using Microsoft.Web.Services2.Addressing; namespace WSE_AsynWebSvc { public class AsyncWebSvc : SoapReceiver { public AsyncWebSvc(){} private EndpointReference epSendTo; protected override void Receive(SoapEnvelope envelope) { epSendTo = new EndpointReference(new Uri(envelope.Context.Addressing.ReplyTo.Address.Value.ToString())); SoapEnvelope retEnv = new SoapEnvelope(); retEnv.CreateBody(); retEnv.SetBodyObject("success"); retEnv.Context.Addressing.To = new To(epSendTo.Address); retEnv.Context.Addressing.Action = new Action(epSendTo.Address.Value.ToString() ); retEnv.Context.Addressing.ReplyTo = new ReplyTo(epSendTo); SoapSender ssend = new SoapSender(epSendTo); ssend.Send(retEnv); } //Here's our IHttHandler ProcessMessage implementation //SoapReceiver already implements this function for us anyway //We can override the SoapReceivers implementation public override void ProcessMessage(SoapEnvelope message) { base.ProcessMessage (message); } } } Now, let�s register it. Here�s the configuration file: <> <system.web> <httpHandlers> <add type="WSE_AsncWebSvc.AsyncWebSvc" path="*.ashx" verb="*" /> </httpHandlers> </system.web> <microsoft.web.services2> <diagnostics> <trace enabled="true" input="InputTrace.webinfo" output="OutputTrace.webinfo" /> <detailedErrors enabled="true" /> </diagnostics> </microsoft.web.services2> </configuration> Once we add the <system.web> section to our web.config file, our Web service can be accessed through the .ashx file extension. Let�s talk about the code. We first create a class called AsyncWebSvc. We derive this class from the SoapReceiver class. The SoapReceiver class already handles the implementation of ProcessMessage, so we don�t have to worry about that unless we want to. In other words, we could override the base�s implementation and add our own code here as shown in the code. The SoapReceiver class is found within the Microsoft.Web.Services2.Messaging namespace that performs asynchronous SOAP parsing. This class parses the HttpRequest body section and looks for a SOAP message. When one is found, it makes a call into the Receive method passing in this SOAP message XML format to allow developers to manipulate and parse to perform some action. This is all you need to do. Currently, if we stop here, and we don�t need to send a response back, this is what we�d call a One-way Asynchronous web service. If we want to send a response back, WSE uses the SoapSender and SoapClient classes for sending SOAP messages. To send a message using WSE, we first must create the message to send. Using WSE, we create a SoapEnvelope class that represents the SOAP message to send. This SoapEnvelope class gives developers programmatic control over the raw SOAP XML format for exactly what data they want to wrap inside the body of the message. WSE has the task of formatting it so that the message adheres to the SOAP XML WS-* community standard. The code shows one way on how to create a SoapEnvelope and send it using a SoapSender class instance. The only other piece to explain is: where are we sending the message to anyway? For a normal Asynchronous two way web service, the SoapSender class instance is created by passing in an Uri address (basically, a URL address not specifically based on HTTP protocols, it�s more generic in nature). In WSE 2.0, Uri addresses are wrapped up inside of a class called an EndpointReference. This is done this way because of the WS-Addressing and WS-Messaging standards. A client application, be it another Web Service or an ASP.NET application or even a Windows Form, can create a listening port to listen for SOAP responses. Here�s the code for a Windows Form client app, it creates a EndpointReference for itself and then makes a call into this web service using WSE 2.0 and gets a response back asynchronously: using System; using System.Windows.Forms; using Microsoft.Web.Services2; using Microsoft.Web.Services2.Addressing; using Microsoft.Web.Services2.Messaging; namespace UsingAsyncWebSvc { //create a class that inherits from the base Form class public class Form1 : System.Windows.Forms.Form { //create some controls that display and execute //the method on the web service internal System.Windows.Forms.Label label1; private System.Windows.Forms.Button button1; private System.ComponentModel.Container components = null; public Form1() { //Initialize the Controls and position them; //set up event handlers etc� InitializeComponent(); } //basic clean up code without using a destructor protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } //Method to initialize controls, positioning on form, colors and etc. private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.SuspendLayout(); this.label1.Location = new System.Drawing.Point(16, 8); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(264, 96); this.label1.TabIndex = 0; this.label1.Text = "label1"; this.button1.Location = new System.Drawing.Point(200, 120); this.button1.Name = "button1"; this.button1.TabIndex = 1; this.button1.Text = "button1"; this.button1.Click += new System.EventHandler(this.button1_Click); this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(292, 150); this.Controls.Add(this.button1); this.Controls.Add(this.label1); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); } //Entry point for the Exe application [STAThread] static void Main() { Application.Run(new Form1()); } //handles the button click event private void button1_Click(object sender, System.EventArgs e) { //Create a URI address and point it to the current client system name //use the tcp protocol; open port 3119; //and a fake path of MyServiceReceive //the path equates to the Action in a Soap Message that has multiple //Operations it can perform Uri uriMe = new Uri("soap.tcp://" + System.Net.Dns.GetHostName() + ":3119/MyServiceReceive"); EndpointReference epMe = new EndpointReference(uriMe); //To receive SoapMessage in WSE, we use a class that derives from //SoapReceiver and overrides the Receive Method. //Thus we create a ReceiveData Class instance and use this class ReceiveData receive = new ReceiveData(); receive.frm = this; //We add this class along with the Uri pointing //to where we plan to listen //to the AppDomain�s SoapReceivers collection of SoapReceivers SoapReceivers.Add(epMe, receive); //Now that we�re listening for responses let�s setup the //SoapMessage and the SoapSender to send the message //to the Web service we created SoapSender sSend = new SoapSender(); SoapEnvelope env = new SoapEnvelope (); //To pass data we must initialize the body of the SoapMessage env.CreateBody(); //WS-Addressing specifies that we can re-route our SoapMessages //We can also apply a reply to address //so that the Web Service can reply back //to the uri we give here. env.Context.Addressing.ReplyTo = new ReplyTo(uriMe); //We now tell our SoapMessage where it will be sent to Uri uriTo =new Uri("http://"+ System.Net.Dns.GetHostName() + "/MyAsyncWebSvc/MyService.ashx"); EndpointReference epTo = new EndpointReference(uriTo); //We load some data into the body of the SoapMessage env.SetBodyObject("<data>dosomething</data>"); //We set up Uri Address env.Context.Addressing.To = new To(epTo.Address ); //We tell the Web Service which method of function we want to call env.Context.Addressing.Action = new Action("MyRequest"); sSend.Destination = uriTo; //We send the message asynchronously sSend.Send(env); this.label1.Text = "Message Sent"; } } //This is our Clients Receiving communication to WSE v2.0 //To receive a SoapMessage using WSE manually, we create // a class inheriting the SoapReceiver class public class ReceiveData : SoapReceiver { public string msg = String.Empty; public Form1 frm = null; //We Override the Receive function and parse the Soapmessage through its //SoapEnvelope class protected override void Receive(SoapEnvelope envelope) { msg = envelope.Body.OuterXml; frm.label1.Text = msg; } } //We could have also done the same thing using a class //inheriting from SoapClient such as this public class MyHttpClient : SoapClient { public string msg = String.Empty; public Form1 frm = null; //For SoapClient Classes we must initialize the base class // with an intializer passing in the EndpointReference that //points to this applications listening port public MyHttpClient(EndpointReference dest) : base(dest) { } //Utilizes the SoapMethodAttribute //to set the SoapAction of a SoapMessage [SoapMethod("MyRequest")] public SoapEnvelope MyRequest(SoapEnvelope envelope) { SoapEnvelope response = base.SendRequestResponse("MyRequest",envelope); msg = response.Body.OuterXml; frm.label1.Text = msg; return response; } } } See comments for explanation of client side code. This practice is not recommended for public major web sites, only really for internal use or quick solutions to get something done. So why is this solution not a production recommended practice? Why is it really only to be used for internal communication patterns? When Web Services hit the industry, one of its major success patterns was its design for interoperability. This means the ability to send a SOAP message from a ASP.NET Microsoft Web Service to a BEA system's Web Logic web service which in turn could go through a IBM�s Web Sphere system, only to be accessed by a Java Web Service Client application and responded back to a ASP.NET web service. In its concept, it worked well. However, in its practicality, it didn�t work until you tweaked the SOAP format for each system you were sending it through. Now with WSE, this is not a problem. As long as the other systems also adhere to the community standard, interoperability is seamless. The piece that allows this interoperability is contracts, sometimes referred to as Service Level Agreements (SLA). These are basically contracts defined by business processes that define what�s going to be inside of each SOAP message going through disparate systems. These contracts are implemented through XML Schemas dealing with web services, also referred to as Web Service Description Language (WSDL) files. The WSDL defines the SOAP format and the SOAP message body format. It basically tells you what can and can not be inside of a SOAP message. Well, nowhere in these exercises did I mention anything about WSDL files until now. Thus, if you want to use these examples as a B2B process, you would have to define WSDL files to fit the interoperability standard. Now, this is not a problem, because it's just an XML schema file. However, there are not a lot of "Don Box's" out in the computer industry who know every facet of a WSDL file. It is not recommended you design one from scratch; there are too many things that can go wrong. This is the main reason for not using this pattern with a B2B Web Service e-commerce application. Another downer is that using this method, the ASP.NET engine can not generate a WSDL file for your application like it can for the "ASMX" technology. Thus, you can�t even create a client application using the "Add Web Reference" wizard in VS.NET. One last note, the Web Reference wizard and the WSDL.exe utility won�t work here as mentioned earlier, nor will the SOAP Encapsulation of the WSDL generated proxy classes shield you from the raw details of a SOAP message when using this method. So if you are afraid of getting to low level, this may not be a good design pattern for you after all. Happy coding! General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/aspnet/Wse_SimpleHandlerFactory.aspx
crawl-002
refinedweb
3,352
50.33
June 2007 Reports (see ReportingSchedule) FROZEN This report is now frozen for submission to the board. Not additional editing will be reflected in the report! Thanks to everyone who contributed These reports are due to the Incubator PMC by 13 June 2007 ODE iPMC Reviewers: jukka, robertburrelldonkin, mvdb Apache ODE is an implementation of the BPEL4WS and WS-BPEL specifications for web services orchestration. ODE entered incubation in March 2006. Beside regular development, the principal improvement in ODE for these 3 past months is our first incubator release. We've been able to come up with a valid release after several release candidates reviewed by the ODE committers and got voted by the IPMC. We've also received a very nice contribution from Kelly Thompson for our website with good looking graphics. A steady stream of patches is also coming in (see [1], [2] and [3] for example) and we have a few leads to bring in more committers (Tammo Van Lessen and Jim Alateras) after a couple more patch contributions. We've raised some concerns about the absence of a real PPMC for ODE to the IPMC, result of the lack of activity of some of our mentors. We'd been handling all decisions as a community with all active committers before but our PPMC didn't reflect it. As a result, Niclas Hedhman has volunteered to become a mentor for ODE, Dims and Paul being both active mentors and the PPMC is elected now. We're ready to move on. As a community, once the PPMC issue settles down, we believe we're ready for graduation. [1] [2] [3] iPMC questions / comments: OpenEJB iPMC Reviewers: jukka, robertburrelldonkin, mvdb. iPMC questions / comments: wrowe asks; what are the obstacles/next steps towards graduation? I didn't see any hint from this report. log4net iPMC Reviewers: log4net is an implementation of the Apache log4j for the .NET Framework. Incubating since: 2004-01-15 iPMC questions / comments: jukka: Report missing robertburrelldonkin: Report missing - should ask logging PMC mvdb: log4net had a graduation vote, but no result (at least afai could find) and no status file update. Wicket iPMC Reviewers: jukka, robertburrelldonkin, mvdb Web development framework focusing on pure OO coding, making the creation of new components very easy. Wicket entered the incubator in October 2006. Top two items to resolve Graduate Release Apache Wicket 1.3.0 final Community aspects: Community is very active and participating on wicket-dev@ Community building effort on wicket-user Voted Martijn Dashorst to become Chair after graduation Voted Jean-Baptiste Quenot to become PPMC member Community had a positive graduation vote Had a blast at ApacheCon, integrated, mingled and socialized with the Apache community Code aspects: Released Wicket 1.3.0-beta1-incubating Started process for finalizing 1.3.0: feature freeze, plans for release candidates Development on Wicket 2.0 has been discontinued after a community vote. The benefits of this version did not outweigh the burden of maintaining 2 code bases, and the API breakage would create a rift in the community. Adopted wicket-velocity integration sub project into Wicket Licensing: Licensing issues have been resolved Acquired ICLA for component/code contributions for James McLaughlin. Wicket Velocity has been checked out and found to be issue free (license wise) Infrastructure: Caught a couple of spammers on the confluence Wiki gmail keeps being a pest for moderation of Wicket's lists iPMC questions / comments: robertburrelldonkin - hopefully this will be Wicket's last Incubator report River iPMC Reviewers: robertburrelldonkin, mvdb River is aimed at the development and advancement of the Jini technology core infrastructure. River entered incubation on Dec 26, 2006. The River community is starting some real work. The initial code submission for the Jini Technology Starter Kit (JTSK) and the ServiceUI API have been filed at the ASF secretary, voted in and landed in SVN, the committers account are in place and the PPMC is set up. No more excuses, now it's time for coding & community! The discussion is now moving to technical issues and code evolution, which is a very good sign. There has been a discussion about package naming, as the code in SVN is under a non org.apache.* namespace: given the sheer amount of issues with backward compatibility and supporting existing users, there has been a general consensus on getting our feet wet with the current code base, integrate a few patches that have been held off while the code was to be migrated to the ASF infrastructure, and devise a roadmap ( possibly with assistance from general/pmc@IAO) for migration to the ASF namespace: this is high priority and the community realizes how it might be important to have a decision as soon as possible, even more if River is to publish incubating releases. iPMC questions / comments: Tika iPMC Reviewers: robertburrelldonkin, mvdb Tika is a toolkit for detecting and extracting metadata and structured text content from various documents using existing parser libraries. Tika entered incubation on March 22nd, 2007. Community The Tika mailing lists have been relatively quiet lately, probably because with little code we don't yet have many concrete issues to talk about. Development We saw the first piece of Tika code when Chris A. Mattmann ported the Nutch metadata framework to Tika. Rida Benjelloun has created a version of the Lius codebase to be included in Tika, and the code is currently in the issue tracker. Issues before graduation. iPMC questions / comments: robertburrelldonkin - tika is at a very early stage of development and incubator RCF iPMC Reviewers: jukka, robertburrelldonkin, mvdb iPMC questions / comments: robertburrelldonkin - no code drop as yet mvdb - code drop is being worked on, but takes time. Yoko iPMC Reviewers: jukka, robertburrelldonkin, mvdb The Yoko project is a robust and high performance CORBA server which is usable from inside any JVM. Incubating since: 2006-01-31 Since our last report, the majority of the development work in Yoko has focused on: Adding new type support to the binding runtime. Improving performance of the runtime binding in terms of marshaling and unmarshaling data. Adding new type support to the IDLToWSDL and WSDLToIDL tools. Fixing minor issues in the ORB core code. Started development of an IDL preprocessor for the tools module. Prepared and completed a Milestone 2 release Yoko has also become a key component of the soon to ship Geronimo 2.0 release, which has just passed certification tests. Future plans: We are currently working to stabilize and finalize type support in the binding runtime and tools in preparation for a release which would like to put out shortly. We are also planning to improving the documentation for Yoko, with the goal of provide more in depth information to users of the Yoko project and to assist any future committers in understanding the existing code and functionality. iPMC questions / comments: jukka: issues/steps before graduation? Heraldry iPMC Reviewers: robertburrelldonkin, mvdb The. TripleSoup iPMC Reviewers: robertburrelldonkin, mvdb.
http://wiki.apache.org/incubator/June2007
crawl-002
refinedweb
1,153
51.28
Sorting Strings By dananourie on Jan 23, 2008 compare() method of String for sorting, the ñ character will come after the z character and will not be the natural Spanish ordering, between the n character and o character. That's where the Collator class of the java.text package comes into play. Imagine a list of words - first - mañana - man - many - maxi Using the default sorting mechanism of String, its compare() method, this will result in a sorted list of: - first - man - many - maxi - mañana.) That's where the Collator class comes in handy. The Collator class takes into account language-sensitive sorting issues and doesn't just try to sort words based upon their ASCII/Unicode character values. Using Collator requires understanding one additional property before you can fully utilize its features, and that is something called strength. The strength setting of the Collator Collator javadoc for more information on these differences and decomposition mode rules. To work with Collator, you need to start by getting one. You can either call getInstance() to get one for the default locale, or pass the specific Locale to the getInstance() method to get a locale for the one provided. For instance, to get one for the Spanish language, you would create a Spanish Locale with new Locale("es") and then pass that into getInstance(): Collator esCollator = Collator.getInstance(new Locale("es")); Assuming the default Collator strength for the locale is sufficient, which happens to be SECONDARY for Spanish, you would then pass the Collator like any Comparator into the sort() routine of Collections to get your sorted List: Collections.sort(list, esCollator); Working with the earlier list, that now gives you a proper sorting with the Spanish alphabet: - first - man - many - mañana - maxi Had you instead used the US Locale for the Collator, mañana would appear between man and many since the ñ is not its own letter. Here's a quick example that shows off the differences.); } } One last little bit of information about collation. The Collator returned by the getInstance() call is typically an instance of RuleBasedCollator for the supported languages. You can use RuleBasedCollator: String rule = "< c, C < a, A < f, F < e, E"; RuleBasedCollator collator = new RuleBasedCollator(rule); This defines the explicit order as cafe, with the different letter cases shown. Now, for a list of words of ace, cafe, ef, and face, the resultant sort order is cafe, ace, face, and ef with the new rules: import java.text.\*; import java.util.\*; public class Rule { public static void main(String args[]) throws ParseException { String words[] = {"ace", "cafe", "ef", "face"}; String rule ="< c, C < a, A < f, F < e, E"; RuleBasedCollator collator = new RuleBasedCollator(rule); List list = Arrays.asList(words); Collections.sort(list, collator); System.out.println(list); } } After compiling and running, you see the words sorted with the new rules: > javac Rule.java > java Rule [cafe, ace, face, ef] After reading the rule syntax some more in the javadocs, try to expand the alphabet and work with the different diacritical marks, too. Now, when developing programs for the global world, your programs can be better prepared to suit the local user. Be sure to keep strings in resource bundles, too, as shown in an earlier tip: \*\*\*\*\*\*\*\*\* Connect and Participate With GlassFish Try GlassFish for a chance to win an iPhone. This sweepstakes ends on March 23, 2008. Submit your entry today. Foote on Blu-ray Disc Java In this video interview, Sun's Blu-ray Disc Java (BDJ) architect Bill Foote talks about this powerful technology and shows some examples of BDJ code and applications. Download the code Thanks by article i don't know this Posted by jlinkamp on January 23, 2008 at 04:46 PM PST # I'd like to see more tips likes this in the future. Useful classes that I was not aware of ;-) Posted by Michael Rogers on January 23, 2008 at 09:32 PM PST # Useful information for me as a Turkish software developer. Java is always helpful about this kind of differences. Thanks. Posted by Özmen Adıbelli on January 24, 2008 at 07:29 PM PST # Posted by double density design on February 01, 2008 at 06:12 PM PST # hi nice hint Posted by Girish on February 07, 2008 at 07:53 PM PST # i want to know about the strings expashally reverse strings plz give the notes of reverse strings Posted by manohar on February 29, 2008 at 06:43 PM PST #
https://blogs.oracle.com/CoreJavaTechTips/entry/sorting_strings
CC-MAIN-2016-07
refinedweb
744
56.79
Question: There is a list of numbers. The list is to be divided into 2 equal sized lists, with a minimal difference in sum. The sums have to be printed. #Example: >>>que = [2,3,10,5,8,9,7,3,5,2] >>>make_teams(que) 27 27 Is there an error in the following code algorithm for some case? How do I optimize and/or pythonize this? def make_teams(que): que.sort() if len(que)%2: que.insert(0,0) t1,t2 = [],[] while que: val = (que.pop(), que.pop()) if sum(t1)>sum(t2): t2.append(val[0]) t1.append(val[1]) else: t1.append(val[0]) t2.append(val[1]) print min(sum(t1),sum(t2)), max(sum(t1),sum(t2)), "\n" Question is from Solution:1 New Solution This is a breadth-first search with heuristics culling. The tree is limited to a depth of players/2. The player sum limit is totalscores/2. With a player pool of 100, it took approximately 10 seconds to solve. def team(t): iterations = range(2, len(t)/2+1) totalscore = sum(t) halftotalscore = totalscore/2.0 oldmoves = {} for p in t: people_left = t[:] people_left.remove(p) oldmoves[p] = people_left if iterations == []: solution = min(map(lambda i: (abs(float(i)-halftotalscore), i), oldmoves.keys())) return (solution[1], sum(oldmoves[solution[1]]), oldmoves[solution[1]]) for n in iterations: newmoves = {} for total, roster in oldmoves.iteritems(): for p in roster: people_left = roster[:] people_left.remove(p) newtotal = total+p if newtotal > halftotalscore: continue newmoves[newtotal] = people_left oldmoves = newmoves solution = min(map(lambda i: (abs(float(i)-halftotalscore), i), oldmoves.keys())) return (solution[1], sum(oldmoves[solution[1]]), oldmoves[solution[1]]) print team([90,200,100]) print team([2,3,10,5,8,9,7,3,5,2]) print team([1,1,1,1,1,1,1,1,1,9]) print team([87,100,28,67,68,41,67,1]) print team([1, 1, 50, 50, 50, 1000]) #output #(200, 190, [90, 100]) #(27, 27, [3, 9, 7, 3, 5]) #(5, 13, [1, 1, 1, 1, 9]) #(229, 230, [28, 67, 68, 67]) #(150, 1002, [1, 1, 1000]) Also note that I attempted to solve this using GS's description, but it is impossible to get enough information simply by storing the running totals. And if you stored both the number of items and totals, then it would be the same as this solution except you kept needless data. Because you only need to keep the n-1 and n iterations up to numplayers/2. I had an old exhaustive one based on binomial coefficients (look in history). It solved the example problems of length 10 just fine, but then I saw that the competition had people of up to length 100. Solution:2 Dynamic programming is the solution you're looking for. Example with [4, 3, 10, 3, 2, 5]: X-Axis: Reachable sum of group. max = sum(all numbers) / 2 (rounded up) Y-Axis: Count elements in group. max = count numbers / 2 (rounded up) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 | | | | 4| | | | | | | | | | | // 4 2 | | | | | | | | | | | | | | | 3 | | | | | | | | | | | | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 | | | 3| 4| | | | | | | | | | | // 3 2 | | | | | | | 3| | | | | | | | 3 | | | | | | | | | | | | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 | | | 3| 4| | | | | |10| | | | | // 10 2 | | | | | | | 3| | | | | |10|10| 3 | | | | | | | | | | | | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 | | | 3| 4| | | | | |10| | | | | // 3 2 | | | | | | 3| 3| | | | | |10|10| 3 | | | | | | | | | | 3| | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 | | 2| 3| 4| | | | | |10| | | | | // 2 2 | | | | | 2| 3| 3| | | | | 2|10|10| 3 | | | | | | | | 2| 2| 3| | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 | | 2| 3| 4| 5| | | | |10| | | | | // 5 2 | | | | | 2| 3| 3| 5| 5| | | 2|10|10| 3 | | | | | | | | 2| 2| 3| 5| 5| | | ^ 12 is our lucky number! Backtracing to get the group: 12 - 5 = 7 {5} 7 - 3 = 4 {5, 3} 4 - 4 = 0 {5, 3, 4} The other set can then be calculated: {4,3,10,3,2,5} - {5,3,4} = {10,3,2} All fields with a number are possible solutions for one bag. Choose the one that is furthest in the bottom right corner. BTW: It's called the knapsack-problem. If all weights (w1, ..., wn and W) are nonnegative integers, the knapsack problem can be solved in pseudo-polynomial time using dynamic programming. Solution:3 Well, you can find a solution to a percentage precision in polynomial time, but to actually find the optimal (absolute minimal difference) solution, the problem is NP-complete. This means that there is no polynomial time solution to the problem. As a result, even with a relatively small list of numbers, it is too compute intensive to solve. If you really need a solution, take a look at some of the approximation algorithms for this. Solution:4 Q. Given a multiset S of integers, is there a way to partition S into two subsets S1 and S2 such that the sum of the numbers in S1 equals the sum of the numbers in S2? Best of luck approximating. : ) Solution:5 Note that it is also an heuristic and I moved the sort out of the function. def g(data): sums = [0, 0] for pair in zip(data[::2], data[1::2]): item1, item2 = sorted(pair) sums = sorted([sums[0] + item2, sums[1] + item1]) print sums data = sorted([2,3,10,5,8,9,7,3,5,2]) g(data) Solution:6 It's actually PARTITION, a special case of KNAPSACK. It is NP Complete, with pseudo-polynomial dp algorithms. The pseudo in pseudo-polynomial refers to the fact that the run time depends on the range of the weights. In general you will have to first decide if there is an exact solution before you can admit a heuristic solution. Solution:7 A test case where your method doesn't work is que = [1, 1, 50, 50, 50, 1000] The problem is that you're analyzing things in pairs, and in this example, you want all the 50's to be in the same group. This should be solved though if you remove the pair analysis aspect and just do one entry at a time. Here's the code that does this def make_teams(que): que.sort() que.reverse() if len(que)%2: que.insert(0,0) t1,t2 = [],[] while que: if abs(len(t1)-len(t2))>=len(que): [t1, t2][len(t1)>len(t2)].append(que.pop(0)) else: [t1, t2][sum(t1)>sum(t2)].append(que.pop(0)) print min(sum(t1),sum(t2)), max(sum(t1),sum(t2)), "\n" if __name__=="__main__": que = [2,3,10,5,8,9,7,3,5,2] make_teams(que) que = [1, 1, 50, 50, 50, 1000] make_teams(que) This give 27, 27 and 150, 1002 which are the answers that make sense to me. Edit: In review, I find this to not actually work, though in the end, I'm not quite sure why. I'll post my test code here though, as it might be useful. The test just generates random sequence that have equal sums, puts these together and compares (with sad results). Edit #2: Based in the example pointed out by Unknown, [87,100,28,67,68,41,67,1], it's clear why my method doesn't work. Specifically, to solve this example, the two largest numbers need to both be added to the same sequence to get a valid solution. def make_sequence(): """return the sums and the sequence that's devided to make this sum""" while 1: seq_len = randint(5, 200) seq_max = [5, 10, 100, 1000, 1000000][randint(0,4)] seqs = [[], []] for i in range(seq_len): for j in (0, 1): seqs[j].append(randint(1, seq_max)) diff = sum(seqs[0])-sum(seqs[1]) if abs(diff)>=seq_max: continue if diff<0: seqs[0][-1] += -diff else: seqs[1][-1] += diff return sum(seqs[0]), sum(seqs[1]), seqs[0], seqs[1] if __name__=="__main__": for i in range(10): s0, s1, seq0, seq1 = make_sequence() t0, t1 = make_teams(seq0+seq1) print s0, s1, t0, t1 if s0 != t0 or s1 != t1: print "FAILURE", s0, s1, t0, t1 Solution:8 They are obviously looking for a dynamic programming knapsack solution. So after my first effort (a pretty good original heuristic I thought), and my second effort (a really sneaky exact combinatorial solution that worked for shortish data sets, and even for sets up to 100 elements as long as the number of unique values was low), I finally succumbed to peer pressure and wrote the one they wanted (not too hard - handling duplicated entries was the trickiest part - the underlying algorithm I based it on only works if all the inputs are unique - I'm sure glad that long long is big enough to hold 50 bits!). So for all the test data and awkward edge cases I put together while testing my first two efforts, it gives the same answer. At least for the ones I checked with the combinatorial solver, I know they're correct. But I'm still failing the submission with some wrong answer! I'm not asking for anyone to fix my code here, but I would be very greatful if anyone can find a case for which the code below generates the wrong answer. Thanks, Graham PS This code does always execute within the time limit but it is far from optimised. i'm keeping it simple until it passes the test, then I have some ideas to speed it up, maybe by a factor of 10 or more. #include <stdio.h> #define TRUE (0==0) #define FALSE (0!=0) static int debug = TRUE; //int simple(const void *a, const void *b) { // return *(int *)a - *(int *)b; //} int main(int argc, char **argv) { int p[101]; char *s, line[128]; long long mask, c0[45001], c1[45001]; int skill, players, target, i, j, tests, total = 0; debug = (argc == 2 && argv[1][0] == '-' && argv[1][1] == 'd' && argv[1][2] == '\0'); s = fgets(line, 127, stdin); tests = atoi(s); while (tests --> 0) { for (i = 0; i < 45001; i++) {c0[i] = 0LL;} s = fgets(line, 127, stdin); /* blank line */ s = fgets(line, 127, stdin); /* no of players */ players = atoi(s); for (i = 0; i < players; i++) {s = fgets(line, 127, stdin); p[i] = atoi(s);} if (players == 1) { printf("0 %d\n", p[0]); } else { if (players&1) p[players++] = 0; // odd player fixed by adding a single player of 0 strength //qsort(p, players, sizeof(int), simple); total = 0; for ( i = 0; i < players; i++) total += p[i]; target = total/2; // ok if total was odd and result rounded down - teams of n, n+1 mask = 1LL << (((long long)players/2LL)-1LL); for (i = 0; i < players; i++) { for (j = 0; j <= target; j++) {c1[j] = 0LL;} // memset would be faster skill = p[i]; //add this player to every other player and every partial subset for (j = 0; j <= target-skill; j++) { if (c0[j]) c1[j+skill] = c0[j]<<1; // highest = highest j+skill for later optimising } c0[skill] |= 1; // so we don't add a skill number to itself unless it occurs more than once for (j = 0; j <= target; j++) {c0[j] |= c1[j];} if (c0[target]&mask) break; // early return for perfect fit! } for (i = target; i > 0; i--) { if (debug || (c0[i] & mask)) { fprintf(stdout, "%d %d\n", i, total-i); if (debug) { if (c0[i] & mask) printf("******** ["); else printf(" ["); for (j = 0; j <= players; j++) if (c0[i] & (1LL<<(long long)j)) printf(" %d", j+1); printf(" ]\n"); } else break; } } } if (tests) printf("\n"); } return 0; } Solution:9 class Team(object): def __init__(self): self.members = [] self.total = 0 def add(self, m): self.members.append(m) self.total += m def __cmp__(self, other): return cmp(self.total, other.total) def make_teams(ns): ns.sort(reverse = True) t1, t2 = Team(), Team() for n in ns: t = t1 if t1 < t2 else t2 t.add(n) return t1, t2 if __name__ == "__main__": import sys t1, t2 = make_teams([int(s) for s in sys.argv[1:]]) print t1.members, sum(t1.members) print t2.members, sum(t2.members) >python two_piles.py 1 50 50 100 [50, 50] 100 [100, 1] 101 Solution:10 For performance you save computations by replacing append() and sum() with running totals. Solution:11 You could tighten your loop up a little by using the following: def make_teams(que): que.sort() t1, t2 = [] while que: t1.append(que.pop()) if sum(t1) > sum(t2): t2, t1 = t1, t2 print min(sum(t1),sum(t2)), max(sum(t1),sum(t2)) Solution:12 Since the lists must me equal the problem isn't NP at all. I split the sorted list with the pattern t1<-que(1st, last), t2<-que(2nd, last-1) ... def make_teams2(que): que.sort() if len(que)%2: que.insert(0,0) t1 = [] t2 = [] while que: if len(que) > 2: t1.append(que.pop(0)) t1.append(que.pop()) t2.append(que.pop(0)) t2.append(que.pop()) else: t1.append(que.pop(0)) t2.append(que.pop()) print sum(t1), sum(t2), "\n" Edit: I suppose that this is also a wrong method. Wrong results! Solution:13 After some thinking, for not too big problem, I think that the best kind of heuristics will be something like: import random def f(data, nb_iter=20): diff = None sums = (None, None) for _ in xrange(nb_iter): random.shuffle(data) mid = len(data)/2 sum1 = sum(data[:mid]) sum2 = sum(data[mid:]) if diff is None or abs(sum1 - sum2) < diff: sums = (sum1, sum2) print sums You can adjust nb_iter if the problem is bigger. It solves all the problem mentioned above mostly all the times. Solution:14 In an earlier comment I hypothesized that the problem as set was tractable because they had carefully chosen the test data to be compatible with various algorithms within the time alloted. This turned out not to be the case - instead it is the problem constraints - numbers no higher than 450 and a final set no larger than 50 numbers is the key. These are compatible with solving the problem using the dynamic programming solution I put up in a later post. None of the other algorithms (heuristics, or exhaustive enumeration by a combinatorial pattern generator) can possibly work because there will be test cases large enough or hard enough to break those algorithms. It's rather annoying to be honest because those other solutions are more challenging and certainly more fun. Note that without a lot of extra work, the dynamic programming solution just says whether a solution is possible with N/2 for any given sum, but it doesn't tell you the contents of either partition. Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com EmoticonEmoticon
http://www.toontricks.com/2018/05/tutorial-algorithm-to-divide-list-of.html
CC-MAIN-2018-43
refinedweb
2,508
67.28
# How Protonmail is getting censored by FSB in Russia A completely routine tech support ticket has uncovered unexpected bans of IP addresses of Protonmail — a very useful service for people valuing their Internet freedoms — in several regions of Russia. I seriously didn’t want to sensationalize the headline, but the story is so strange and inexplicable I couldn’t resist. ### TL;DR Disclaimer: the situation is still developing. There might not be anything malicious, but most likely there is. I will update the post once new information comes through. MTS and Rostelecom — two of the biggest Russian ISPs — started to block traffic to SMTP servers of the encrypted email service Protonmail according to an FSB request, with no regard for the official government registry of restricted websites. It seems like it’s been happening for a while, but no one paid special attention to it. Until now. All involved parties have received relevant requests for information which they’re obligated to reply. **UPD:** MTS has provided a scan of the FSB letter, which is the basis for restricting the access. Justification: the ongoing Universiade in Krasnoyarsk and “phone terrorism”. It’s supposed to prevent ProtonMail emails from going to emergency addresses of security services and schools. **UPD:** Protonmail was surprised by “these strange Russians” and their methods for battling fraud abuse, as well as suggested a more effective way to do it — via *abuse mailbox*. **UPD:** FSB’s justification doesn’t appear to be true: the bans broke ProtonMail’s *incoming* mail, rather than outgoing. **UPD:** Protonmail shrugged and changed the IP addresses of their MXs taking them out of the blocking after that particular FSB letter. What will happen next is open ended question. **UPD:** Apparently, such letter was not the only one and there is still a set of IP addresses of VOIP-services which are blocked without appropriate records in the official registry of restricted websites. We love our Habr users because they’re very tech-savvy. They understand what “computer hygiene” means. Some of our users have been using [Protonmail](http://protonmail.com) — an “encrypted email” service. We’ll discuss only the technological matter today, leaving discussion of the service itself and its business model aside. Every day we send out a lot of emails to our users, and since we care about our independence and their privacy, we don’t use external mail services (ESPs). Instead we use our own resources, from bare-metal servers and self-maintained MX servers to encrypting connections and owning our independent IP addresses. Last week our support team was overloaded by messages from Protonmail users, complaining that our mail doesn’t get through to them: > Hello. Since around the first week of March 2019, when I try to login, I get a red banner saying that they couldn’t send an email to my address. I tried to send a test message manually, to no avail.The mailbox itself, hosted by Protomail, is perfectly functional (other emails do come through fine). The last digest from Habr is from February 28th. > > > > I didn’t change any of the settings neither there nor on Protomail, but around the time the trouble first came up I was logged out of the Android app. > > > > I don’t think the account has been compromised, but I couldn’t find the list of IPs used to access it so I can’t be sure. I hope for your help, since without a working email I can’t vote on comments/posts. > > > > Changed the email address from Gmail to Protomail. The confirmation email doesn’t arrive to the new address. Of course, our tech support suggested the simple stuff like checking spam folders, but the sheer volume of similar complaints forced us to dig deeper. **Briefly on how email works** For most modern Internet users using email means logging into the “personal Inbox” on the email service provider’s website and then sending letters through the same web interface. Then some magic happens and a couple of moments later the letter arrives to the web interface on the receiving end. This “magic” is called SMTP (or esmtp, to be precise). The sending server extracts the domain part (after the @) from the receiving address and makes a DNS request for MX servers of the receiver’s domain. For support@habr.team, it looks like this: ![](https://habrastorage.org/r/w1560/webt/yk/ql/y3/ykqly3tg6zln6xmft_s1nb4bola.png) MX stands for “mail exchange”. It indicates the email service used by the receiver or, to be precise, what email servers the receiving domain’s hosting collects new mail. The example above shows that our domain, habr.team, is hosted by Google (G.Suite). After finding the MX servers, a request is made through the esmtp protocol to the server with the highest priority, to deliver the mail to the user. Multiple servers are listed for redundancy, since “interconnectivity” of the Internet is a very relative term. That’s how sending a letter looks like: ![](https://habrastorage.org/r/w1560/webt/y9/qp/hh/y9qphhtxk91vatelybzuc2gs9ie.png) NB: mail from a certain domain doesn’t necessarily have to be sent to users on MX servers listed in the DNS; this is only used for incoming mail. Outgoing mail can be forwarded through other servers, usually listed in an SPF record. We dug through our mail logs and discovered that connection attempts from our servers to Protomail’s MX servers (185.70.40.101, 185.70.40.102) always timed out. This looked strange for a number of reasons and resembled the mechanism for Internet censorship in Russia. **I’m terribly sorry, but I have to digress and tell you how Internet, autonomous systems and routing work** In general, the term “Internet” is made of two words: “Inter-Net”, and can be interpreted as “network of networks” or “united networks”. The Internet doesn’t have a “technical center” (though it does have an “organizing center”): it simply connects different networks that are, in theory, equal to each other (though some networks are more equal than others, but that’s a story for another day). Networks are called “Autonomous systems” (AS) and are connected to each other via gates, or “peers”. Each AS has a unique number used to identify it by other ASes. Like IP addresses, but in a more general way. Each network receives from its “neighbours” the topology of its connections to nearby networks, how these nearby networks connect to their nearby networks, etc. Essentially, each network has a map of how all AS connect with each other from the perspective of that network. A route from one AS to another according to that map is simply called “AS path”. For example, our autonomous system number (ASN) is 204671, Protonmail servers are hosted on the network of a large American corporation Neustar, and its ASN is 19905. We have two gates with ISPs, meaning two possible AS paths from us to the Neustar network. For a number of reasons, one of the gates (through MGTS) is preferable, so our AS path looks like this: 204671 (us) — 57681 (MGTS, the ISP), 8359 (MTS, the larger ISP) — 22822 (Limelight) — 19905 (Neustar). And here’s the routing table: ![](https://habrastorage.org/r/w1560/webt/gg/py/4k/ggpy4krchlicj-mjlds1kpwg_yc.png) Each traceroute to any of Protonmail’s two MX servers cut off at the MTS network and looked like this: ``` GW-Core-R3#traceroute ip 185.70.40.101 probe 1 timeout 3 Type escape sequence to abort. Tracing the route to 185.70.40.101 VRF info: (vrf in name/id, vrf out name/id) 1 185.2.126.73 [AS 57681] 2 msec 2 212.188.12.73 [AS 8359] 2 msec 3 195.34.50.73 [AS 8359] 3 msec 4 212.188.55.2 [AS 8359] 3 msec 5 * 6 * 7 * 8 * ``` We found an alternative host within the Neustar network and used it as reference to eliminate possible disruptions between MTS and Limelight: ``` GW-Core-R3#traceroute ip 156.154.208.234 probe 1 timeout 3 Type escape sequence to abort. Tracing the route to 156.154.208.234 VRF info: (vrf in name/id, vrf out name/id) 1 185.2.126.73 [AS 57681] 2 msec 2 212.188.12.73 [AS 8359] 2 msec 3 212.188.2.37 [AS 8359] 14 msec 4 212.188.54.2 [AS 8359] 20 msec 5 195.34.50.146 [AS 8359] 27 msec 6 195.34.38.54 [AS 8359] 37 msec 7 68.142.82.159 [AS 22822] 26 msec 8 * 9 156.154.208.234 [AS 19905] 26 msec ``` Meanwhile, we successfully completed another trace through another ISP to Protonmail’s MX servers (it cuts off at Neustar, but that’s expected — the connection still works): ``` $ traceroute -a 185.70.40.101 traceroute to 185.70.40.101 (185.70.40.101), 64 hops max, 52 byte packets 1 [AS49063] hidden (hidden) 5.149 ms 268.571 ms 6.707 ms 2 [AS49063] 185.99.11.146 (185.99.11.146) 5.161 ms 6.317 ms 5.476 ms 3 [AS0] 10.200.16.128 (10.200.16.128) 5.588 ms [AS0] 10.200.16.176 (10.200.16.176) 5.225 ms [AS0] 10.200.16.130 (10.200.16.130) 5.001 ms 4 [AS0] 10.200.16.49 (10.200.16.49) 6.480 ms [AS0] 10.200.16.156 (10.200.16.156) 5.439 ms 7.469 ms 5 [AS20764] 80-64-98-234.rascom.as20764.net (80.64.98.234) 6.208 ms 9.301 ms 6.348 ms 6 [AS20764] 80-64-100-102.rascom.as20764.net (80.64.100.102) 24.281 ms [AS20764] 80-64-100-86.rascom.as20764.net (80.64.100.86) 54.632 ms 23.936 ms 7 [AS20764] 81-27-254-223.rascom.as20764.net (81.27.254.223) 27.589 ms 116.438 ms 27.348 ms 8 [AS22822] siteprotect.security.neustar (68.142.82.153) 28.683 ms 25.376 ms 41.489 ms ``` Given that traceroute isn’t a very reliable tool, we conducted another couple experiments, for example, with MTS’s Looking Glass service: ![](https://habrastorage.org/r/w1560/webt/qf/z4/ku/qfz4kut1ootk1mn1ydp1mdoecj0.png) It became clear that it’s probably an intentional restriction of service at the MTS level. However, consulting with [Roskomnadzor’s official registry](http://blocklist.rkn.gov.ru) revealed that both addresses (neither domain name no IP) are not listed there: ![](https://habrastorage.org/r/w1560/webt/5k/7j/sx/5k7jsxf1na8mpncwtuufkgincvi.png) ![](https://habrastorage.org/r/w1560/webt/av/pk/ud/avpkud4_hpevw7u297-ol8t2fn0.png) ![](https://habrastorage.org/r/w1560/webt/_t/hi/uf/_thiufwc_dioa0swspwjsclo-mg.png) ![](https://habrastorage.org/r/w1560/webt/ft/kp/qa/ftkpqatohww7u0ypln53gucyc28.png) *Unable to find anything on your request* Leaving specifics of Internet censorship in Russia aside, there’s only one valid justification for an ISP to block a resource — the so-called “registry dump” containing the resource put there more or less legally. Sometimes resources get blocked without a relevant registry entry (they’re colloquially named “registry-less blocking”), and usually the justification for these doesn’t stand a chance in any legal case. At this point, we suspected a simple technical misunderstanding or a botched unlock of another unrelated site. Yes, we don’t sound the alarms without meticulously fact-checking everything first. We sent an email detailing our findings to MGTS tech support and asked for clarification. A bit later we received a non-answer: “it’s not us, it’s MTS, ask them”. Of course, we didn’t, but instead forced MGTS to do their job and investigate it properly. The response we got was very interesting: according to an MTS employee from the relevant department, they’ve been contacted by the FSB via an official letter №12/T/3/1-94 from 25 Feb 2019, demanding them to urgently block these hosts: ![](https://habrastorage.org/r/w1560/webt/wh/dn/pt/whdnptmds-0xp12rwxa3vws9smy.png) At this point, our bullshit detectors have gone off the scale and we dug even deeper. And faster. We sent a request to the FSB asking if the letter exists and if it does, what justification do they have: ![](https://habrastorage.org/r/w1560/webt/zj/pl/ut/zjpluthn28v5qvxqf-y61iza9fi.png) We asked MGTS to provide a justification as well: ![](https://habrastorage.org/r/w1560/webt/hk/w0/9s/hkw09stkepo9_uw224uoivlvbqw.png) After that, we went to some topical chat rooms in a certain illegal in Russia instant messaging service. The telecom community reacted pretty reluctantly: * “I had experience solving these issues and no one wants to use RKN’s tools. First, it’s complicated. Second, transferring the problem to another department doesn’t solve the problem”. * “You need to provide so much documentation and jump through so many bureaucratic hoops (and there’s monetary punishment for not doing all of that) that no one bothers”. Well, it’s hard to really judge them, seeing as those working in telecoms have to deal with so much crap (considering “SORM”, “network node” or “registry dump” aren’t just words to them, but a daily annoyance). Nevertheless, the Russian [Internet Defence Community’s](https://ozi-ru.org) chat room took the case enthusiastically and conducted a proper investigation of their own. ![](https://habrastorage.org/r/w1560/webt/ns/fb/sk/nsfbsk6jlxgvatqe_dxto1ccbl4.png) ![](https://habrastorage.org/r/w1560/webt/dh/j1/-y/dhj1-yyzxpybtusp6okbh9wke8g.png) They suggested an interesting idea — to check what ISPs (in Russia and otherwise) block access to the MX servers through [RIPE Atlas](https://atlas.ripe.net/). The results were predictable, but still very curious: in Russia, the servers are blocked by MTS and Rostelecom, as well as networks working through these two ISPs ([results on the primary MX server](https://atlas.ripe.net/measurements/20021704/), and the [backup one](https://atlas.ripe.net/measurements/20021705/)). The worldwide check detected issues in Russia, Ukraine and Iran ([worldwide results for the primary server](https://atlas.ripe.net/measurements/20022243/), and the [backup](https://atlas.ripe.net/measurements/20022244)). A more involved research showed that Rostelecom acts in a similar manner: ![](https://habrastorage.org/r/w1560/webt/ra/8q/_u/ra8q_uqy3exwhkezn73k7mldfvc.png) After the weekend, MTS finally provided a scan of the FSB letter that ordered the blocks. Of course, they blamed “telephone terrorists” and tied it all up to the XXIX World University Winter Games — Universiade 2019: ![](https://habrastorage.org/r/w780q1/webt/vh/gd/qy/vhgdqy5_kuvtbgpump4i2zoeufy.jpeg) ![](https://habrastorage.org/r/w780q1/webt/0o/lq/uz/0olquzbq7zdlpjpt7dlz4d28mrm.jpeg) Then Protomail representatives reacted on [reddit](https://www.reddit.com/r/ProtonMail/comments/az20il/russian_mts_blackholed_as19905_neustaras6_with/), [Twitter](https://twitter.com/ProtonMail/status/1105090222503747584) and [TechCrunch](https://techcrunch.com/2019/03/11/russia-blocks-protonmail/). As expected, they were surprised by the bluntness of FSB’s methods and offered to cooperate toward finding real criminals: > We have a dedicated team at abuse@protonmail.ch that helps to combat illegal activities. We were never contacted. Blocking MX like this does not make sense for the given "explanation" so we suspect something else is going on. > > — ProtonMail (@ProtonMail) [March 11, 2019](https://twitter.com/ProtonMail/status/1105090222503747584?ref_src=twsrc%5Etfw) Hmm. Protomail themselves suspected there’s a hidden agenda to all of this. Well, it appears to be the case. So, as I’ve already explained avobe, MX records are a mechanism for handling incoming emails. FSB clearly deliberately broke the incoming mail rather than outgoing, so their, ahem, “justification” of saving school headmasters from trouble is very clearly fabricated. So, we have three options: * They simply blocked what they first found (a lazy explanation, but the most probably one according to the Occam Razor: someone must have just read “nslookup for dummies”); * They tried to limit the possibility of setting up anonymous and untrackable Proton addresses collecting damaging information on themselves (doesn’t work in the vast majority of cases) * The cursory UFO explanation. Here’s the proof: an email sent from Proton to another service went through different IPs that aren’t blocked. Remember, FSB banned 185.70.40.101 and 185.70.40.102. Do you see these here? ![](https://habrastorage.org/r/w1560/webt/mf/ff/zy/mfffzyg-itm0tl9ecjzbdvsise8.png) Head of ProtonMail confirmed the findings to [TechCrunch](https://techcrunch.com/2019/03/11/russia-blocks-protonmail/) and suggested to fight terrorist activity in cooperation with foreign law enforcement, rather than just handwaving the issue away: > ProtonMail chief executive Andy Yen called the block “particularly sneaky,” in an email to TechCrunch. > > > > “ProtonMail is not blocked in the normal way, it’s actually a bit more subtle,” said Yen. “They are blocking access to ProtonMail mail servers. So Mail.ru — and most other Russian mail servers — for example, is no longer able to deliver email to ProtonMail, but a Russian user has no problem getting to their inbox,” he said. > > > > “The wholesale blocking of ProtonMail in a way that hurts all Russian citizens who want greater online security seems like a poor approach,” said Yen. He said his service offers superior security and encryption to other mail providing rivals in the country. > > > > “We have also implemented technical measures to ensure continued service for our users in Russia and we have been making good progress in this regard,” he explained. “If there is indeed a legitimate legal complaint, we encourage the Russian government to reconsider their position and solve problems by following established international law and legal procedures.” > > — ProtonMail chief executive Andy Yen @ [TechCrunch](https://techcrunch.com/2019/03/11/russia-blocks-protonmail/) Also, it looks like this FSB letter only ordered to block SMTP servers for incoming mail. Web access and outgoing SMTP servers still work, which means that whatever the FSB tried to do, they weren’t very good at it. We’ll say again: even disregarding the entire legal side of the issue of regulating the Internet on the very particular 1/8th of Earth land, there are rules of the game. The rules aren’t terribly clear, very ambiguous and they change all the time, but they’re still rules, even if they’re clearly designed to benefit the maintainers of these rules. And even then, there are people trying to bypass them. This was very Kafka-esque, with no due process at all. At least in any court case you can call upon an industry expert for consultation, but there the decision was purely based on the personal worldview of one particular person. So, here are all the facts we’ve gathered up to this point. All the requests have been sent, but not all have been responded to. Of course, we hoped that it was just a consequence of a botched job by someone at MTS, but, to be honest, it didn’t look terribly probable from the beginning. As for our users who also use Protomail, then they can safely continue to use their Proton mailboxes with Habr, since we rerouted the traffic from us to Protomail service through another Russian ISP that doesn’t play these sorts of games. And MGTS is probably about to lose another customer.
https://habr.com/ru/post/443638/
null
null
3,204
56.15
Heat Engine Combustion and efficiency of heat engines from source temperature, fuel, and combustion chamber dimensions. The Novikov efficiency rating can be compared with a process fraction of useful work in an eTCL calculator, developed from some code on a firebox. The impetus for these calculations was checking rated efficiency in some heat engines. These heat engines are called endoreversible engines. These endoreversible engines are rated from the (equation) Chambadal-Novikov efficiency (Nu) = 1.- sqrt(sink temperature low over temperature source high) or Nu = 1.-sqrt(tl/t2). These efficiency ratings are related to the Carnot engine, which was rated as Carnot efficiency (Nu)=1.-(t1/t2). As an electrical analog, the chart of a Novikov engine looks somewhat like a voltage source to resistors/LED to ground, where the output light is offset by resistor losses. For another example, the fire in a brick oven will cook the pizza with energy called the process heat fraction here, but much of the heat energy goes into heating the oven and the brick walls. Most of the testcases involve modeled data, using assumptions and rules of thumb .The Carnot heat engine with temperatures proportional to the golden ratio phi (1.618...) can be developed from the following relationships. The heat flow of work (W) equals the heat flow of the source (Qh) minus the heat flow of the sink (Qc). Following the Huleihul paper, the ratio of Qh/Qc = Qc/W, where the Carnot efficiency Nu = W/Qh, W=Qh-Qc,Qc=Qh-W, and W>Qc. The ratio equation Qh/Qc = Qc/W can be solved into a quadratic equation in f(Nu) . Moving terms, Qh*W=Qc*Qc,and substituting Qh*W = (Qh-W)*(Qh-W), Qh*W=Qh**2 -2*W*Qh+W**2. Shifting terms to the left side, Qh**2 +2*W*Qh+W*Qh+W**2 = 0, Qh**2 + 3*W*Qh+W**2 = 0, and dividing by Qh**2, 1+3*W*Qh/(Qh**2)-(W**2)/Qh**2=0. Substituting Nu=W/Qh and taking -1*, the equation is a quadratic equation in terms of f(Nu), Nu**2 - 3*Nu-1=0. Using the quadratic solution and leaving the negative solution behind, the quadratic solution is Nu =( 3+ (sqrt(5)) /2 or Nu=1-(1/phi), where phi is the golden ratio 1.618... For the Carnot engine limited to the golden ratio, Nu=0.382 and the initial equations and proportions take on a new utility for the Carnot engine. We have the ratio W/Qh=0.382 or ~ 4/10, Qh=2.6*W, and the ratio W/Qc = decimal 0.625 or ~6/10. Where Qh/Qc = Qc/W, then flipping W/Qh >> 1/0.382 for the right term, Qh/Qc= 1/0.625 or Qh/Qc=1.6, 1+6/10, or ~16/10. Returning to Nu=1-(1/phi), the losses part of the equation is (1/phi) and equals TL/TH. Rearranging terms in the equation 1/phi = TL/TH, so TL = TH*phi and TH = TL/phi.The solved ratios can be implemented into the eTCL routines for a firebox heat engine. Also, there are a lot of series and identities mathematics on the golden ratio, which are amenable to computer implementation (and peer review).Another way of examining heat engines is the study of the loss portions of the Carnot and Novikov equations. The loss portion of the Carnot engine would be TL/TH and the loss portion of the Novikov would be sqrt(TL)/sqrt(TH). For both engines, the raising source temperature TH means lower losses and higher efficiencies. Likewise for the sink temperature TL, the lowering TL means lower losses and thus higher efficiencies.A solar oven can be made from surplus parts to study the Novikov heat engine. A old wooden speaker box was painted with a black matte finish and was filled on the inside with a layer of styrofoam. The front of the speaker box was rectangular of width 40 cm and height 34 cm, extending back in a triangular form to about 45 cm. The diameter of the front speaker opening was about 22.6 cm. A V-shaped internal cavity was lined with glazed porcelain tiles. The thickness between the porcelain tiles and the wooden crate varies between 4 to 13 cm of styrofoam insulation. A small side hole of diameter 7 cm was kept as a side entry. In operation, the side cavity would be plugged with 1) a baffle of porcelain tile and 2) a conical styrofoam drink cup filled with bits of crushed styrofoam. The front circular opening just fit two pie pans of pyrex glass. Two pans were glued lid to lid together with epoxy for better insulation like so {}. The maximum diameter of the glued pans is 25 cm and the thickness of the disk is 7 cm. The sunlight enters the cavity through two layers of pyrex glass, a plastic fresnel lens, and a layer of air. The fresnel lens was intended to concentrate the entering energy in roughly the center of the cavity. At noon or solar max, the solar oven operates about 30 F or 20 C above the ambient temperature. The solar oven is usually propped up with three bricks to aim the front opening for the noon sun.The interior of the solar oven is a V-shaped cavity of about 3400 cubic centimeters. The front of the V-shaped cavity is a rectangle about 15 cm wide and 19 cm height, extended back about 24 cm in a triangular form. The V-shaped cavity acts as a solar trap with angles such that entering solar energy is less likely to be reflected out of the cavity. The white porcelain tiles reflect a substantial portion of light and radiant heat energy back to the centered target. As noon approaches, the tiles and pyrex glass get hot and should be handled with a towel.Several targets have been prepared and tried in the solar oven. For 24Aug2013, the shade temperature at noon was 90F or 32C. A small pint of tea in a transparent glass jar had reached a temperature of 110F or 42C at noon. At 1330 hours, the shade temperature was 89F or 31C and the small pint of tea was at 110F or 43C. At 1400 hours, the tea was replaced by a small sphere of wet green clay and by a small cup of roped green clay. Completely drying the clay would take about 3 days in this solar oven. At 1430 hours, a small blackened tin of soaked beans was added, but cooking beans is about a 8 hour job in this solar oven. The work of the heat engine was heating water, cooking beans, or drying green clay.Targets painted a flat black have an advantage in a solar oven, so a tin can was painted black on the outside, brick was painted flat black, and a pint glass jar was painted flat black on the inside. Although steam can crack glass, there is some advantage in putting solid targets inside blackened containers or doubled containers, eg. a blackened jar inside a transparent jar with loose lids to allow pressure to escape. At the end of effective sunlight, if is possible to cover the front opening and insulate the solar to continue some cooking after daylight. A blackened brick or other solid object can be added inside the cavity to retain some residual heat after daylight. Another way of retaining heat is to pour heated beans or soup into a thermos bottle, after peak of solar heat in the day.From the measured Kelvin temperatures, the Novikov efficiency of the solar oven can be calculated. At noon, the Novikov efficiency Nu(305K,315K) was 0.016, from the eTCL calculator. At 1330 hours, the Novikov efficiency Nu(304K,316K) was 0.019.The formula for combined cycle efficiency is Nu(combined) = Nu(1)+Nu(2) - Nu(1)*Nu(2). For an example using round numbers, the yoked value of a gas turbine generating electricity and the exhaust heat fed to a steam generator generating electricity. The formula eTCL statements below can be pasted into the console window, when the eTCL report function is activated with access to the utility subroutines. The Carnot and Novikov efficiencies can also be estimated in the eTCL calculator separately. The temperatures for the gas turbine is 1700 degrees K and the exhaust is 900 K, in round numbers. The measured efficiency of the gas turbine is Nu(1) equals 0.40. The followon steam generator is 900 K and the exhaust is 400 K. The measured efficiency of the steam generator is Nu(2) equals 0.33. The combined efficiencies from the Novikov formula (not measured), the Nu(combined) = Nu(1)+Nu(2) - Nu(1)*Nu(2), Nu(combined) = 0.40+0.32-(0.40*0.32), Nu(combined)= 0.592 or 59.2 percent. Comparing the measured efficiencies with the Novikov formula, the Novikov formula for the steam generator was in close agreement with the measured results, the Novikov results for the gas generator was not so good. Both the Carnot and Novikov formulas assume Newtonian heat flow, and above 900 K degrees radiant heat transfer (T**4 terms) becomes more important. The gist is that the Carnot and Novikov formulas start to break down above 900 K. namespace path {::tcl::mathop ::tcl::mathfunc} set Nu_combined [ - [ + 0.40 0.32 ] [* 0.40 0.32 ] ] answer% 0.592 for measured efficiencies set carnotefficiency_gas_turbine [ carnotthermic 1700 900] answer% 0.4705 or 47 percent set novikovefficiency_gas_turbine [ endothermic 1700 900] answer% 0.272 set carnotefficiency_steam [ carnotthermic 900 400] answer% 0.555 set novikovefficiency_steam [ endothermic 900 400] answer% 0.33 set Nu_combined_Novikov [ - [ + 0.272 0.33 ] [* 0.272 0.33 ] ] answer% 0.512 for Novikov estimated efficienciesThe formula for combined cycle efficiency is Nu(combined) = Nu(1)+Nu(2) - Nu(1)*Nu(2). It might be wondered why the Carnot efficiency is calculated and tracked with the Novikov efficiency? The Carnot efficiency is good at predicting the amount of heat loss to stack when natural gas is burned. Maybe a numerical coincidence, but when natural gas burned completely in air, about 50 to 60 percent heat goes up the stack. Without other considerations like power generation and radiant heat transfer, the efficiency of the natural gas furnace is 100%-(50% to 60% up the stack) or 50 to 40% efficient ( vis. measured gas Nu 40% vs Carnot 47 %).Pizza is baked for 20 minutes or 20*60, 1200 seconds in a brick oven, wood fired. Sink temperature T1 (300) and source temperature T2 ( 900 ) are inputs. The calculations should be carried out in Kelvin degrees. Exhaust or low temperature T1 is fixed at 300 degrees kelvin. Firing max temperature is calculated on a separate track, solving T**4 equation in chamber. namespace path {::tcl::mathop ::tcl::mathfunc} set Nu_Carnot [ - 1. [/ 300. 900. ] ] set Nu_Carnot [ - 1. [/ 300. 1200. ] ] set Nu_Carnot [ - 1. [/ 300. 1400. ] ] set Nu_Carnot [ - 1. [/ 300. 700. ] ] set Nu_Endoreversable [ - 1. [sqrt [/ 300. 900. ] ]] set Nu_Endoreversable [ - 1. [sqrt [/ 300. 1200. ] ]] set Nu_Endoreversable [ - 1. [sqrt [/ 300. 1400. ] ]] set Nu_Endoreversable [ - 1. [sqrt [/ 300. 700. ] ]] Testcase 4 Rating small gas stoves boiling water set Nu_Carnot [ - 1. [/ 32. 96.5 ] ] set Nu_Carnot [ - 1. [/ 24.5 95.5 ] ] set Nu_Carnot [ - 1. [/ 24. 96.5 ] ] set Nu_Novikov [ - 1. [sqrt [/ 32. 96.5 ] ]] set Nu_Novikov [ - 1. [sqrt [/ 24.5 95.5 ] ]] set Nu_Novikov [ - 1. [sqrt [/ 24.5 96.5 ] ]] Testcase 5 Rating kilns#Not sure formulas work on kilns? set Nu_Carnot [ - 1. [/ 300. 1370. ] ] set Nu_Carnot [ - 1. [/ 300. 1400. ] ] set Nu_Novikov [ - 1. [sqrt [/ 300. 1370. ] ]] set Nu_Novikov [ - 1. [sqrt [/ 300. 1400. ] ]] Testcase 5The fuel used was wood at 237 kg in 135 min or 135*60 or 8100 seconds. The average heat flux was 237*16 MJ/kg over 8100 seconds, 237*16/8100, or 0.468 MJ/S. A WATT is a joule per second, so the heat power is 0.468 E6 J/S, or 4.68E5 watts.Using electrical analog model, Q in watts equals (TH-TL)/(R1+R2+R3+R4) or (TH-TL)/(SUM of R) , where TH=1200 deg K and TL=300 deg K. From the eTCL calculator, Nu(1200,300)returns Carnot Nu 0.75 and Novikov Nu 0.5. The thermaI current is estimated as I=4.68E5 watts Many statements below can be pasted into eTCL console window. set current 4.5E5 R= delta T/ power or(1200K-300K) /4.68E5 watts delta 1200K-300K = 900K (SUM of delta T’s of each R) set R_overall [/ 900 4.65e5] SUM R =0.00190 OR 1.9e-3 R2 is largest component of SUM R For each R step, R= delta T/ power R1 is delta 100K / 4.5E5 =0.000222 R2 is delta 700K / 4.5E5 =0.001555 R3 is delta 50K / 4.5E5 =0.0001111 R4 is delta 50K / 4.5E5 =0.0001111 2% set R1 [/ 100 4.5E5] 0.000222 3% set R2 [/ 700 4.5E5] 0.001555 4% set R3 [/ 50 4.5E5] 0.001111 5% set R4 [/ 50 4.5E5] 0.001111 6% set sumR [+ 0.000222 0.001555 0.000111 0.000111 ] 0.00199 P=VOLTS*CURRENT>> (T1-T2)*I set R2_power [* [- 800 100] 500] 350000 set efficiency [/ 3.5E5 4.5E5 ] 0.77777 set process_heat [/ [* [- 100 50] 500] 4.5E5 ] 0.0555 or 5.55 percent. Only small portion of heat cooks pizza Screenshots Section figure 1. figure 2. figure 3. figure 4. figure 5. figure 6. figure 7. figure 8. References: - Kenyan Ceramic Jiko cooking stove, by Hugh Allen - Endoreversible Thermodynamics, Katharina Wagner, - thesis pub. Chemnitz University of Technology, July 07, 2008 - - Introduction toEndoreversible Thermodynamics , Karl Heinz Hoffman, - Atti dell’Accademia Peloritana,February 01, 2008 - Summary of heat engines, Lecture 12, - Endoreversible thermodynamics, wikipedia - Comment on concept of endoreversibility, Bjarne Andresen, - Oersted Laboratory, University of Copenhagen - Specific Heat Ratio of an Endoreversible Otto Cycle,R. Ebrahimi,Shahrekord University - Golden Section Heat Engines, Mahmoud Huleihill, Gedalya Mazor , - Sami Shamoon College of Engineering, Israel, pub Feb 2012 - Efficiency of atomic power stations,Novikov, Atomnaya Energiya, 3:409, 1957. in Russian. - Efficiency of atomic power stations,Journal Nuclear Energy II, 7:125-128, 1958.,translated - Thermodynamics. Mashinostroenie, M. P. Vukalovich and I. I. Novikov - Efficiency of a Carnot Engine at Maximum Power Output, - Curzon and B. Ahlborn Am. J. Phys. 43, 22 (1975). - Efficiency Measurement of Biogas, Kerosene and LPG Stoves Appendix Code edit appendix TCL programs and scripts # pretty print from autoindent and ased editor # heat engine combustion calculator # written on Windows XP on eTCL # working under TCL version 8.5.6 and eTCL 1.0.1 # gold on TCL WIKI , 9aug2013 package require Tk namespace path {::tcl::mathop ::tcl::mathfunc} frame .frame -relief flat -bg aquamarine4 pack .frame -side top -fill y -anchor center set names {{} {combustion chamber diameter meters:} } lappend names {combustion chamber height meters:} lappend names {heat source temperature input: } lappend names {heat sink temperature input: } lappend names {answer: volume cubic meters} lappend names {total heat units, megajoules:} lappend names {endo process, applied/total energy: } Heat Engine Combustion from TCL WIKI, written on eTCL " tk_messageBox -title "About" -message $msg } proc pi {} {expr acos(-1)} proc pistonvolumex { d h } { set pistonvolumexxx [* .25 [pi] $d $d $h ] return $pistonvolumexxx } proc heatx { vol density } { set fuel_mass [* $vol $density] set total_heat [* $fuel_mass 40.1] return $total_heat } proc endothermic { theatsource tlow } { set endo [expr { 1.-sqrt($tlow)/sqrt($theatsource)} ] return $endo } proc carnotthermic { theatsource tlow } { set theatsource [* 1. $theatsource] set tlow [* 1. $tlow] set carnot [- 1. [/ $tlow $theatsource]] return $carnot } proc endoprocess { theatsource tlow } { set theatsource [* 1. $theatsource] set tlow [* 1. $tlow] set endoprocess [* .25 [- 1. [/ $tlow $theatsource]]] return $endoprocess } proc firebox { total_heat burn_time cross_section temp_ambient temp_flame} { set d $cross_section set firing_temp 1 set heat_flux [/ $total_heat $burn_time] set heat_flux_persec [/ $heat_flux $burn_time] set cross_section [ / [* [pi] $d $d ] 4.] set item 25 set temp_ambient 25 set temp_flame 1488. set tx $temp_ambient set taxx $temp_flame set t 25 set h [/ $heat_flux_persec $cross_section] while {$item <= 4000} { incr item set t [+ $t 1 ] set term1 [* 1. $t $t $t $t] set term2 [* 1. $tx $tx $tx $tx] set term1 [* .000000000056703 [ - $term1 $term2]] set term2 [* $h 1.1 [/ [- $taxx $t] [ - $taxx $tx ]]] set difference [abs [- $term1 $term2]] if {$difference < 2.} { set temp_answer $t } } return $temp_answer } proc calculate { } { global answer2 global side1 side2 side3 side4 side5 global side6 side7 testcase_number fuel global piston_volume piston_temperature_exp global workdays total_heat massfromvolume global total_heat firebox_temp heatsourcetemp2 global carnotefficiency novikovefficiency global idealappliedovertotal piston_firing_time global heatsinktemp1 incr testcase_number set piston_diameter $side1 set piston_height $side2 set piston_firing_time [* 2 60 10] set heatsourcetemp2 $side3 set heatsinktemp1 $side4 set piston_volume 1 set piston_volume [pistonvolumex $piston_diameter $piston_height] set fuel_density 850 set massfromvolume [* $piston_volume $fuel_density] set fuel [* [ / 8.2 60. ] $massfromvolume] set total_heat [* 13.5 $fuel] set temp_amb 25. set temp_flame 1488. set piston_temperature_exp $temp_flame set total_heat_joules [* $total_heat 1.0E6] set firebox_temp [firebox $total_heat_joules $piston_firing_time $piston_diameter $temp_amb $temp_flame] if {$piston_temperature_exp > 1200.} {set piston_temperature_exp 1200} set workdays [/ $piston_volume 3. ] set carnotefficiency [ carnotthermic $heatsourcetemp2 $heatsinktemp1] set novikovefficiency [ endothermic $heatsourcetemp2 $heatsinktemp1] set idealappliedovertotal [ endoprocess $heatsourcetemp2 $heatsinktemp1] set fractionwork [ endoprocess $heatsourcetemp2 $heatsinktemp1] set side5 $piston_volume set side6 $total_heat set side7 $fractionwork } fuel global piston_temperature massfromvolume global piston_volume workdays global total_heat firebox_temp global piston_temperature_exp global carnotefficiency novikovefficiency global idealappliedovertotal global piston_firing_time heatsourcetemp2 global heatsinktemp1 console show; puts "testcase number: $testcase_number" puts "piston diameter meters: $side1 " puts "piston height meters: $side2 " puts "piston firing seconds: $piston_firing_time " puts "volume cubic meters: $side5 " puts "total energy MJ: $side6 " puts "piston volume m*m*m: $piston_volume " puts "heat source temperature T2 $heatsourcetemp2" puts "heat sink temperature T1 $heatsinktemp1" puts "max room fuel kg $massfromvolume" puts "estimated fuel, kg $fuel" puts "total heat megajoules $total_heat" puts "firing max temperature $firebox_temp " puts "man workdays to load fuel $workdays" puts "Carnot efficiency $carnotefficiency" puts "Novikov efficiency $novikovefficiency" puts "ideal applied/total $idealappliedovertotal " } frame .buttons -bg aquamarine4 ::ttk::button .calculator -text "Solve" -command { calculate } ::ttk::button .test2 -text "Testcase1" -command {clearx;fillup .5 .5 900. 300. 0.0981 153.9 .166 } ::ttk::button .test3 -text "Testcase2" -command {clearx;fillup 1.5 1.5 1200. 300. 2.65 4156. .1875 } ::ttk::button .test4 -text "Testcase3" -command {clearx;fillup 2. 2. 1400. 300. 6.28 9853. .196 } : . "Heat Engine Combustion Calculator " Pushbutton Operation |&" Initial Console Program # pretty print from autoindent and ased editor # Novikov efficiency of small gas stoves # written on Windows XP on eTCL # working under TCL version 8.5.6 and eTCL 1.0.1 # gold on TCL WIKI , 8aug2013 package require Tk namespace path {::tcl::mathop ::tcl::mathfunc} console show proc novikov { theatsource tlow } { set endo [expr { 1.-sqrt($tlow)/sqrt ($theatsource)} ] return $endo } proc carnot { theatsource tlow } { set theatsource [* 1. $theatsource] set tlow [* 1. $tlow] set carnot [- 1. [/ $tlow $theatsource]] return $carnot } proc k { temperature } { set temperature [+ $temperature 273. ] return $temperature } puts "%|name|water boiled|measured Nu|Novikov Nu|Carnot Nu |%" puts "&|stove a|1 l|49.4|[* 100 [novikov 96.5 32.]]|[* 100. [carnot 96.5 32.]]|&" puts "&|stove b|1 l|43.8|[* 100. [novikov 95.5 24.5]] |[* 100. [carnot 95.5 24.5]] |&" puts "&|stove c|0.5 l|32.4|[* 100. [novikov 96.5 24.]] |[carnot 96.5 24.]|&" gold This page is copyrighted under the TCL/TK license terms, this license Please place any comments here, Thanks.
http://wiki.tcl.tk/38453
CC-MAIN-2018-30
refinedweb
3,219
57.27
Crypt::GCrypt::MPI - Perl interface to multi-precision integers from the GNU Cryptographic library use Crypt::GCrypt::MPI; my $mpi = Crypt::GCrypt::MPI->new(); Crypt::GCrypt::MPI provides an object interface to multi-precision integers from the C libgcrypt library. Create a new multi-precision integer. my $mpi = Crypt::GCrypt::MPI::new( secure => 1, value => 20, ); No parameters are required. If only one parameter is given, it is treated as the "value" parameter. Available parameters: The initial value of the MPI. This can be an integer, a string, or another Crypt::GCrypt::MPI. (It would also be nice to be able to initialize it with a Math::Int). If this parameter evaluates to non-zero, initialize the MPI using secure memory, if possible. If the value is a string, the format parameter suggests how to convert the string. See CONVERSION FORMATS for the available formats. Defaults to Crypt::GCrypt::MPI::FMT_STD. Copies the value of the other Crypt::GCrypt::MPI object. $mpi->set($othermpi); Exchanges the value with the value of another Crypt::GCrpyt::MPI object: $mpi->swap($othermpi); Returns true if the Crypt::GCrypt::MPI uses secure memory, where possible. Compares this object against another Crypt::GCrypt::MPI object, returning 0 if the two values are equal, positive if this value is greater, negative if $other is greater. Compares this object against another Crypt::GCrypt::MPI object, returning true only if the two values share no factors in common other than 1. Returns a new Crypt::GCrypt::MPI object, with the contents identical to this one. This is different from using the assignment operator (=), which just makes two references to the same object. For example: $b = new Crypt::GCrypt::MPI(15); $a = $b; $b->add(1); # $a points to the same object, # so both $a and $b contain 16. $a = $b->copy(); # $a and $b are both 16, but # different objects; no risk of # double-free. $b->add(1); # $a == 16, $b == 17 If $b is a Crypt::GCrypt::MPI object, then "$a = $b->copy();" is identical to "$a = Crypt::GCrypt::MPI->new($b);" All calculation operations modify the object they are called on, and return the same object, so you can chain them like this: $g->addm($a, $m)->mulm($b, $m)->gcd($x); If you don't want an operation to affect the initial object, use the copy() operator: $h = $g->copy()->addm($a, $m)->mulm($b, $m)->gcd($x); Adds the value of $other to this MPI. Adds the value of $other to this MPI, modulo the value of $modulus. Subtracts the value of $other from this MPI. Subtracts the value of $other from this MPI, modulo the value of $modulus. Multiply this MPI by the value of $other. Multiply this MPI by the value of $other, modulo the value of $modulus. Multiply this MPI by 2 raised to the power of $e (this is a leftward bitshift) Divide this MPI by the value of $other, leaving the integer quotient. (This is integer division) Divide this MPI by the value of $other, leaving the integer remainder. (This is the modulus operation) Raise this MPI to the power of $other, modulo the value of $modulus. Find the multiplicative inverse of this MPI, modulo $modulus. Find the greatest common divisor of this MPI and $other. Send the MPI to the libgcrypt debugging stream. Return a string with the data of this MPI, in a given format. See CONVERSION FORMATS for the available formats. The available printing and scanning formats are all in the Crypt::GCrypt::MPI namespace, and have the same meanings as in gcrypt. Two's complement representation. Same as FMT_STD, but with two-byte length header, as used in OpenPGP. (Only works for non-negative values) Same as FMT_STD, but with four-byte length header, as used by OpenSSH. Hexadecimal string in ASCII. Simple unsigned integer. Crypt::GCrypt::MPI does not currently auto-convert to and from Math::BigInt objects, even though it should. Other than that, here are no known bugs. You are very welcome to write mail to the maintainer (aar@cpan.org) with your contributions, comments, suggestions, bug reports or complaints. Daniel Kahn Gillmor <dkg@fifthhorseman.net> Alessandro Ranellucci <aar@cpan.org> Copyright © Daniel Kahn Gillmor. Crypt::GCrypt::MPI)..
http://search.cpan.org/dist/Crypt-GCrypt/lib/Crypt/GCrypt/MPI.pm
CC-MAIN-2016-36
refinedweb
706
57.77
In a previous post I talked a bit about writing a snake game in Haskell. At the end of the post we had a working game, but there was 1 ingredient missing; the snake would not go anywhere by itself! The fundamental problem was that our game was being driven by Haskell's lazy IO. Whenever a new character appeared on stdin the runtime would crank the handle on our Haskell code, transforming this character into a sequence of IO actions that the runtime evaluates to print the game world to the screen. This use of lazy IO meant that basically all of the logic (except drawing to the screen) could take place outside the IO monad in nice, pure code. The challenge now was to find a way of inserting an extra stream of "fake messages from the keyboard" that would be delivered at regular intervals (these would make the snake move forward without me having to type a key). It seemed to make sense to retain the "pipeline" structure of the code, so I thought about modifying it as illustrated by the following ascii-art: directions from >-+-------------------------+-> update game world keyboard | | and draw update +-> forward most recent >-+ every X seconds I came across the Pipes library pretty quickly, and was delighted to see that the first example in the pipes-concurrency tutorial is a game! Essentially all I had to do was launch 3 threads that would run the above 3 components, with each one either feeding messages to, or reading messages from, a mailbox. The above diagram translates into the following haskell (inside the IO monad) (mO, mI) <- spawn unbounded (dO, dI) <- spawn $ latest West let inputTask = getDirections >-> to (mO <> dO) delayedTask = from dI >-> rateLimit 1 >-> to mO drawingTask = for (from mI >-> transitions initialWorld) (lift . drawUpdate) We first create some mailboxes: the main one ( mO and mI), which drawingTask will draw directions from, and the one that will handle the delayed directions ( dO and dI). Then we build up some pipelines that feed and consume these messages to and from the pipelines. All we need to do now is to run each of these pipelines in a separate thread using the async function. This is a bit involved because we first need to "unwrap" the pipeline into an IO action using runEffect (and perform garbage collection ¯\_(ツ)_/¯). let run p = async $ runEffect p >> performGC tasks <- sequence $ map run [inputTask, delayedTask, drawingTask] waitAny tasks The full code is on Github. Thoughts Lots of stuff happens in monads I previously had the impression that Haskell code was super readable because it was composed of teeny tiny functions that only do one thing. However, after reading a bit of Haskell code (for example the Pipes.Concurrent library) I realised that a lot of Haskell code is written inside monads which, in my opinion, harms readability. When I say that the code "happens in monads" what I really mean is that code is written using Haskell's do notation that allows you to write code that looks like it's imperative, but it really just a bunch of monadic compositions: do x <- x_monad y <- returns_a_monad(x) return (x + y) the above contrived example is equivalent to the following chain of monadic bind operations: x_monad >>= (\x -> returns_a_monad(x) >>= (\y -> return (x + y))) which is certainly more difficult to read than the do notation! However, because it is easy to build up a lot of context when using do notation, I find it goes a bit against the grain of composing tiny functions that do only one thing. Hopefully as I gain competence in Haskell I'll be able to overcome these hurdles. Haskell's import style is scary The language I have worked in most is recent years is Python. The zen of Python teaches us that explicit is better than implicit, because it makes code easier to reason about. Given this, I find Haskell's default mode when importing modules somewhat scary. In Haskell, when you say import foo, this is equivalent to saying from foo import * in Python. This means that you get a bunch of arbitrary names injected into your namespace. This isn't quite as bad as import * in Python from a code-correctness perspective because Haskell is statically typed, and so any problems will (most probably) be caught at compile time. From a code readability perspective, however, I find it to be a complete nightmare; someone reading the code has no idea where an (often cryptically named) function comes from! For example, Pipes.Concurrent exports a function called spawn that creates a new mailbox. Someone reading the code may naturally assume that spawn has something to do with creating new threads, but without knowing even what module it comes from, it's very difficult to tell. Now Haskell experts may well respond with "read the code and the meaning will be obvious" or merely "get gud", but I would posit that the whole point of things like clear variable names and explicit imports is that you shouldn't have to "get gud" to get a sense of what some code is trying to do. Maintaining mental context is hard, and as communicators we should try and reduce the burden by not requiring people to retain excess information, such as which modules export exactly which functions. I am, of course, aware that Haskell has several variants of its import syntax, such as import qualified (which requires you to prepend the namespace, as you would with a regular import in Python) or by specifying explicitly which names should be imported. However, the overwhelming majority of Haskell code that I have read so far has made use of the unqualified syntax, making it more difficult than necessary to decipher people's code.
http://joseph.weston.cloud/blog/haskell-snake2/
CC-MAIN-2019-09
refinedweb
964
60.18
Deploy an ASP.NET MVC 5 mobile web app in Azure App Service This tutorial will teach you the basics of how to build an ASP.NET MVC 5 web app that is mobile-friendly and deploy it to Azure App Service. For this tutorial, you need Visual Studio Express 2013 for Web or the professional edition of Visual Studio if you already have that. You can use Visual Studio 2015 but the screen shots will be different and you must use the ASP.NET 4.x templates. Note: To complete this tutorial, you need an Azure account. You can activate your Visual Studio subscriber benefits or sign up for a free trial. What You'll Build For this tutorial, you'll add mobile features to the simple conference-listing application that's provided in the starter project. The following screenshot shows the ASP.NET sessions in the completed application, as seen in the browser emulator in Internet Explorer 11 F12 developer tools. You can use the Internet Explorer 11 F12 developer tools and the Fiddler tool to help debug your application. Skills You'll Learn Here's what you'll learn: - How to use Visual Studio 2013 to publish your web application directly to a web app in Azure App Service. - How the ASP.NET MVC 5 templates use the CSS Bootstrap framework to improve display on mobile devices - How to create mobile-specific views to target specific mobile browsers, such as the iPhone and Android - How to create responsive views (views that respond to different browsers across devices) Set up the development environment Set up your development environment by installing the Azure SDK for .NET 2.5.1 or later. - To install the Azure SDK for .NET, click the link below. If you don't have Visual Studio 2013 installed yet, it will be installed by the link. This tutorial requires Visual Studio 2013. Azure SDK for Visual Studio 2013 - In the Web Platform Installer window, click Install and proceed with the installation. You will also need a mobile browser emulator. Any of the following will work: - Browser Emulator in Internet Explorer 11 F12 developer tools (used in all mobile browser screenshots). It has user agent string presets for Windows Phone 8, Windows Phone 7, and Apple iPad. - Browser Emulator in Google Chrome DevTools. It contains presets for numerous Android devices, as well as Apple iPhone, Apple iPad, and Amazon Kindle Fire. It also emulates touch events. - Opera Mobile Emulator Visual Studio projects with C# source code are available to accompany this topic: Deploy the starter project to an Azure web app Download the conference-listing application starter project. Then in Windows Explorer, right-click the downloaded ZIP file and choose Properties. In the Properties dialog box, choose the Unblock button. (Unblocking prevents a security warning that occurs when you try to use a .zip file that you've downloaded from the web.) Right-click the ZIP file and select Extract All to unzip the file. In Visual Studio, open the C#\Mvc5Mobile.sln file. In Solution Explorer, right-click the project and click Publish. In Publish Web, click Microsoft Azure App Service. If you haven't already logged into Azure, click Add an account. Follow the prompts to log into your Azure account. The App Service dialog should now show you as signed in. Click New. In the Web App Name field, specify a unique app name prefix. Your fully-qualified web app name will be <prefix>.azurewebsites.net. Also, select or specify a new resource group name in Resource group. Then, click New to create a new App Service plan. Configure the new App Service plan and click OK. Back in the Create App Service dialog, click Create. After the Azure resources are created, the Publish Web dialog will be filled with the settings for your new app. Click Publish. Once Visual Studio finishes publishing the starter project to the Azure web app, the desktop browser opens to display the live web app. Start your mobile browser emulator, copy the URL for the conference application ( .azurewebsites.net) into the emulator, and then click the top-right button and select Browse by tag. If you are using Internet Explorer 11 as the default browser, you just need to type F12, then Ctrl+8, and then change the browser profile to Windows Phone. The image below shows the AllTags view in portrait mode (from choosing Browse by tag). Tip: While you can debug your MVC 5 application from within Visual Studio, you can publish your web app to Azure again to verify the live web app directly from your mobile browser or a browser emulator. The display is very readable on a mobile device. You can also already see some of the visual effects applied by the Bootstrap CSS framework. Click the ASP.NET link. The ASP.NET tag view is zoom-fitted to the screen, which Bootstrap does for you automatically. However, you can improve this view to better suit the mobile browser. For example, the Date column is difficult to read. Later in the tutorial you'll change the AllTags view to make it mobile-friendly. Bootstrap CSS Framework New in the MVC 5 template is built-in Bootstrap support. You have already seen how it immediately improves the different views in your application. For example, the navigation bar at the top is automatically collapsible when the browser width is smaller. On the desktop browser, try resizing the browser window and see how the navigation bar changes its look and feel. This is the responsive web design that is built into Bootstrap. To see how the Web app would look without Bootstrap, open App_Start\BundleConfig.cs and comment out the lines that contain bootstrap.js and bootstrap.css. The following code shows the last two statements of the RegisterBundles method after the change: bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( //"~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new StyleBundle("~/Content/css").Include( //"~/Content/bootstrap.css", "~/Content/site.css")); Ctrl+F5 to run the application. Observe that the collapsible navigation bar is now just an ordinary unordered list. Click Browse by tag again, then click ASP.NET. In the mobile emulator view, you can see now that it is no longer zoom-fitted to the screen, and you must scroll sideways in order to see the right side of the table. Undo your changes and refresh the mobile browser to verify that the mobile-friendly display has been restored. Bootstrap is not specific to ASP.NET MVC 5, and you can take advantage of these features in any web application. But it is now built into the ASP.NET MVC 5 project template, so that your MVC 5 Web application can take advantage of Bootstrap by default. For more information about Bootstrap, go to the Bootstrap site. In the next section you'll see how to provide mobile-browser specific views. Override the Views, Layouts, and Partial Views You, you can5 Application to MVC5 Application (Mobile). In each Html.ActionLink call for the navigation bar, remove "Browse by" in each link ActionLink. The following code shows the completed <ul class="nav navbar-nav"> tag of the mobile layout file. <ul class="nav navbar-nav"> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li>@Html.ActionLink("Date", "AllDates", "Home")</li> <li>@Html.ActionLink("Speaker", "AllSpeakers", "Home")</li> <li>@Html.ActionLink("Tag", "AllTags", "Home")</li> </ul> (the title from _Layout.Mobile.cshtml and the title from AllTags.Mobile.cshtml). In contrast, the desktop display has not changed (with titles from _Layout.cshtml and AllTags.cshtml). Create Browser-Specific Views In addition to mobile-specific and desktop-specific views, you can create views for an individual browser. For example, you can create views that are specifically for the iPhone or the Android browser. In this section, you'll create a layout for the iPhone browser and an iPhone version of the AllTags view. Open the Global.asax file and add the following code to the bottom. Note: When adding mobile browser-specific display modes, such as for iPhone and Android, be sure to set the first argument to 0 (insert at the top of the list) to make sure that the browser-specific mode takes precedence over the mobile template (*.Mobile.cshtml). If the mobile template is at the top of the list instead, it will be selected over your intended display mode (the first match wins, and the mobile template matches all mobile browsers). In the code, right-click DefaultDisplayMode, choose Resolve, and then choose using System.Web.WebPages;. This adds a reference to the System.Web.WebPages namespace, which is where the DisplayModeProvider and DefaultDisplayMode types are defined. Alternatively, you can just manually add the following line to the using section of the file. using System.Web.WebPages; Save the changes. Copy the Views\Shared\_Layout.Mobile.cshtml file to Views\Shared\_Layout.iPhone.cshtml. Open the new file and then change the title from MVC5 Application (Mobile) to MVC5 Application (iPhone). Copy the Views\Home\AllTags.Mobile.cshtml file to. If you are using the emulator in Internet Explorer 11 F12 developer tools, configure emulation to the following: - Browser profile = Windows Phone - User agent string = Custom - Custom string = Apple-iPhone5C1/1001.525 The following screenshot shows the AllTags view rendered in the emulator in Internet Explorer 11 F12 developer tools with the custom user agent string (this is an iPhone 5C user agent string). In the mobile browser, select the Speakers link. Because there's not a mobile view (AllSpeakers.Mobile.cshtml), the default speakers view (AllSpeakers.cshtml) is rendered using the mobile layout view (_Layout.Mobile.cshtml). As shown below, the title MVC5 Application (Mobile) is defined in _Layout.Mobile.cshtml. (i.e. when (without the string "(Mobile)" in the navigational bar at the top). You can disable consistent display mode in a specific; } In this section we've seen how to create mobile layouts and views and how to create layouts and views for specific devices such as the iPhone. However, the main advantage of the Bootstrap CSS framework is the responsive layout, which means that a single stylesheet can be applied across desktop, phone, and tablet browsers to create a consistent look and feel. In the next section you'll see how to leverage Bootstrap to create mobile-friendly views. Improve the Speakers List As you just saw, the Speakers view is readable, but the links are small and are difficult to tap on a mobile device. In this section, you'll make the AllSpeakers view mobile-friendly, which displays large, easy-to-tap links and contains a search box to quickly find speakers. You can use the Bootstrap linked list group styling to improve the Speakers view. In Views\Home\AllSpeakers.cshtml, replace the contents of the Razor file with the code below. @model IEnumerable<string> @{ ViewBag. @foreach (var speaker in Model) { @Html.ActionLink(speaker, "SessionsBySpeaker", new { speaker }, new { @class = "list-group-item" }) } </div> The class="list-group" attribute in the <div> tag applies the Bootstrap list styling, and the class="input-group-item" attribute applies Bootstrap list item styling to each link. Refresh the mobile browser. The updated view looks like this: The Bootstrap linked list group styling makes the entire box for each link clickable, which is a much better user experience. Switch to the desktop view and observe the consistent look and feel. Although the mobile browser view has improved, it's difficult to navigate the long list of speakers. Bootstrap doesn't provide a search filter functionality out-of-the-box, but you can add it with a few lines of code. You will first add a search box to the view, then hook up with the JavaScript code for the filter function. In Views\Home\AllSpeakers.cshtml, add a <form> tag just after the <h2> tag, as shown below: @model IEnumerable<string> @{ ViewBag. <span class="input-group-addon"><span class="glyphicon glyphicon-search"></span></span> <input type="text" class="form-control" placeholder="Search speaker"> </form> <br /> <div class="list-group"> @foreach (var speaker in Model) { @Html.ActionLink(speaker, "SessionsBySpeaker", new { speaker }, new { @class = "list-group-item" }) } </div> Notice that the <form> and <input> tags both have the Bootstrap styles applied to them. The <span> element adds a Bootstrap glyphicon to the search box. In the Scripts folder, add a JavaScript file called filter.js. Open the file and paste the following code into it: $(function () { // reset the search form when the page loads $("form").each(function () { this.reset(); }); // wire up the events to the <input> element for search/filter $("input").bind("keyup change", function () { var searchtxt = this.value.toLowerCase(); var items = $(".list-group-item"); // show all speakers that begin with the typed text and hide others for (var i = 0; i < items.length; i++) { var val = items[i].text.toLowerCase(); val = val.substring(0, searchtxt.length); if (val == searchtxt) { $(items[i]).show(); } else { $(items[i]).hide(); } } }); }); You also need to include filter.js in your registered bundles. Open App_Start\BundleConfig.cs and change the first bundles. Change the first bundles.Add statement (for the jquery bundle) to include Scripts\filter.js, as follows: bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js", "~/Scripts/filter.js")); The jquery bundle is already rendered by the default _Layout view. Later, you can utilize the same JavaScript code to apply the filter functionality to other list views. Refresh the mobile browser and go to the AllSpeakers view. In the search box, type "sc". The speakers list should now be filtered according to your search string. Improve the Tags List Like the Speakers view, the Tags view is readable, but the links are small and difficult to tap on a mobile device. You can fix the Tags view the same way you fix the Speakers view, if you use the code changes described earlier, but with the following Html.ActionLink method syntax in Views\Home\AllTags.cshtml: @Html.ActionLink(tag, "SessionsByTag", new { tag }, new { @class = "list-group-item" }) The refreshed desktop browser looks as follows: And the refreshed mobile browser looks as follows: Note: If you notice that the original list formatting is still there in the mobile browser and wonder what happened to your nice Bootstrap styling, this is an artifact of your earlier action to create mobile specific views. However, now that you are using the Bootstrap CSS framework to create a responsive web design, go head and remove these mobile-specific views and the mobile-specific layout views. Once you have done so, the refreshed mobile browser will show the Bootstrap styling. Improve the Dates List You can improve the Dates view like you improved the Speakers and Tags views if you use the code changes described earlier, but with the following Html.ActionLink method syntax in Views\Home\AllDates.cshtml: @Html.ActionLink(date.ToString("ddd, MMM dd, h:mm tt"), "SessionsByDate", new { date }, new { @class = "list-group-item" }) You will get a refreshed mobile browser view like this: You can further improve the Dates view by organizing the date-time values by date. This can be done with the Bootstrap panels styling. Replace the contents of the Views\Home\AllDates.cshtml file with the following code: @model IEnumerable<DateTime> @{ ViewBag. <div class="panel-heading"> @dategroup.Key.ToString("ddd, MMM dd") </div> <div class="panel-body list-group"> @foreach (var date in dategroup) { @Html.ActionLink(date.ToString("h:mm tt"), "SessionsByDate", new { date }, new { @class = "list-group-item" }) } </div> </div> } This code creates a separate <div class="panel panel-primary"> tag for each distinct date in the list, and uses the linked list group for the respective links as before. Here's what the mobile browser looks like when this code runs: Switch to the desktop browser. Again, note the consistent look. Improve the SessionsTable View In this section, you'll make the SessionsTable view more mobile-friendly. This change is more extensive the previous changes. In the mobile browser, tap the Tag button, then enter asp in the search box. Tap the ASP.NET link. As you can see, the display is formatted as a table, which is currently designed to be viewed in the desktop browser. However, it's a little bit difficult to read on a mobile browser. To fix this, open Views\Home\SessionsTable.cshtml and then replace the contents of the file with the following code: @model IEnumerable<Mvc5Mobile.Models.Session> <h2>@ViewBag.Title</h2> <div class="container"> <div class="row"> @foreach (var session in Model) { <div class="col-md-4"> <div class="list-group"> @Html.ActionLink(session.Title, "SessionByCode", new { session.Code }, new { @ <div class="list-group-item-text"> @Html.Partial("_SpeakersLinks", session) </div> <div class="list-group-item-info"> @session.DateText </div> <div class="list-group-item-info small hidden-xs"> @Html.Partial("_TagsLinks", session) </div> </div> </div> </div> } </div> </div> The code does 3 things: - uses the Bootstrap custom linked list group to format the session information vertically, so that all this information is readable on a mobile browser (using classes such as list-group-item-text) - applies the grid system to the layout, so that the session items flow horizontally in the desktop browser and vertically in the mobile browser (using the col-md-4 class) - uses the responsive utilities to hide the session tags when viewed in the mobile browser (using the hidden-xs class) You can also tap a title link to go to the respective session. The image below reflects the code changes. The Bootstrap grid system that you applied automatically arranges the sessions vertically in the mobile browser. Also, notice that the tags are not shown. Switch to the desktop browser. In the desktop browser, notice that the tags are now displayed. Also, you can see that the Bootstrap grid system you applied arranges the session items in two columns. If you enlarge the browser, you will see that the arrangement changes to three columns. Improve the SessionByCode View Finally, you'll fix the SessionByCode view to make it mobile-friendly. In the mobile browser, tap the Tag button, then enter asp in the search box. Tap the ASP.NET link. Sessions for the ASP.NET tag are displayed. Choose the Building a Single Page Application with ASP.NET and AngularJS link. The default desktop view is fine, but you can improve the look easily by using some Bootstrap GUI components. Open Views\Home\SessionByCode.cshtml and replace the contents with the following markup: @model Mvc5Mobile.Models.Session @{ ViewBag. <div class="panel-heading"> Speakers </div> @foreach (var speaker in Model.Speakers) { @Html.ActionLink(speaker, "SessionsBySpeaker", new { speaker }, new { @ <div class="panel-heading"> Tags </div> @foreach (var tag in Model.Tags) { @Html.ActionLink(tag, "SessionsByTag", new { tag }, new { @class = "panel-body" }) } </div> The new markup uses Bootstrap panels styling to improve the mobile view. Refresh the mobile browser. The following image reflects the code changes that you just made: Wrap Up and Review This tutorial has shown you how to use ASP.NET MVC 5 to develop mobile-friendly Web applications. These include: - Deploy an ASP.NET MVC 5 application to an App Service web app - Use Bootstrap to create responsive web layout in your MVC 5 application - Override layout, views, and partial views, both globally and for an individual view - Control layout and partial override enforcement using the RequireConsistentDisplayModeproperty - Create views that target specific browsers, such as the iPhone browser - Apply Bootstrap styling in Razor code See Also - 9 basic principles of responsive web design - Bootstrap - Official Bootstrap Blog - Twitter Bootstrap Tutorial from Tutorial Republic - The Bootstrap Playground - W3C Recommendation Mobile Web Application Best Practices - W3C Candidate Recommendation for media queries What's changed - For a guide to the change from Websites to App Service see: Azure App Service and Its Impact on Existing Azure Services
https://azure.microsoft.com/en-us/documentation/articles/web-sites-dotnet-deploy-aspnet-mvc-mobile-app/
CC-MAIN-2016-18
refinedweb
3,301
57.16
In today’s Programming Praxis exercise, our goal is to calculate the Mersenne prime exponents up to 256. Let’s get started, shall we? A quick import: import Data.Numbers.Primes The Mersenne primes can be determine with a simple list comprehension. Although the Lucas-Lehmer test officially doesn’t work for M2, in practice it works just fine so there is no need to make it a special case. mersennes :: [Int] mersennes = [p | p <- primes, iterate (\n -> mod (n^2 - 2) (2^p - 1)) 4 !! p-2 == 0] A test shows that the algorithm is working correctly. Piece of cake. main :: IO () main = print $ takeWhile (<= 256) mersennes == [2,3,5,7,13,17,19,31,61,89,107,127] Tags: bonsai, code, Haskell, kata, mersenne, praxis, primes, programming
http://bonsaicode.wordpress.com/2011/06/03/programming-praxis-mersenne-primes/
CC-MAIN-2014-41
refinedweb
129
76.11
wxRegEx represents a regular expression. This class provides support for regular expressions matching and also replacement. It is built on top of either the system library (if it has support for POSIX regular expressions - which is the case of the most modern Unices) or uses the built in Henry Spencer's library. Henry Spencer would appreciate being given credit in the documentation of software which uses his library, but that is not a requirement. Regular expressions, as defined by POSIX, come in two flavours: extended and basic. The builtin library also adds a third flavour of expression advanced, which is not available when using the system library. Unicode is fully supported only when using the builtin library. When using the system library in Unicode mode, the expressions and data are translated to the default 8-bit encoding before being passed to the library. On platforms where a system library is available, the default is to use the builtin library for Unicode builds, and the system library otherwise. It is possible to use the other if preferred by selecting it when building the wxWidgets. Derived from No base class Data structures Flags for regex compilation to be used with Compile(): enum { // use extended regex syntax wxRE_EXTENDED = 0, // use advanced RE syntax (built-in regex only) #ifdef wxHAS_REGEX_ADVANCED wxRE_ADVANCED = 1, #endif // use basic RE syntax wxRE_BASIC = 2, // ignore case in match wxRE_ICASE = 4, // only check match, don't set back references wxRE_NOSUB = 8, // if not set, treat '\n' as an ordinary character, otherwise it is // special: it is not matched by '.' and '^' and '$' always match // after/before it regardless of the setting of wxRE_NOT[BE]OL wxRE_NEWLINE = 16, // default flags wxRE_DEFAULT = wxRE_EXTENDED }Flags for regex matching to be used with Matches(). These flags are mainly useful when doing several matches in a long string to prevent erroneous matches for '' and '$': enum { // '^' doesn't match at the start of line wxRE_NOTBOL = 32, // '$' doesn't match at the end of line wxRE_NOTEOL = 64 }Examples A bad example of processing some text containing email addresses (the example is bad because the real email addresses can have more complicated form than user@host.net): wxString text; ... wxRegEx reEmail = wxT("([^@]+)@([[:alnum:].-_].)+([[:alnum:]]+)"); if ( reEmail.Matches(text) ) { wxString text = reEmail.GetMatch(email); wxString username = reEmail.GetMatch(email, 1); if ( reEmail.GetMatch(email, 3) == wxT("com") ) // .com TLD? { ... } } // or we could do this to hide the email address size_t count = reEmail.ReplaceAll(text, wxT("HIDDEN@\\2\\3")); printf("text now contains %u hidden addresses", count);Include files <wx/regex.h> wxRegEx::wxRegEx wxRegEx::~wxRegEx wxRegEx::Compile wxRegEx::IsValid wxRegEx::GetMatch wxRegEx::GetMatchCount wxRegEx::Matches wxRegEx::Replace wxRegEx::ReplaceAll wxRegEx::ReplaceFirst wxRegEx() Default ctor: use Compile() later. wxRegEx(const wxString& expr, int flags = wxRE_DEFAULT) Create and compile the regular expression, use IsValid to test for compilation errors. ~wxRegEx() dtor not virtual, don't derive from this class bool Compile(const wxString& pattern, int flags = wxRE_DEFAULT) Compile the string into regular expression, return true if ok or false if string has a syntax error. bool IsValid() const Return true if this is a valid compiled regular expression, false otherwise. bool GetMatch(size_t* start, size_t* len, size_t index = 0) const Get the start index and the length of the match of the expression (if index is 0) or a bracketed subexpression (index different from 0). May only be called after successful call to Matches() and only if wxRE_NOSUB was not used in Compile(). Returns false if no match or if an error occurred. wxString GetMatch(const wxString& text, size_t index = 0) const Returns the part of string corresponding to the match where index is interpreted as above. Empty string is returned if match failed May only be called after successful call to Matches() and only if wxRE_NOSUB was not used in Compile(). size_t GetMatchCount() const Returns the size of the array of matches, i.e. the number of bracketed subexpressions plus one for the expression itself, or 0 on error. May only be called after successful call to Compile(). and only if wxRE_NOSUB was not used. bool Matches(const wxChar* text, int flags = 0) const bool Matches(const wxChar* text, int flags, size_t len) const bool Matches(const wxString& text, int flags = 0) const Matches the precompiled regular expression against the string text, returns true if matches and false otherwise. Flags may be combination of wxRE_NOTBOL and wxRE_NOTEOL. Some regex libraries assume that the text given is null terminated, while others require the length be given as a separate parameter. Therefore for maximum portability assume that text cannot contain embedded nulls. When the Matches(const wxChar *text, int flags = 0) form is used, a wxStrlen() will be done internally if the regex library requires the length. When using Matches() in a loop the Matches(text, flags, len) form can be used instead, making it possible to avoid a wxStrlen() inside the loop. May only be called after successful call to Compile(). int Replace(wxString* text, const wxString& replacement, size_t maxMatches = 0) const Replaces the current regular expression in the string pointed to by text, with the text in replacement and return number of matches replaced (maybe 0 if none found) or -1 on error. The replacement text may contain back references \number which will be replaced with the value of the corresponding subexpression in the pattern match. \0 corresponds to the entire match and & is a synonym for it. Backslash may be used to quote itself or & character. maxMatches may be used to limit the number of replacements made, setting it to 1, for example, will only replace first occurrence (if any) of the pattern in the text while default value of 0 means replace all. int ReplaceAll(wxString* text, const wxString& replacement) const Replace all occurrences: this is actually a synonym for Replace(). See also ReplaceFirst int ReplaceFirst(wxString* text, const wxString& replacement) const Replace the first occurrence. See also Replace
http://docs.wxwidgets.org/stable/wx_wxregex.html
crawl-002
refinedweb
981
52.7
Interrupt, Perform a specific function, not the loop Hi. I have a node which sleeps most of the time and It has interrupt function enabled. But I want to perform a specific function when Node awake from sleep through interrupt pin 2, not the loop and again it should go to sleep using gw.sleep command. Is it possible to perform that specific function on an interrupt? describes what I need but I want to implement sleep function of mysensors also. May someone please help me? - scalz Hardware Contributor last edited by hi. it is not recommended, and not good practice to do stuff in your interrupt routine. you must keep it short. one idea and there are others : you could set a boolean to true in your interrupt routine for this. and use this flag like you want in your loop for example. do things if your boolean=true or not... - martinhjelmare Plugin Developer last edited by martinhjelmare The sleep function with single interrupt returns true if woken by the interrupt and false if woken by the timer. Sleeping with two interrupts returns the number of the interrupt pin that wakes it or negative if timer wakes. See the API. I would check the return value of the sleep function and divide the loop into at least two functions. One is run if interrupt wakes it, the other is run after timer wake up. edit Note that it's the interrupt number and not the pin number of the interrupt, that is returned for the two pin interrupt sleep function, according to the API. This sounds great! Do you have a code example? It's untested, but here you go. It's a modified version of the sketch by @Anticimex for a binary switch with two interrupts. - Anticimex Contest Winner last edited by I tested it when I submitted it so I can vouch for the functionality. At least for the time of submission. But the library might have changed since then of course. @martinhjelmare Thank you so much buddy for the help. I have not tested it yet. Can I use it with mysensors 1.4 version? Because I am using easyiot as controller and it uses 1.4 version. Yes, I don't see why it shouldn't work with version 1.4, but as I said, I haven't even tested this myself yet. Try it, and post back if you encounter problems. It'll be interesting to see what your final version will be. Btw, @hek, I noticed that the API says that the sleep function with two interrupts returns a bool, but looking at github it should be int8_t, which also makes sense. int8_t sleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrupt2, uint8_t mode2, unsigned long ms=0); I have tried it with single interrupt and It is working good so far on my mysensors 1.4 version. In case of interrupt wake = gw.sleep(INTERRUPT,FALLING, SLEEP_TIME); I use wake value (wake == 1) for function related to interrupt and use else condition for function related to timer wake up. Here is my sketch if someone finds it useful. It uses LDR to set night mode in low light conditions and vice versa, door reed switch and PIR sensor to turn ac or dc lights with the help of two channel relay and EasyIOT as server. Interrupts perform the functions of turning lights on and off while timer wake up decides the night mode implementation. Moreover, sensor node sleeps most of its time to conserve the battery. #include <SPI.h> #include <MySensor.h> #define CHILD_ID_LIGHT 0 #define CHILD_ID_DOOR 1 #define CHILD_ID_PIR 2 #define CHILD_ID_LED 3 #define CHILD_ID_SAVER 4 #define LDR_PIN A0 #define DOOR_PIN 2 #define PIR_PIN 3 #define LED_PIN 4 // Relay 1 is attached #define SAVER_PIN 5 // Relay 2 is attached #define INTERRUPT DOOR_PIN-2 unsigned long SLEEP_TIME = 1200000; // Sleep time 1200000 i.e. 20 minutes (in milliseconds) MySensor gw; boolean activity = false; boolean LEDSwitch = false; boolean SaverSwitch = false; boolean nightSwitch = false; MyMessage msgLDR(CHILD_ID_LIGHT, V_LIGHT_LEVEL); MyMessage msgDoor(CHILD_ID_DOOR, V_TRIPPED); MyMessage msgPir(CHILD_ID_PIR, V_TRIPPED); void setup() { gw.begin(NULL, AUTO, false, 1); gw.sendSketchInfo("BedRoom", "1.2"); pinMode(DOOR_PIN,INPUT); pinMode(PIR_PIN,INPUT); pinMode(LED_PIN, OUTPUT); pinMode(SAVER_PIN, OUTPUT); digitalWrite(DOOR_PIN, HIGH); digitalWrite(PIR_PIN, HIGH); digitalWrite(LED_PIN, HIGH); digitalWrite(SAVER_PIN, HIGH); gw.present(CHILD_ID_LIGHT, S_LIGHT_LEVEL); gw.present(CHILD_ID_DOOR, S_DOOR); gw.present(CHILD_ID_PIR, S_MOTION); int LightLevel; for(int i = millis(); i < (millis() + 5000); i++){ LightLevel = (100 - ((1023-analogRead(LDR_PIN))/10.23)); } if(LightLevel < 20){ gw.send(msgLDR.set(LightLevel)); nightSwitch = true; } else { gw.send(msgLDR.set(LightLevel)); nightSwitch = false; } } void loop() { if(nightSwitch){ //When night switch is on int wake; wake = gw.sleep(INTERRUPT,FALLING, SLEEP_TIME); if(wake == 1){ if(!activity){ gw.send(msgDoor.set("1")); gw.send(msgDoor.set("0")); activity = true; if((!LEDSwitch) && (!SaverSwitch)){ pirswitch(); } else{ //activity finished activityoff(); } } } else{ //Timer wake up int LightLevel; if((!LEDSwitch) && (!SaverSwitch)){ for(int i = millis(); i < (millis() + 5000); i++){ LightLevel = (100 - ((1023-analogRead(LDR_PIN))/10.23)); } } else{ for(int i = millis(); i < (millis() + 1000); i++){ LightLevel = (100 - ((1023-analogRead(LDR_PIN))/10.23)); } } if((LightLevel < 10) && ((!LEDSwitch) && (SaverSwitch))){ Serial.println("Light level is less than 50%, Turning LED on"); digitalWrite(LED_PIN, LOW); LEDSwitch = true; SLEEP_TIME = 7200000; // Sleep time changed to 2 hours } else if((LightLevel > 20) && ((!LEDSwitch) && (!SaverSwitch))){ gw.send(msgLDR.set(LightLevel)); nightSwitch = false; SLEEP_TIME = 7200000; // Sleep time changed to 2 hours gw.sleep(SLEEP_TIME); } else if((LightLevel > 5) && (nightSwitch) && ((!LEDSwitch) && (!SaverSwitch))){ gw.send(msgLDR.set(LightLevel)); SLEEP_TIME = 600000; // Sleep time changed to 10 minutes } } } else { //When night switch is off int LightLevel; for(int i = millis(); i < (millis() + 5000); i++){ LightLevel = (100 - ((1023-analogRead(LDR_PIN))/10.23)); } if(LightLevel < 20){ gw.send(msgLDR.set(LightLevel)); nightSwitch = true; SLEEP_TIME = 7200000; // Sleep time changed to 2 hours gw.sleep(INTERRUPT,FALLING, SLEEP_TIME); } else if((LightLevel < 30) && (!nightSwitch)){ SLEEP_TIME = 600000; // Sleep time changed to 10 minutes gw.sleep(SLEEP_TIME); } else if((LightLevel < 50) && (!nightSwitch)){ SLEEP_TIME = 1800000; // Sleep time changed to 30 minutes gw.sleep(SLEEP_TIME); } } } void pirswitch() { for(int i = millis(); i < (millis() + 5000); i++){ //Check PIR for activity 10 times with delay of half second boolean tripped = digitalRead(PIR_PIN) == HIGH; Serial.println(i); if(tripped){ gw.send(msgPir.set(tripped?"1":"0")); Serial.println("Motion detected"); //activity on function activityon(); Serial.println("Loop terminated"); break; } } delay(3000); activity = false; } void activityon() { //turn saver on digitalWrite(SAVER_PIN, LOW); SaverSwitch = true; Serial.println("Energy saver turned on"); int LightLevel; for(int i = millis(); i < (millis() + 1000); i++){ //Check if energy saver is on LightLevel = (100 - ((1023-analogRead(LDR_PIN))/10.23)); } if(LightLevel < 10){ Serial.println("Light level is less than 50%, Turning LED on"); digitalWrite(LED_PIN, LOW); LEDSwitch = true; } else{ SLEEP_TIME = 1000; Serial.println("Sleep time changed to second"); } } void activityoff() { delay(3000); //turn off saver or LED digitalWrite(SAVER_PIN, HIGH); digitalWrite(LED_PIN, HIGH); Serial.println("Activity finished"); SaverSwitch = false; LEDSwitch = false; activity = false; SLEEP_TIME = 7200000; Serial.println("Sleep time changed to 2 hours"); } - AWI Hero Member last edited by @vickey Just curious, what is the purpose of this piece of code? for(int i = millis(); i < (millis() + 5000); i++){ LightLevel = (100 - ((1023-analogRead(LDR_PIN))/10.23)); } @martinhjelmare In your code example, the sleep function needs a non-zero last parameter, in order to wake on timer. So line 104 should read: wake_cause = sensor_node.sleep(PRIMARY_BUTTON_PIN-2, CHANGE, SECONDARY_BUTTON_PIN-2, CHANGE, SLEEP_TIME); where SLEEP_TIME is in milliseconds, e.g., unsigned long SLEEP_TIME = 60000; // 60 sec sleep time between reads (seconds * 1000 milliseconds) Just tested this on the binary switch sketch. @AWI This code runs continuously for 5 seconds in order to get a stable reading of light using LDR, which is used to set night mode on and off.
https://forum.mysensors.org/topic/2207/interrupt-perform-a-specific-function-not-the-loop
CC-MAIN-2018-30
refinedweb
1,279
58.18
Computer Science Archive: Questions from June 13, 2010 - Anonymous askedI am planning to create this "Flashdisk to Flashdisk File SharingTechnology using Bluetooth" bec... Show morehi! I am planning to create this "Flashdisk to Flashdisk File SharingTechnology using Bluetooth" because i thnk it's a necessity andnobody has ever invented or studied it. How it works: the device is like a typical USB flash drive only that it has anLCD screen where you can see the files you would want to transfer.Using Bluetooth you don't have to look for a computer, justtransfer the file presto. It helps when there's brown out or whenyour laptop's battery runs out, and other emergency cases. Do youthink it's good?what is your opinion? BUT..my problem is... after programming the interface and the function of it, how would ilet it appear in the screen of my device? im not oriented withhardwares. i do not even know how would i connect the powersupply(battery) to it. thanks. • Show less0 answers - Anonymous askedIt has to ask the user for a text file where... Show moreI am stuck on this program that I am supposed to create. It has to ask the user for a text file where the format lookslike: MATH 101 GEOLOGY 101 GYM 101 Then i'm supposed to store the information from the file in anarray which then gets pointed to a function that creates a new datastructure and then gets pointed to another function which printsthe data from the text file. I am extremely stuck on this...can anyone please help? Here is the code i've worked on so far... #include <stdlib.h> #include <stdio.h> #include <stdbool.h> //created a data structure that consists of a courseName andcourseNumber typedef struct { char courseName; int courseNumber; } Course; //this is a function that returns a reference to a new coursestructure allocated from heap Course *createCourse(int name, int number) { Course *newCourse; newCourse = (Course*)malloc(sizeof(Course)); newCourse.courseName = name newCourse.courseNumber = number return newCourse; } //this function takes in the array of courseName pointers andcourseNumber po void printCourse(Course *newCourse) { printf ("Course Name: %s",(newCourse*).courseName); printf ("Course Number: %d",(newCourse*).courseNumber); } int main() { FILE* pFile = NULL; char data[255]; char filename[80]; // asking the user to enter a filename, the file will readthe conents printf("Please enter a filename for input:"); scanf("%s", &filename); pFile = fopen(filename, "r"); if (pFile == NULL) { printf ("Error openingfile!\n"); return -1; } while (!feof(pFile)) { fscanf(pFile, "%s \n",data); *createCourse(data } fclose(pFile); } • Show less0 answers - Anonymous asked Study the Inter-process communication mechanism available inLinux and explain the following points:... Show more Study the Inter-process communication mechanism available inLinux and explain the following points: 1 answer - How is a communication link established between twoprocesses running on the same machine? - How does a process write to another process - How does a process read from another process - Anonymous asked1 answer - Anonymous asked1. What are the benefits and drawbacks of starting most newhires at he help desk function? 2. What a0 answers - Anonymous askeddesign and implement a GUI program to convert a positivenumber given in one base to another. for thi... Show moredesign and implement a GUI program to convert a positivenumber given in one base to another. for this problem, assumethat both the base is less than or equal to 10. eg- convert 2010 using base 3 and then the new base is4. 2010 in base 3 is 57 andthen 57 with base 4 is 321. please note - the input number can be anything by the user(but only positive) the output of the GUI needs to look like as follows : the bottom is the convert button • Show less1 answer - InfamousAnimal973 askedUsing the Visual Studio IDE, create a Form that contains a buttonlabeled "About". When a user clicks... Show moreUsing the Visual Studio IDE, create a Form that contains a buttonlabeled "About". When a user clicks the button, display aMessageBox thatcontains your personal copyright statement for the program. Save the project as About.cs.Additional comments in the code are required. Thank you.• Show less1 answer - Anonymous askedWrite a small program to print the sum of the integers between Mand N, inclusive, where M... Show moreProgram is, Write a small program to print the sum of the integers between Mand N, inclusive, where M and N are program constants. With an M of1 and an N of 100, your program should print 5050. Modify the program to use scanf to read the two limiting values andto behave sensibly even if M >= N. Use a FOR loop to compute the sum. Use scanf to read the two limiting values, rather than programconstants. Create two functions, besides the main function. One functionshould be passed the values of m and n, and return the sum of theintegers between them inclusive. This sum should then be passed tothe other function which will print it. What would some good(meaningful) names be for these functions? Remember to use localvariables, rather than global variables, if needed. Have the program continue to prompt the user for input using awhile loop until they enter valid input values, i.e., m<n. Makesure that your printed output demonstrate this error check byincluding test runs for both m>n and m=n. Thank you for your help for looking into it. • Show less1 answer - Anonymous asked3 answers - GoldenEgg askedCustom... Show morewrite c++ program that will store the data of 40customers in file .the program should takeCustomer ID ( do not assign sequentialId let the user to assign any ID)NamePhone numberCurrent BalanceAddress ( The user should be able toEnter Mutiple Line Address )The program should Allow the user to searchthe File by Customer ID or By name(it should display in menu if you want to search by CustomerId press 1 Or if by name press 2 )The program should display complete information of customer whose ID or name entered by the user• Show less1 answer - Anonymous askedthe ca... Show more Build anefficient Huffman tree using the algorithm we discussed in classfor the following: the cat in the hat Show allsteps in building the tree. The counts for each character havealready been calculated for you. Also note the blank is representedby an underscore ( ). • Show less0 answers - Anonymous asked1 answer - Anonymous asked1. What are the benefits and drawbacks of starting most newhires at he help desk function? 2. What a0 answers
http://www.chegg.com/homework-help/questions-and-answers/computer-science-archive-2010-june-13
CC-MAIN-2014-52
refinedweb
1,065
63.59
Introduction: In this article I will explain how to save/upload files in folder and download files from folder system when click on link in gridview using asp.net. In this article I will explain how to save/upload files in folder and download files from folder system when click on link in gridview using asp.net. Description: In many websites we will see download link whenever we click on that we will have a chance to download that files into our system. In many websites we will see download link whenever we click on that we will have a chance to download that files into our system. Generally we have different ways to save files like directly in our database or our project folder. If we save files in our database it will occupy more space so it will create problem for us after host website because host providers will provide limited space for us we can solve this problem by saving files in our project folder. Here I am going to use another post how to insert images in folder and display images from folder to implement concept like save files in folder and download those files from file system using asp.net. To implement this first design table in your database like below to save file details in database. After that design your aspx page like this After completion of aspx page design add the following namespaces in code behind C# Code After that write the following code in code behind VB.NET Code Demo Download sample code attached 95 comments : Nice aritcal .......it is very useful to me ..Thanks.. super website nice sir you are great Great Suresh!!! how to upload the file on ftp server and retrieve,i mean show the file in gridview with remove and download button. please help me... This site are very good.......it's very help full. thanks Mr. suresh dasari your reg red by shamsul huda wonderful sir you are star you need to make big photo of your in website good post . Thanks , bhaskar very nice article specially those who are beginner. When i upload into hosting it is not working . how to resolve this issue.please help me sdfdf its good for all asp .net viewers and also for beginners.... Hey Suresh, Harsh here, Ur code is good and its very helpful. I wud suggest not to use the project folder directly, instead U can create a folder on the server and ther U can upload files, directly uploading in the project folder can lead to hacking...:-) @muthu... i think that problem is because of path to folder please change the path to your hosting provider server path... nice site for beginners hi... suresh garu.. me articles really very useful in realtime..sir.. thanks... You have to allow nulls in your table for the ID or it may not work. Hi suresh, If user click the save button in download save dialog box,i want to update the database with downloaded time,can u please help me. it is working gud....but when uploading large files throwing ERROR...? i faced exception in linkbtn coding . @Cherry... To solve that error you need to increase the upload size of your files in web.config check this article thank u for valuable information sharing with us Nice work boss really useful sort thanx..... hi suresh....tis s bargava,ur blog is really nice and useful,and can u send me the code of upload and download the file such as,msword,pdf into sql datbase ,without using gridview....am hoping to get a reply soon... i want to know how to scroll news headlines in ovrewebsite Hi good job ........ i need one help how upload image postgres sql database using vb.net .... Gracias, tu ejemplo es muy claro y sencillo, justo lo que uno busca, me ayudo mucho. Now, I'm working with telerik asp.net ajax controls if you know, please, i need help. thanks thanks very well, thank you. really appreciate it. Very useful. I needed to serve invoices to my customers in pdf and xlm files and thanks to your sharing I am done! Regards! string filePath = dgvfiledown.DataKeys[gvrow.RowIndex].Value.ToString(); i got an error in this line . "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index" Please help me to the post 31 ... My best visit.....best website..its very useful for new programmer...as learner. Thanks a lot to Developer. hi suresh.... i have some problem to use this code if you some kind of information how to use this code in layered architecture. you know layered work very different..plz tell us some idea .... hanks very well, thank you. really appreciate it. we use this code than files not save in file folder in project and saved to datbase correctley plz help me Hi sir, I need help from your side. If I am upload my resume means to specific fields to fetch the textbox control. for eg: email, firstname, lastname, role, mobile no to get values for to upload the resume to automatically to bind the text box control. I need coding path and examples please help me sir great brother your coding always help me..thanks a lot.... Hello sir give me some application of wcf Thanks a lot .......this article was very helpful thank u very much Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index i'm getting error like this..please help me Sir, I have error in downloading the file after uploading. Pls help me with this. Sir,i want to scan the virus when uploading the files .. pls tell c# code..pls help me sir.. if i dont want to use grid view then can i download multiple files? Hi. Great post. Works a charm. I was however wondering if it is possible to save files to e.g. Dropbox or Azure cloud or Amazon or any other hosting using your steps? Or how about FTP? How would you incorporate a username and password? how to download sever side file through the gridview in asp.net Server.MapPath is used to translate a virtual path (web path). I want to upload file in different drive example D:/UploadFolder/ its physical path. is there any way to upload and download file from physical path not from virtual path Thank you very nice article what should be the value of date,size & type in parameters ?? Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index i'm getting error like this..please help me Amazing code thnx for this....:) Hi, very nice code, I have an issue with gvDetails and FileUpload1 .. error /// The name 'gvDetails' does not exist in the current context any help Thanks dude...ITS WRORKING How To Load File Automatically into File Up loader. I have requirement , I have asp page with file up-loader and button name "upload"...with out using the browse ,i want load some default file in file up-loader ,suppose , I have folder in c:\serverfloder and i have image "image1.jpg" in that ..when user request 1 time ,i want to automatically load the file into file up-loader ..based user requirement we give chance the change the file file ....i don't want to restrict the user. Suresh sir ...Please help me ..... my question is how to view a uploaded document without downloading that doc...... just i need to view that doc in page itself do we have same thing for java ? How to delete the uploaded document sir plz help me. how to count length of character in custom editor using asp.net plz solve my problem sir.. All Nice aritcal .......it is very useful to me ..Thanks.. good article sir ji i have one problem when i use download code getting some unable to valid expression c# hi,once i submit m resume ,it need to be saved in a folder with the name of the user along with time.can u help me in this regard Hi suresh sir ! I'm shivangi. Your articles are really good n helpful. These articles helped me a lot in my project . How to delete a file which has upload from datagrid? Please help Good Post Thanks Bhaskar. I create word doc dynamicaly.how to save with proper naming? I want to do same Thing in Windows application how can i do pls reply.... Thanks My twitter account did not registered api twitter .com/oauth/request_token. Can i update my account. But i don't know my callback url. Very helpful article. Only I have a problem. I used your code and my page shows all images, looks good! But except imagges it shows Thumb.db link. When I click on the link - there is nothing. There is no such db in the directory. How can I get rid of showing this link? Please, advise. this code is not work in internet explorer hi..which tool u have used for live demo.. thankyou so much......... very nice app........ thank you code is running without any error, but not getting the download option,can any one help me pz Hi Suresh , Everything is Working Fine , But i want to download file directly to "D:\\Project" without asking Open save dialogue . Hi Suresh, This is working fine with fileupload control and save file in a desired location. I am asking one thing, that i need to save file that came from my database in a desired location as above. can you please suggest me without fileupload control. Good website for fresher as well as experienced..!! Keep updating Bro!! Could not complete the operation due to error c00ce514. Dim gvrow As GridViewRow = TryCast(lnkbtn.NamingContainer, GridViewRow) Response.TransmitFile(Server.MapPath(filePath)) Why "GridViewRow" and Response.TransmitFile undifined in asp.net 2003 / visual studio 2003...??? Hi Suresh, I am using below code for download. String FileName = "FileName.txt"; String FilePath = "C:/...."; //Replace this System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "text/plain"; response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";"); response.TransmitFile(FilePath); response.Flush(); response.End(); Upon click of the download button, i am getting Open/Save/Cancel dialog box, but i still able to click download button once again, without answering the dialog box. I wanted to open Model Dialog box. Please guide me in this. Thanks Priya. Hi Suresh, My scenerio is little bit different, I want to save and download the asp.net website in html format with running it on browser just like searched a lots but dint get any solution.Kindly tell me if you have any answer. Regards If its inside the Update Panel then ? Hi suresh, Article is very nice. But one error is display...String or binary data would be truncated. The statement has been terminated. You are my god dear sir in behind code c# with asp.net it 's ok but in vb.net when I try upload it show me object reference not instance an object could you show me? Can u teach file upload and download from remote server using FTP? How can you delete the file and the line of the gridview at the same time good Thank U So Much..... It is Very Much Useful For Me....! Can we hide the (download) save pop up . and gives physical path like ("E:\ABC") folder name ? If know please tell me . thanks in advance. thank you very much for this tutorial. thanks very short n valuable code hi this is jyoti. i don't want to use fileupload control . i retrive value from the database in gridview then i want to to download
http://www.aspdotnet-suresh.com/2012/02/saveupload-files-in-folder-and-download.html
CC-MAIN-2018-13
refinedweb
1,983
77.13
/* customer.h */ typedef struct customer { int id; char *name; int n_orders; order_t *orders; } customer_t; int customer_new (customer_t **); int customer_read (id_t const *, customer_t **); int customer_write (customer_t const *); int customer_delete (customer_t *); int customer_num_orders (customer_t *, int *);Set/gets and accessors are not necessarily an improvement, as claimed above. They are considered code-bloat, anti-YagNi, and a violation of OnceAndOnlyOnce because they are repeating DatabaseVerbs in interfaces for each entity instead of InterfaceFactoring to a single spot. You see a pattern like this for each entity where X is the entity: int X_new (X_t **); int X_read (X_t const *, X_t **); int X_write (X_t const *); int X_delete (X_t *); int X_num_orders (X_t *, int *);(Not that I'd ever write an order-processing system in C anymore! This is for performance-critical and low-level stuff only.) The underscores are being used to emulate a dumbfounded namespace or module, since C does not have a proper module system. In a modular language one could abandon the customer_underscore_hideous_C_crap and put it in a module, or use overloading so that customer is a parameter in to the function, and other functions can accept other parameters (structs) such as notcustomer. See also IncludeFileParametricPolymorphism.. I find myself often refactoring source files into smaller files as I listen to the program, and this feels rather like refactoring classes in a higher-level language. Doing this in C becomes a bit labour-intensive when there's a lot of inheritance, but plenty of problems can be solved reasonably well without polymorphism. -- MartinPool Ideally some kind of meta-programming should be used such that you don't have to keep repeating that. Or, use a database or DataDictionary. I am not sure what OO is fixing in your scenario. One could do the same thing with procedural map arrays also (which C does not natively support), I would note. Further, if the schema is already in the database, then echoing it in code is perhaps a violation of OnceAndOnlyOnce anyhow. -- top And repeating the customer_prefix with an underscore, in addition to sending customer in as a parameter, also violates OnceAndOnlyOnce and can be solved by using modules which the braindead CeeLanguage doesn't support... and if using several of the same algorithms over and over again for different types then one can make use of a ParametricPolymorphism pattern (without needing OOP as commonly misunderstood). foo(customer, 'bar');Not this kludgy C stuff: customer_foo(customer, 'bar');The only problem that I see with the idea that the schema can be just in the database is that eventually the programming language is going to have to access the database columns and have some knowledge about the invidual column names... for example thishash["customerid"]. How did we know for sure that the "customerid" exists in the database in any programming language, without having some knowledge about the database schema? One would have to query the database schema to verify that customerid first exists and loop through it, violating OnceAndOnlyOnce... unless it was built into the language that you had a DatabaseType that you could declare and use natively. If thishash["customerid"] is ever assigned, it could first check the database schema to verify the "customerid" column really exists - but... again this is crude and you are still violating OnceAndOnlyOnce since you are declaring "customerid" in the program and in the DB. I was thinking about automatically mapping an array or dictionary or hash to the DB and realized that eventually you have to have some knowledge about the columns to know what to put in the hash as the dict items or array indexes... and eventually you have to violate OnceAndOnlyOnce (unless some special DB is built into your language natively, which would be nice but impractical in the case of SQL products that we can actually use today). So I'd say that trying as hard as we can to not violate OnceAndOnlyOnce is a good practice... reducing duplication as much as we can... but I think that as with other Patterns, it is never a perfect discipline. You could loop through the schema columns and map them at run time... but again you'd have to eventually query the columns and duplicate the schema at some point: assigning or accessing thishash['thecolumnname'] is duplicating the schema. If that column name ever changes then you have to change things twice - in the schema and in the code. At some point, you must have knowledge about "thecolumnname"... at design time? I think so... so the only idealistic way to solve the problem would be to embed the database into the program itself as a native type...? I'm not sure that just referencing something is a violation of OnceAndOnlyOnce. That's almost like saying that a "print(...)" statement is a violation because it repeats a reference to printing over and over. If 80 nodes all reference node X, they will repeat some kind of identifier to X somewhere somehow. The only way I see out of that is some kind of context/locational association, which has other drawbacks. I meant that print_print(print, 'the text');would be a waste, compared to print('the text');For example if you had a namespace or module of "print" you would declare it as "using print" or "uses print" instead of rehacking it into underscore and parameter nonsense like: print_print('the text');Sometimes this is hard to avoid if you reference a namespace like: printunit.out()But if we can avoid it like using printunit; // or uses printunit; out()I think it makes code clearer and simpler. But often short verbs tend to risk or cause naming conflicts. But repeating the name-space over and over can be cluttery: printunit::out(foo);Ideally, one could alias name-spaces: use printunit; ... p = printunit; // name-space alias p::out(foo);One may argue that OOP reduces the need for such. This is true to some extent, but it does not necessarily eliminate it because name-space management is useful even at the class level. OOP can also create resource overhead because the interpreter/compiler has to allocate an object "p" for a mere function/method call. Plus, it does not give you the option to call "out()" without an object reference (barring some odd language shortcut tricks). You always have to use an object reference (dot notation). Name-space references ("foo::x") are optional in most languages. Thus, it's a wash in my opinion (WaterbedTheory in action). --top ComponentPascal has unit aliases and they are extremely useful. QompLanguage will have them too. The problem with OOP as a namespace is that you have to create the instance and I know an instance is not needed all the time (just like humans do not have new baby instances (childs and sons) each time we need to get something done). Especially in languages like Delphi, using a class as a fake namespace dangerous and introduces more bugs into the program due to dangling objects that have no garbage collection.. and it bloats up the code with more and more Free/Create code. NeedlessRepetition of Free and Create in the code. OOP does not allow one to stick just regular old commands into the namespace... the whole lifecycle of the class must be designed, created, freed.. which is overly complex for lots of solutions that just need a namespace (or unit alias). Laughingly explained in AntiCreation. Namespaces can have classes inside them, too. --MopMind? Proposal for FreePascal/DelphiLanguage: uses u := someunit; begin u.callfunction(); end;Proposal for QompLanguage use u = someunit; b u.callfunction; e;
http://c2.com/cgi/wiki?ModularProgramming
CC-MAIN-2014-41
refinedweb
1,260
60.85
- OSI-Approved Open Source (561) - GNU General Public License version 2.0 (275) - GNU Library or Lesser General Public License version 2.0 (86) - GNU General Public License version 3.0 (63) - Mozilla Public License 1.1 (60) - (9) - Windows (605) - Linux (556) - Mac (522) - Grouping and Descriptive Categories (343) - Android (238) - Modern (119) - BSD (46) Browsers Software - Plugins and add-ons - Hot topics in Browsers Softwareckfinder qr code qr code vb6 kcfinder qr code activex jsunit qr code code with logo qr code dll js tools javascript JSPackaging JSPackaging is a JavaScript framework that provides simple directives for defining, loading & importing uniquely named packages of JavaScript modules. UPDATE: This project now exists as Ajile at & weekly downloads JSS (Javascript Style Sheets) JSS is an extension to CSS that allows for multiple inheritance of CSS rules. Base classes, tags and tag identifiers can be defined and then inerited from.1 weekly downloads JavaScripTools JavaScript utilities, including input masks and data parsers4 weekly downloads JavaScript Collections JavaScript Vector and Matrix objects acts as a collection of objects or elements. Has methods similar to Java, C++ Vector. The Matrix is a 2D Vector.1 weekly downloads JavaScript Namespace Initiative The creation of a cross-browser Namespace in the JavaScript language. This includes new data types with more powerful methods, and new classes such as a W3C compliant XML DOM API, and WebControls. New classes and namespaces can be created at any time.1 weekly downloads JavaScript QR Code Make QR Codes in JavaScript17 weekly downloads JavaScript Validation Framework JSValidation is a framework which focusing on validation in various web applications. Since there are many web frameworks involves such feature, but jsvalidation can be suit for any web application even in ASP, PHP and other languages. JavaScript demos Useful scripts based on Prototype weekly downloads JavaScriptDB Javascript DB, es un minimotor de base de datos, escrito en Javascript, usando sentencias SQL todo ello en JS.2 weekly downloads JavaScripts for iMacro Useful utilities written in JavaScript for iMacro. iMacro is a free plug-in for Firefox that provides a simple way of recording and running macros to automate web browsing, scraping and form-filling.1 Remote Socket Allowed browser to have live communication without designing a complicated database structure and yet provides flexibilities to the needs.1 weekly downloads Javascript plug-in modules Javascript tools is a set of Object oriented pluggable modules, which include: Data Validation (forms), Debugging, Error trapping, XML DOM and XSLT manipulation.1 weekly downloads Javascrit web form validator.1 weekly downloads Jex Jex (short for 'objects') is an ultra-lightwieght ecmascript library framework for embedded and browser applications Kaazing Gateway Kaazing Gateway is an open source, full-duplex streaming WebSocket Server, and is the world's first enterprise-ready implementation of the HTML 5 WebSockets and Server-Sent Events specification—a standards-based alternative to Comet and Ajax. KapiRegnumHelper This is an AddOn to FireFox for KapiRegnum Germany from upjers. It is written in JavaScript and delivers some neat features for the Browsergame which make life much easier and helps to speed up some reoccuring tasks.4 weekly downloads Kitsune Firefox Extension Kitsune is a Firefox extension which enables users to input Japanese in Firefox without external Japanse IME..
https://sourceforge.net/directory/internet/www/browsers/language%3Ajavascript/?sort=name&page=9
CC-MAIN-2016-44
refinedweb
541
50.57
and Java (still?) Syntactical differences aside, what's wrong with just overriding equals()? IMHO, it's a lot simpler to limit == to reference comparisons and have equals() do logical comparisons. I know it's slightly diff. from the first since the first is a check for equality and the second is an assignment of reference) Originally posted by Robert Paris:Lol. Sorry guys. Jos, no I knew YOU knew what I was talking about but since you said: still? I thought you weren't 100% sure so I wanted to see if anyone else knew (and to be sure they knew what I was talking about). Originally posted by Jos Horsmeier: 'aspects' Originally posted by Jim Yingst: But as you see, the basic "flaw" already exists in Java. Originally posted by Robert Paris: oh, one other plus of the autoboxing keyword? All old Java code will still work 100% as written! While the current idea for autoboxing would make this previously written code, to not work: public class Test { public void foo(Integer fooey){} public void foo(int fooey){} } With boxing, another rule is added... you can never create a method that takes a primitive if the class already has a method with the same name that takes an Object. Robert - old working code will continue to work under the proposed autoboxing scheme (without the need for a keyword). It's only when you add new code to it that you have the opportunity to make the old code not work, if you're not careful. Which is to say, adding bad code is the problem, not adding autoboxing. The problem occurs if in a world with boxing you have a method that boxes and then later on you add a method with the primitive. Suddenly all the users of your code unknowingly switch to the primitive version which could introduce strange errors into their code. I mean, aren't they responsible for understanding how the existing code works before they change it? Originally posted by Robert Paris: We have a class with two methods which in our non-boxing current JRE/JVM works with no ambiguities: public int add(Integer num); public int add(int num); In an auto-boxing JVM, with NO autobox indicator, how will the JVM know which method to use? Well, as Tom pointed out, it would switch people who were previously getting their code sent to one method to the other:
http://www.coderanch.com/t/370606/java/java/object-override-equals
CC-MAIN-2015-27
refinedweb
407
68.5
: ===== - XInclude at the SAX level (libSRVG) - fix the C code prototype to bring back doc/libxml-undocumented.txt to a reasonable level - Computation of base when HTTP redirect occurs, might affect HTTP interfaces. - Computation of base in XInclude. Relativization of URIs. - listing all attributes in a node. - Better checking of external parsed entities TAG 1234 - Go through erratas and do the cleanup. ... started ... - jamesh suggestion: SAX like functions to save a document ie. call a function to open a new element with given attributes, write character data, close last element, etc + inversted SAX, initial patch in April 2002 archives. - htmlParseDoc has parameter encoding which is not used. Function htmlCreateDocParserCtxt ignore it. - fix realloc() usage. - Stricten the UTF8 conformance (Martin Duerst):. The bad files are in. - xml:id normalized value TODO: ===== - move all string manipulation functions (xmlStrdup, xmlStrlen, etc.) to global.c. Bjorn noted that the following files depends on parser.o solely because of these string functions: entities.o, global.o, hash.o, tree.o, xmlIO.o, and xpath.o. - Optimization of tag strings allocation ? - maintain coherency of namespace when doing cut'n paste operations => the functions are coded, but need testing - function to rebuild the ID table - functions to rebuild the DTD hash tables (after DTD changes). EXTENSIONS: =========== - Tools to produce man pages from the SGML docs. - Add Xpointer recognition/API - Add Xlink recognition/API => started adding an xlink.[ch] with a unified API for XML and HTML. it's crap :-( - Implement XSchemas => Really need to be done
http://opensource.apple.com/source/libxml2/libxml2-21.3/libxml2/TODO?txt
CC-MAIN-2014-52
refinedweb
249
61.22
Issue I have a LSTM model trained on text content. And now I want to use that model to generate some sentences. But instead of always picking the best option, i want it to select from for example the top 3, so that it can produce different sentences with the same input, because now I get the same answer for almost every input. How do i modify this code so that is possible, I know I need to remove the np.argmax but i don’t know how to the return the index of the top 3 highest values. Current code: def prediction(seed_text, next_words): for _ in range(next_words): token_list = tokenizer.texts_to_sequences([seed_text])[0] token_list = pad_sequences([token_list], maxlen=max_seq_length-1, padding='pre') predicted = np.argmax(model.predict(token_list, verbose=0), axis=-1) ouput_word = "" for word, index in tokenizer.word_index.items(): if index == predicted: output_word = word break seed_text += ' '+output_word return seed_text Solution np.argsort will give you the indices of the items in an array in the order that sorts them small to large: Here’s an example using argsort. Note that the one with the lowest prediction (index 2, "c" with the predicted value of 0.05) is left out of what is printed. import numpy as np word_index = {'a': 0, 'b': 1, 'c': 2, 'd': 3} predictions = np.array([0.1, 0.7, 0.05, 0.15]) # add negative to sort large to small; slice to select just up to 3rd index top_3 = np.argsort(-predictions)[:3] for word, index in word_index.items(): if index in top_3: print(word) #> a #> b #> d This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0
https://errorsfixing.com/get-top-3-prediction-of-lstm-instead-of-only-the-top/
CC-MAIN-2022-33
refinedweb
288
65.93
Actually, maybe each Django project needs to store some custom bunch of project specified settings. For doing this we can just separate place where we storing them. And move its to another Python module (so not use DJANGO_SETTINGS_MODULE for this purpose). After we anyway will load these custom settings, like: from cfg.appconfig import * It’s mainly okay. But what to do, when customer will need to fast change just one setting from the cfg.appconfig? In this case, ask customer’s request to dev-team, setup new issue for this case, create new branch by dev, fix setting value, commit changes, push the branch to repo, ask lead to check changes and finally lead will merge fixes to the master and deploy its to production. Not so easy? Huh First idea is simple. Let store these settings in database and give access to the superusers do all necessary changes from the UI. And, yeah, why not use some validators to sure that superuser entered proper values in UI. Also, it’s more better to have simple interface for reading these settings and then updating its values from the code. And finally, more better to read settings from database only after they changed or invalidated cause of time and other time just read them from cache. Really, why we need to read settings each time per request? Welcome django-setman, simple reusable app that adds ability to store custom settings in database and then slightly use its in code. All projects settings would be stored in setman.Settings model as JSON dump. It’s easy. And mainly we don’t need to know these details cause of next. A simple interface for reading and storing any custom settings. With support all values from django.conf.settings instance. So, if earlier you needed to import Django’s settings as usual: from django.conf import settings Now, to use database settings, you’ll need to use next statement instead: from setman import settings And that’s all. All other actions same. Saying you need to check list of project admins or managers (or any other global project setting). Just write: from setman import settings def example(request): admins = settings.ADMINS managers = settings.MANAGERS ... And, when you need to read some value for custom setting, you’ll write: from setman import settings def example(request): bonus_score = settings.BONUS_SCORE ... And if you need to update value for custom setting, you just used .save() method: from setman import settings def example(request): if request.method == 'POST': settings.BONUS_SCORE = request.POST.get('bonus_score') settings.save() That’s all! django-setman supports caching settings to reduce number of database queries. So, all you need to get this support, just setup CACHE_BACKEND in global project settings. Okay, we hope that right now, all seems clear for you. But maybe, you’ve already interested how some settings being custom project settings. The answer is with help of configuration definition file. It’s simple text file that next read by ConfigParser library, that uses next format: [SETTING_NAME] type = (boolean|choice|decimal|float|int|string) default = <default> label = Setting help_text = Short description about setting. validators = path.to.validator By default, this file should be placed in same directory where DJANGO_SETTINGS_MODULE located, but you can customize things by changing SETMAN_SETTINGS_FILE value in your project settings. And, don’t worry if you haven’t settings.cfg and you’ve already installed setman, all will work fine and setman just sends all errors to the logger. And don’t raise any errors when configuration definition file doesn’t exist or cannot parse. But, what to do if you want to add some predefined settings to your reusable app and add ability of further users to change them? It’s no problem at all too, cause we have support for app settings as well as project settings. But with some restrictions. First of all, on naming. By default, it’s good to have all configuration definition files named as settings.cfg, but what to do if you already have customized SETMAN_SETTINGS_FILE? The answer is starting to use SETMAN_SETTINGS_FILES, which should be a simple key-value tuple, list or dict where key is short app name, used by Django and value is path to settings file. If this path isn’t absolute we relate it with app directory as do for the project settings file as well. Next, all attributes for app settings (except type) should be updated in project settings, in next way: app/settings.cfg [SETTING_NAME] type = (boolean|choice|decimal|float|int|string) default = <default> label = Setting settings.cfg [app.SETTING_NAME] default = <new_default> label = New Setting validators = project.app.validators.setting_validator And the main feature of setman is simple UI for editing all custom project settings. It could be well configured for use with project styles or with standard Django admin styles. The most easy solution is use Django admin for editting settings, in that case you don’t need to change anything in your project, just include admin.urls at your root URLConf module. And that’s all. For enabling UI, you’ll need to include setman urls in your root URLConf module: urlpatterns = patterns('', ... (r'^setman/', include('setman.urls')), ... ) Next, you need to setup who permitted to access “Edit Settings” page from UI. By default, only superusers can have access to this page. But you can customize things providing SETMAN_AUTH_PERMITTED trigger in project settings: SETMAN_AUTH_PERMITTED = lambda user: user.is_staff Make sure, that is lambda or callable object that would be called with one argument. This argument would be standard user instance from request.user var, so you can allow to edit settings for any logged in user with next statement: SETMAN_AUTH_PERMITTED = lambda user: user And finally, feel free to run development server and go to the setman UI. In test project it looks next. For more information check next links,
http://pythonhosted.org/django-setman/
CC-MAIN-2013-20
refinedweb
978
66.03
instead ofand _WIN32_WINNT defined properly. You can defined these values in your stdafx.h. #include <atltheme.h>" to your stdafx.h file. This should be placed after all the other ATL includes. CColorButtonmakes heavy use of helper types from ATL. You will need to make sure that "atltypes.h" and "atlgdi.h" are being included in stdafx.h. REFLECT_NOTIFICATIONS ()". OnInitDialogfor the dialog, add a line to subclass the control. It is important that is it subclassed and not just assigned a window handle._DROPDOWN is sent to the parent window prior to the picker window being displayed. CPN_CLOSEUP is sent to the parent window after the picker window has been closed. CPN_SELENDOK is sent to the parent window after the picker window has been closed with a valid selection and not canceled. CPN_SELENDCANCEL is sent to the parent window after the picker window has been closed but canceled by the user. General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/wtl/wtlcolorbutton.aspx
crawl-002
refinedweb
158
61.22
Problem with exe compiled in CS5.5, good in CS5.0rahulkumbhar Jul 10, 2012 2:08 PM I have a flash application with ActionScript 3.0. I use to compile the code with CS5.0, and it was all perfect. But, now I upgraded to CS5.5, and it started giving problems. When I compile the fla file to exe, and run it, it runs perfect for some time, then it starts getting heavy, using lots of CPU cycles, and eventually the computer hangs. If I again compile the same code in CS5.0, it runs perfect again. Can anybody help me to solve this issue. 1. Re: Problem with exe compiled in CS5.5, good in CS5.0kglad Jul 10, 2012 5:00 PM (in response to rahulkumbhar) Memory Tracking The code below is adapted from Damian Connolly's code at divillysausages.com. The MT class reports frame rate, memory consumption and what objects are still in memory. Using it is easy. Initialize it from the document class MT.init(this,reportFrequency); where this references your document class (i.e., the main timeline) and reportFrequency is an integer. The main timeline reference is used to compute the realized frame rate and reportFrequency is the frequency in seconds that you want trace output reporting the frame rate and amount of memory consumed by your flash game. If you don't want any frame rate/memory reporting pass 0 (or anything less). You can still use the memory tracker part of this class. To track objects you create in your game, use: MT.track(whatever_object,any_detail); where the first parameter is the object you want to track (to see if it is ever removed from memory) and the second parameter is anything you want (typically a string that supplies details about what, where and/or when you started tracking that object). When you want a report of whether your tracked objects still exist in memory, use: MT.report(); I'll show sample code using MT after discussing details of the MT class in the MT class comments. It is not necessary that you understand the class to use it but it is a good idea to check how the Dictionary class is used to store weak references to all the objects passed to MT.track(). Similar to the observer effect in physics, the mere fact that we are measuring the frame rate and/or memory and/or tracking memory, changes the frame rate and memory of the game. However, the effect of measurement should be minimal if the trace output is relatively infrequent. In addition, the absolute numbers are usually not important. It is the change in frame rate and/or memory use over time that is important and for that, this class works well. This class does not allow more than once per second trace output to help minimize spuriously low frame rate reports caused by frequent use of trace. And, you can eliminate trace output as a confounder of frame rate determination by using a textfield instead of trace output. com.kglad.MT package com.kglad{ import flash.display.MovieClip; import flash.events.Event; import flash.utils.getTimer; import flash.system.System; import flash.utils.Dictionary; // adapted from @author Damian Connolly // public class MT { // Used to calculate the real frame rate private static var startTime:int=getTimer(); // Used to generate trace output intermittantly private static var traceN:int=0; // Megabyte constant to convert from bytes to megabytes. private static const MB:int=1024*1024; private static var mc:MovieClip; // d is used to store weak references to objects that you want to track. // It is the essential object used to memory track in this class. // The true parameter used in the constructor designates that // all references are weak. That is, the dictionary reference itself // won't prohibit the object from being gc'd. private static var d:Dictionary = new Dictionary(true); // Used to trigger a report on the tracked objects private static var reportBool:Boolean; // Used to (help) ensure gc takes place private static var gcN:int; // This is the variable that will store the reportFrequency value that // you pass. private static var freq:int; // A constructor is not needed public function MT() { } // traceF() is the listener function for an Enter.ENTER_FRAME event. If // the game is running at its maximum frame rate (=stage.frameRate), // traceF() will be called stage.frameRate times per second. private static function traceF(e:Event):void { traceN++; // This conditional ensures trace output occurs no more frequently // than every freq seconds. If the game is running at // stage.frameRate, output will occur at approximately freq // seconds. if (traceN%(freq*mc.stage.frameRate)==0) { // This is used to (try and) force gc. gcN = 0; forceGC(); trace("FPS:",int(traceN*1000/(getTimer()-startTime)),"||","Memory Use:",int(100*System.totalMemory/MB)/100," MB"); traceN=0; startTime=getTimer(); } } // Called just prior to the above trace() and called just prior to a // memory report. When called just prior to a memory report, reportBool // is assigned true. private static function forceGC():void { // The first call to System.gc() marks items that are available // for gc. The second should sweep them and the third is for good // luck because you can't count on anything being predictably // gc'd when you think it should be. mc.addEventListener(Event.ENTER_FRAME,gcF,false,0,true); gcN = 0; } private static function gcF(e:Event):void { // System.gc() initiates the gc process during testing only. It // does not work outside the test environment. So, if you are using this class to test a game that is installed on a mobile device, System.gc() will not clear memory of objects ready to be g System.gc(); gcN++; // 3 System.gc() statements is usually enough to clear memory of // objects that can be cleared from memory. if (gcN>2) { mc.removeEventListener(Event.ENTER_FRAME,gcF,false); // Here's where reportBool being true triggers the memory if(reportBool){ reportBool = false; reportF(); } } } // Memory report. All objects passed to d in the track() function, // if they still exist, will be displayed by the trace statement along // with the additional information you passed to track() private static function reportF():void{ trace("** MEMORY REPORT AT:",int(getTimer()/1000)); for(var obj:* in d){ trace(obj,"exists",d[obj]); } } public static function init(_mc:MovieClip,_freq:int=0):void{ mc=_mc; freq=_freq; if(freq>0){ mc.addEventListener(Event.ENTER_FRAME,traceF,false,0,true); } } // This the function you use to pass objects you want tracked. public static function track(obj:*,detail:*=null):void{ d[obj] = detail; } // This is the function that triggers a memory report. public static function report():void{ reportBool = true; forceGC(); } } } 2. Re: Problem with exe compiled in CS5.5, good in CS5.0rahulkumbhar Jul 11, 2012 1:25 PM (in response to kglad) Hi kglad, thank for the reply. I understand you are trying to see if there is any memory leaks in my code. Let me explain you the scenario. I have a this flash application running on one computer. There is another computer which sends some data over TCP/IP, i.e. I am using sockets in my flash application to read those values and accordingly change the looks of some icons, or display a message on my flash. I create all the objects at the start. And I have to keep this application running for the whole day. Whereever, I run the other application which sends data to my flash, they get connected and work accordingly. I am just concerned, why is it, that the exe compiled in CS5.0 works like charm, but gets slower as the time passes with the exe compiled in CS5.5. Are there any publish settings I need to change. Or is there any library that CS5.5 uses different than CS5.0 which is causing this slowdown. I would still try to use your program to check any memory leak. But as to what I understand memory leaks could be caused by creating new objects and not freeing the memory after the use of those objects is finished. But here, I just create the objects at the start, and keep running the application the day long. Not sure where the problem is. Thank you 3. Re: Problem with exe compiled in CS5.5, good in CS5.0kglad Jul 11, 2012 9:36 PM (in response to rahulkumbhar) there are differences in how swfs publishes by different versions of flash pro handle gc and there are differences in gc handling (and performance) by different versions of flash player. there are no differences in publish settings.
https://forums.adobe.com/thread/1034801
CC-MAIN-2018-34
refinedweb
1,432
66.64
- map device memory into user space #include <sys/types.h> #include <sys/mman.h> #include <sys/param.h> #include <sys/vm.h> #include <sys/ddi.h> #include <sys/sunddi.h> int prefixsegmap(dev_t dev, off_t off, struct as *asp, caddr_t *addrp, off_t len, unsigned int prot, unsigned int maxprot, unsigned int flags, cred_t *cred_p); Architecture independent level 2 (DKI only). Device whose memory is to be mapped. Offset within device memory at which mapping begins. Pointer to the address space into which the device memory should be mapped. Pointer to the address in the address space to which the device memory should be mapped. Length (in bytes) of the memory to be mapped. A bit field that specifies the protections. Possible settings. Possible values are (other bits may be set): Changes should be shared. Changes are private. Pointer to the user credentials structure. The segmap() entry point is an optional routine for character drivers that support memory mapping. The mmap(2) systemmap_setup(9F) is used as a default. A driver for a memory-mapped device would provide a segmap() entry point if it: needs to maintain a separate context for each user mapping. See devmap_setup(9F) for details. needs to assign device access attributes to the user mapping. The responsibilities of a segmap() entry point are: Verify that the range, defined by offset and len, to be mapped is valid for the device. Typically, this task is performed by calling the devmap(9E) entry point. Note that if you are using ddi_devmap_segmap(9F) or devmap_setup(9F) to set up the mapping, it will call your devmap(9E) entry point for you to validate the range to be mapped. Assign device access attributes to the mapping. See ddi_devmap_segmap(9F), and ddi_device_acc_attr(9S) for details. Set up device contexts for the user mapping if your device requires context switching. See devmap_setup(9F) for details. Perform the mapping with ddi_devmap_segmap(9F), or devmap_setup(9F) and return the status if it fails. The segmap() routine should return 0 if the driver is successful in performing the memory map of its device address space into the specified address space. The segmap() must return an error number on failure. For example, valid error numbers would be ENXIO if the offset/length pair specified exceeds the limits of the device memory, or EINVAL if the driver detects an invalid type of mapping attempted. If one of the mapping routines ddi_devmap_segmap() or devmap_setup()fails, you must return the error number returned by the respective routine. mmap(2), devmap(9E), devmap_setup(9F), ddi_devmap_segmap(9F), ddi_device_acc_attr(9S)
http://docs.oracle.com/cd/E18752_01/html/816-5179/segmap-9e.html
CC-MAIN-2014-52
refinedweb
427
59.7
An independent implementation of the CSS layout algorithm. Colosseum An independent implementation of the CSS layout algorithm. This implementation is completely standalone - it isn’t dependent on a browser, and can be run over any box-like set of objects that need to be laid out on a page (either physical or virtual) At present, the implementation is partial; only portions of the box and flexbox section of the specification are defined: Quickstart In your virtualenv, install Colosseum: $ pip install colosseum Colosseum provides a CSS class that allows you to define CSS properties, and apply them can be applied to any DOM-like tree of objects. There is no required base class; Colosseum will duck-type any object providing the required API. The simplest possible DOM node is the following: from colosseum import Layout class MyDOMNode: def __init__(self, style): self.parent = None self.children = [] self.layout = Layout(self) self.style = style.bind(self) def add(self, child): self.children.append(child) child.parent = self That is, a node must provide: - a parent attribute, declaring the parent in the DOM tree; the root of the DOM tree has a parent of None. - a children attribute, containing the list of DOM child nodes. - a layout attribute, for storing the final position of the node. - a style attribute - generally a CSS declaration, bound to the node. With that a compliant DOM node definition, you can then and query the layout that results: >>> from colosseum import CSS, ROW, COLUMN >>> node = MyDOMNode(style=CSS(width=1000, height=1000, flex_direction=ROW)) >>> node.add(MyDOMNode(style=CSS(width=100, height=200))) >>> node.add(MyDOMNode(style=CSS(width=300, height=150))) >>> node.style.apply() >>> layout = node.layout >>> print(node.layout) <Layout (1000x1000 @ 0,0)> >>> layout.width 1000 >>> layout.height 1000 >>> layout.top 0 >>> layout.left 0 >>> for child in node.children: ... print(child.layout) <Layout (100x200 @ 0,0)> <Layout (300x150 @ 100,0)> Calling node.style.apply() forces the box model to be evaluated. Once evaluated, the layout will be cached. Modifying any CSS property on a node will mark the layout as dirty, and calling apply() again will cause the layout to be re-evaluated. For example, if we switch the outer node to be a “column” flex box, rather than a “row” flex box, you’ll see the coordinates of the child boxes update to reflect a vertical, rather than horizontal layout: >>> node.style.flex_direction = COLUMN >>> node.style.apply() >>> print(node.layout) <Layout (1000x1000 @ 0,0)> >>> for child in node.children: ... print(child.layout) <Layout (100x200 @ 0,0)> <Layout (300x150 @ 0,200)> If the layout is not dirty, the layout will not be recomputed. Style attributes can also be set in bulk, using the set() method on the style attribute: >>> node.style.set(width=1500, height=800) >>> node.style.apply() >>> print(node.layout) <Layout (1500x800 @ 0,0)> Style attributes can also be removed by deleting the attribute on the style attribute. The value of the property will revert to the default: >>> node.style.set(margin_top=10, margin_left=20) >>> node.style.apply() >>> print(node.layout) <Layout (1500x800 @ 20,10)> >>> del(node.style.margin_left) >>> print(node.style.margin_left) 0 >>> print(node.layout) <Layout (1500x800 @ 0,10)> Layout values are given relative to their parent node. If you want to know the absolute position of a node on the display canvas, you can request the origin attribute of the layout. This will give you the point on the canvas from which all the node’s attributes are measured. You can also request the absolute attribute of the layout, which will give you the position of the element on the entire canvas: >>> node.style.set(margin_top=10, margin_left=20) >>> node.style.apply() >>> print(node.layout) <Layout (1500x800 @ 20,10)> >>> for child in node.children: ... print(child.layout) <Layout (100x200 @ 0,0)> <Layout (300x150 @ 0,200)> >>> print(node.style.layout.origin) <Point (0,0)> >>> for child in node.children: ... print(child.style.layout.origin) <Point (20,10)> <Point (20,10)> >>> print(node.style.layout.absolute) <Point (20,10)> >>> for child in node.children: ... print(child.style.layout.absolute) <Point (20,10)> <Point (20,210)> Community Colosse.
https://pypi.org/project/colosseum/
CC-MAIN-2017-51
refinedweb
685
59.6
Implement this interface for your own strategies for printing log statements. More... #include <log4c/defs.h> #include <log4c/layout.h> #include <stdio.h> Go to the source code of this file. Implement this interface for your own strategies for printing log statements. Helper macro to define static appender types. log4c appender class log4c appender type class Attributes description: nameappender type name open append closes the appender Destructor for log4c_appender_t. Get a pointer to an existing appender. Constructor for log4c_appender_t. opens the appender. prints the appender on a stream sets the appender layout sets the appender type sets the appender user data Get a pointer to an existing appender type. Use this function to register an appender type with log4c. Once this is done you may refer to this type by name both programmatically and in the log4c configuration file. Example code fragment: free all appender types prints all the current registered appender types on a stream
http://log4c.sourceforge.net/appender_8h.html
CC-MAIN-2017-47
refinedweb
156
60.51
Hi, I've been experimenting with the checkstyle against a fairly large Java project. However, I've come across an error related to the 'redundant throws' check, and exceptions that are defined as nested classes: the plugin doesn't seem able to locate the information for the exception that's thrown - even though the exception that's thrown is on the same source path and class path as the rest of the code. I've compacted this right down into a simple Java project that illustrates the problem. The project consists of 2 Java files: /Projects/Test/src/test/Test1.java /Projects/Test/src/test/Test2.java The project compiles to: /Projects/Test/bin Here's the source for Test1.java: package test; import test.Test2.TestException1; import test.Test2.TestException2; public class Test1 { void doStuff1() throws TestException1 { throw new Test2().new TestException1(""); } void doStuff2() throws TestException2 { throw new TestException2(""); } } And here's the source for Test2.java: package test; public class Test2 { class TestException1 extends Exception { TestException1(String messg) { super(messg); } } static class TestException2 extends Exception { TestException2(String messg) { super(messg); } } } And here's my CheckStyle ant build file: When I run the ant script, I get the following result: <?xml version="1.0" encoding="UTF-8"?> My system: I'm building on a Windows2000 system, using Ant 1.5.1 and CheckStyle3.3. I'm using checkstyle by including its libraries in the lib directory of my Ant installation. Very useful tool by the way. The only problems that I've encountered so far have been concerning the 'redundant throws' rule. Regards, David Oleg Sukhodolsky 2004-03-29 Logged In: YES user_id=746148 The check unable to load class information for TestExceptionX classes. You should specify classpath for Checkstyle so thiese classes will be in it. David Whitmore 2004-03-29 Logged In: YES user_id=728478 I believe that the ant script that I'm using does specify the classpath - using the 'classpath' attribute of the 'checkstyle' element. I still get the above errors. Am I missing something? Oliver Burn 2004-03-29 Logged In: YES user_id=218824 Look at (the Checkstyle build.xml). You will see that in the "checkstyle.checkstyle" task we specify two classpaths. They are For the taskdef Inside the task. This is the classpath that Checkstyle uses to locate classes. This is the one you need to set. Lars Kühne 2004-03-30 Logged In: YES user_id=401384 Hmm... doesn't David do that? ... David, just to be sure: does the directory actually contain the classes, i.e. do you make sure you call javac before calling the checkstyle task? Checkstyle analyzes throws clauses by using reflection. My guess is that checkstyle does not generate the class name correctly, we probably try to load test.Test2.TestException1, not test.Test2$TestException1. David Whitmore 2004-03-30 Logged In: YES user_id=728478 Originally I was actually half-using Eclipse and half-using Ant to test this. However, I'm pretty sure that the directory /Projects/Test/bin did actually contain the classes. In order to make sure, I extended the Ant build file that I used to reproduce the test. Here it is: Running this, I still get the errors that I outlined earlier. One of the reasons why I'd originally thought that it was a nested class problem was due to the error messages: "Unable to get class information for TestException1." and "Unable to get class information for TestException2." Which suggest that the appropriate classes aren't being found (otherwise, it should surely say "Unable to get class information for Test2$TestException1." and "Unable to get class information for Test2$TestException2."?). Last time, I forgot to include the config file that I was using: /checkstyle_test/checkstyleconfig.xml Here it is: I'm using JDK 1.4.2_03. I think you'll be able to reproduce this on your own systems. Oleg Sukhodolsky 2004-04-05 Logged In: YES user_id=746148 Committed to CVS for 3.4
http://sourceforge.net/p/checkstyle/bugs/224/
CC-MAIN-2014-10
refinedweb
664
66.84
Pelican internals¶ This section describe how Pelican works internally. As you’ll see, it’s quite simple, but a bit of documentation doesn’t hurt. :) You can also find in the Some history about Pelican section an excerpt of a report the original author wrote with some software design information. Overall structure¶ What Pelican does is take a list of files and process them into some sort of output. Usually, the input files are reStructuredText and Markdown files, and the output is a blog, but both input and output can be anything you want. The logic is separated into different classes and concepts: - Writers are responsible for writing files: .html files, RSS feeds, and so on. Since those operations are commonly used, the object is created once and then passed to the generators. - Readers are used to read from various formats (HTML, Markdown and reStructuredText for now, but the system is extensible). Given a file, they return metadata (author, tags, category, etc.) and content (HTML-formatted). - Generators generate the different outputs. For instance, Pelican comes with ArticlesGeneratorand PageGenerator. Given a configuration, they can do whatever they want. Most of the time, it’s generating files from inputs. - Pelican also uses templates, so it’s easy to write your own theme. The syntax is Jinja2 and is very easy to learn, so don’t hesitate to jump in and build your own theme. How to implement a new reader?¶ Is there an awesome markup language you want to add to Pelican? Well, the only thing you have to do is to create a class with a read method that returns HTML content and some metadata. Take a look at the Markdown reader: class MarkdownReader(BaseReader): enabled = bool(Markdown) def read(self, source_path): """Parse content and metadata of markdown files""" text = pelican_open(source_path) md_extensions = {'markdown.extensions.meta': {}, 'markdown.extensions.codehilite': {}} md = Markdown(extensions=md_extensions.keys(), extension_configs=md_extensions) content = md.convert(text) metadata = {} for name, value in md.Meta.items(): name = name.lower() meta = self.process_metadata(name, value[0]) metadata[name] = meta return content, metadata Simple, isn’t it? If your new reader requires additional Python dependencies, then you should wrap their import statements in a try...except block. Then inside the reader’s class, set the enabled class attribute to mark import success or failure. This makes it possible for users to continue using their favourite markup method without needing to install modules for formats they don’t use. How to implement a new generator?¶ Generators have two important methods. You’re not forced to create both; only the existing ones will be called. generate_context, that is called first, for all the generators. Do whatever you have to do, and update the global context if needed. This context is shared between all generators, and will be passed to the templates. For instance, the PageGenerator generate_contextmethod finds all the pages, transforms them into objects, and populates the context with them. Be careful not to output anything using this context at this stage, as it is likely to change by the effect of other generators. generate_outputis then called. And guess what is it made for? Oh, generating the output. :) It’s here that you may want to look at the context and call the methods of the writerobject that is passed as the first argument of this function. In the PageGeneratorexample, this method will look at all the pages recorded in the global context and output a file on the disk (using the writer method write_file) for each page encountered.
https://pelican.readthedocs.io/en/4.1.0/internals.html
CC-MAIN-2019-47
refinedweb
586
58.48
24452/how-to-display-an-animated-gif I want to display animated GIF images in my aplication. As I found out the hard way Android doesn't support animated GIF natively. However it can display animations using AnimationDrawable? The example uses animation saved as frames in application resources but what I need is to display animated gif directly. My plan is to break animated GIF to frames and add each frame as drawable to AnimationDrawable. In Java 9 you can use: List<String> list= List.of("Hello", "World", ...READ MORE public static final String[] VALUES = new ...READ MORE You can also use Java Standard Library ...READ MORE import java.util.Arrays; public class Sort { .. We can use the static frequency() method. int ...READ MORE Here are two ways illustrating this: Integer x ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/24452/how-to-display-an-animated-gif
CC-MAIN-2021-17
refinedweb
141
61.43
Haskell Quiz/Constraint Processing/Solution Jethr0 From HaskellWiki Latest revision as of 10:45, 13 January 2007 Basically there's nothing to be done in haskell for this quiz. As the List Monad already provides non-deterministic evaluation with "guard" as a description of constraints, you really just have to write the problem in the List Monad and be done with it. Of course one could write all kinds of wrapping hackery, but I think from the standpoint of usability and conciseness the built-in behaviour of haskell is already pretty optimal. constr = do a <- [0..4] b <- [0..4] c <- [0..4] guard (a < b) guard (a + b == c) return ("a:",a,"b:",b,"c:",c) {- > constr [("a:",0,"b:",1,"c:",1) ,("a:",0,"b:",2,"c:",2) ,("a:",0,"b:",3,"c:",3) ,("a:",0,"b:",4,"c:",4) ,("a:",1,"b:",2,"c:",3) ,("a:",1,"b:",3,"c:",4)] -})
http://www.haskell.org/haskellwiki/index.php?title=Haskell_Quiz/Constraint_Processing/Solution_Jethr0&diff=10212&oldid=9593
CC-MAIN-2014-23
refinedweb
154
64
Updated Amazon S3 storage from django-storages. Adds more fixes than I can remember, a metadata cache system and some extra utilities for dealing with MEDIA_URL and HTTPS, CloudFront and for creating signed URLs. Updated Amazon S3 storage from django-storages. Adds more fixes than I can remember, a metadata cache system and some extra utilities for dealing with MEDIA_URL and HTTPS, CloudFront and for creating signed URLs. Installation - Add cuddlybuddly.storage.s3 to your INSTALLED_APPS. - Set DEFAULT_FILE_STORAGE to cuddlybuddly.storage.s3.S3Storage (as a string, don’t import it). - Set MEDIA_URL to your bucket URL , e.g.. - Enter your AWS credentials in the settings below. Settings AWS_ACCESS_KEY_ID Your Amazon Web Services access key, as a string. AWS_SECRET_ACCESS_KEY Your Amazon Web Services secret access key, as a string. AWS_STORAGE_BUCKET_NAME Your Amazon Web Services storage bucket name, as a string. AWS_HEADERS A list of regular expressions which if matched add the headers to the file being uploaded to S3. The patterns are matched from first to last: # see AWS_HEADERS = [ ('^private/', { 'x-amz-acl': 'private', 'Expires': 'Thu, 15 Apr 2000 20:00:00 GMT', 'Cache-Control': 'private, max-age=0' }), ('.*', { 'x-amz-acl': 'public-read', 'Expires': 'Sat, 30 Oct 2010 20:00:00 GMT', 'Cache-Control': 'public, max-age=31556926' }) ] - x-amz-acl sets the ACL of the file on S3 and defaults to private. - Expires is for old HTTP/1.0 caches and must be a perfectly formatted RFC 1123 date to work properly. django.utils.http.http_date can help you here. - Cache-Control is HTTP/1.1 and takes precedence if supported. max-age is the number of seconds into the future the response should be cached for. AWS_CALLING_FORMAT Optional and defaults to SUBDOMAIN. The way you’d like to call the Amazon Web Services API, for instance if you need to use the old path method: from cuddlybuddly.storage.s3 import CallingFormat AWS_CALLING_FORMAT = CallingFormat.PATH CUDDLYBUDDLY_STORAGE_S3_GZIP_CONTENT_TYPES A list of content types that will be gzipped. Defaults to ('text/css', 'application/javascript', 'application/x-javascript'). CUDDLYBUDDLY_STORAGE_S3_SKIP_TESTS Set to a true value to skip the tests as they can be pretty slow. CUDDLYBUDDLY_STORAGE_S3_SYNC_EXCLUDE A list of regular expressions of files and folders to ignore when using the synchronize commands. Defaults to ['\.svn$', '\.git$', '\.hg$', 'Thumbs\.db$', '\.DS_Store$']. CUDDLYBUDDLY_STORAGE_S3_KEY_PAIR A tuple of a key pair ID and the contents of the private key from the security credentials page of your AWS account. This is used for signing private CloudFront URLs. For example: settings.CUDDLYBUDDLY_STORAGE_S3_KEY_PAIR = ('PK12345EXAMPLE', """-----BEGIN RSA PRIVATE KEY----- ...key contents... -----END RSA PRIVATE KEY-----""") HTTPS Because when you use S3 your MEDIA_URL must be absolute (i.e. it starts with http) it’s more difficult to have URLs that match how the page was requested. The following things should help with that. cuddlybuddly.storage.s3.middleware.ThreadLocals This middleware will ensure that the URLs of files retrieved from the database will have the same protocol as how the page was requested. cuddlybuddly.storage.s3.context_processors.media This context processor returns MEDIA_URL with the protocol matching how the page was requested. Cache Included is a cache system to store file metadata to speed up accessing file metadata such as size and the last modified time. It is disabled by default. FileSystemCache The only included cache system is FileSystemCache that stores the cache on the local disk. To use it, add the following to your settings file: CUDDLYBUDDLY_STORAGE_S3_CACHE = 'cuddlybuddly.storage.s3.cache.FileSystemCache' CUDDLYBUDDLY_STORAGE_S3_FILE_CACHE_DIR = '/location/to/store/cache' Custom Cache To create your own cache system, inherit from cuddlybuddly.storage.s3.cache.Cache and implement the following methods: - exists - modified_time - save - size - remove Utilities create_signed_url(file, expires=60, secure=False, private_cloudfront=False, expires_at=None) Creates a signed URL to file that will expire in expires seconds. If secure is set to True an https link will be returned. The private_cloudfront argument will use they key pair setup with CUDDLYBUDDLY_STORAGE_S3_KEY_PAIR to create signed URLs for a private CloudFront distribution. The expires_at argument will override expires and expire the URL at a specified UNIX timestamp. It was mostly just added for generating consistent URLs for testing. To import it: from cuddlybuddly.storage.s3.utils import create_signed_url CloudFrontURLs(default, patterns={}, https=None) Use this with the context processor or storage backends to return varying MEDIA_URL or STATIC_URL depending on the path to improve page loading times. To use it add something like the following to your settings file: from cuddlybuddly.storage.s3.utils import CloudFrontURLs MEDIA_URL = CloudFrontURLs('', patterns={ '^images/': '', '^banners/': '', '^css/': '' }, https='') The https argument is a URL to bypass CloudFront’s lack of HTTPS CNAME support. s3_media_url Template Tag This is for use with CloudFrontURLs and will return the appropriate URL if a match is found. Usage: {% load s3_tags %} {% s3_media_url 'css/common.css' %} For HTTPS, the cuddlybuddly.storage.s3.middleware.ThreadLocals middleware must also be used. s3_static_url Template Tag The same as s3_media_url but uses STATIC_URL instead. cuddlybuddly.storage.s3.S3StorageStatic Storage Backend A version of the storage backend that uses STATIC_URL instead. For use with STATICFILES_STORAGE and the static template tag from contrib.staticfiles. Commands cb_s3_sync_media Synchronizes a directory with your S3 bucket. It will skip files that are already up to date or newer in the bucket but will not remove old files as that has the potential to go very wrong. The headers specified in AWS_HEADERS will be applied. It has the following options: - --cache, -c - Get the modified times of files from the cache (if available) instead of checking S3. This is faster but could be inaccurate. - --dir, -d - The directory to synchronize with your bucket, defaults to MEDIA_ROOT. - --exclude, -e - A comma separated list of regular expressions to ignore files or folders. Defaults to CUDDLYBUDDLY_STORAGE_S3_SYNC_EXCLUDE. - --force, -f - Uploads all files even if the version in the bucket is up to date. - --prefix, -p - A prefix to prepend to every file uploaded, i.e. a subfolder to place the files in. cb_s3_sync_static Exactly the same as cb_s3_sync_media except that dir defeaults to STATIC_ROOT. A note on the tests The tests in tests/s3test.py are pretty much straight from Amazon but have a tendency to fail if you run them too often / too quickly. When they do this they sometimes leave behind files or buckets in your account that you will need to go and delete to make the tests pass again. The signed URL tests will also fail if your computer’s clock is too far off from Amazon’s servers. 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/django-cuddlybuddly-storage-s3/
CC-MAIN-2017-51
refinedweb
1,092
58.38
Bruno Haible <address@hidden> writes: > Karl Berry wrote: >> I know I am not looking forward to upgrading Texinfo to using >> all the gnulib modules, precisely because of all those dependencies. > > What is it what disturbs you with the amount of dependencies? The maintenance > work? Don't you trust the code? The size of the distribution? The time > "configure" takes to complete? For me it is that the dependencies create requirements on my code that make things more complicated. Some examples: error: assumes the application add a symbol 'program_name'. This is difficult to do properly if my application is a library with its own namespace. malloc: add a #define malloc rpl_malloc which causes code in my package that doesn't need gnulib to break during link. unlocked-io (included implicitly by several modules): claims to be thread unsafe. alloca.c: depends on xmalloc, which I don't always want to use (especially if just copy the file and use AC_FUNC_ALLOCA). getopt: depends on gettext which adds ~15 additional files even if I don't use gettext. These are all low-level modules that are implicitly used by many packages, so there are many other modules that are unusable for the same reasons. Being able to parametrize modules would be nice. (Incidentally, I just stopped using argp and gnulib in gsasl because of these and other problems...)
http://lists.gnu.org/archive/html/bug-gnulib/2003-11/msg00080.html
CC-MAIN-2015-11
refinedweb
225
66.13
Command Line Programs on macOS Tutorial Discover how easy it is to make your own terminal-based apps with this command line programs on macOS tutorial. Updated for Xcode 9 and Swift 4! Version - Other, Other, Other The typical Mac user interacts with their computer using a Graphical User Interface (GUI). GUIs, as the name implies, are based on the user visually interacting with the computer via input devices such as the mouse by selecting or operating on screen elements such as menus, buttons etc. Not so long ago, before the advent of the GUI, command-line interfaces (CLI) were the primary method for interacting with computers. CLIs are text-based interfaces, where the user types in the program name to execute, optionally followed by arguments. macOS tutorial, you will write a command-line utilty named Panagram. Depending on the options passed in, it will detect if a given input is a palindrome or anagram. It can be started with predefined arguments, or run in interactive mode where the user is prompted to enter the required values. Typically, command-line programs are launched from a shell (like the bash shell in macOS) embedded in a utility application like Terminal in macOS. For the sake of simplicity and ease of learning, in this tutorial, most of the time you will use Xcode to launch Panagram. At the end of the tutorial you will learn how to launch Panagram from the terminal. Getting Started Swift seems like an odd choice for creating a command-line program since languages like C, Perl, Ruby or Java are. For this tutorial, you’ll create a classic compiled project. Open Xcode and go to File/New/Project. Find the macOS group, select Application/Command Line Tool and click Next: For Product Name, enter Panagram. Make sure that Language is set to Swift, then click Next. Choose a location on your disk to save your project and click Create. In the Project Navigator area you will now see the main.swift file that was created by the Xcode Command Line Tool template. the main file that isn’t a method or class declaration is the first one to be executed. It’s a good idea to keep your main.swift file as clean as possible and put all your classes and structs in their own files. This keeps things streamlined and helps you to understand the main execution path. The Output Stream In most command-line programs, you’d like to print some messages for the user. For example, a program that converts video files into different formats could print the current progress or some error message if something went wrong. Unix-based systems such as macOS. stdoutand stderrare the same and messages for both are written to the console. It is a common practice to redirect stderrto a file so error messages scrolled off the screen can be viewed later. Also this can make debugging of a shipped application much easier by hiding information the user doesn’t need to see, but still keep the error messages for later inspection. With the Panagram group selected in the Project navigator, press Cmd + N to create a new file. Under macOS, select Source/Swift File and press Next: Save the file as ConsoleIO.swift. You’ll wrap all the input and output elements in a small, handy class named ConsoleIO. Add the following code to the end of ConsoleIO.swift: class ConsoleIO { } Your next task is to change Panagram to use the two output streams. In ConsoleIO.swift add the following enum at the top of the file, above the ConsoleIO class implementation and below the import line: enum OutputType { case error case standard } This defines the output stream to use when writing messages. Next, add the following method to the ConsoleIO class (between the curly braces for the class implementation): func writeMessage(_ message: String, to: OutputType = .standard) { switch to { case .standard: print("\(message)") case .error: fputs("Error: \(message)\n", stderr) } } This method has two parameters; the first is the actual message to print, and the second is the destination. The second parameter defaults to .standard. The code for the .standard option uses stdout. The .error case uses the C function fputs to write to stderr, which is a global variable and points to the standard error stream. Add the following code to the end of the ConsoleIO class: func printUsage() { let executableName = (CommandLine.arguments[0] as NSString).lastPathComponent writeMessage("usage:") writeMessage("\(executableName) -a string1 string2") writeMessage("or") writeMessage("\(executableName) -p string") writeMessage("or") writeMessage("\(executableName) -h to show usage information") writeMessage("Type \(executableName) without an option to enter interactive mode.") } This code defines the printUsage() method that prints usage information to the console. Every time you run a program, the path to the executable is implicitly passed as argument[0] and accessible through the global CommandLine enum. CommandLine is a small wrapper in the Swift Standard Library around the argc and argv arguments you may know from C-like languages. Create another new Swift file named Panagram.swift (following the same steps as before) and add the following code to it: class Panagram { let consoleIO = ConsoleIO() func staticMode() { consoleIO.printUsage() } } This defines a Panagram class, how to send messages to stdout and stderr Panagram.swift and add the following enum at the top of the file, outside the scope of the Panagram class: enum OptionType: String { case palindrome = "p" case anagram = "a" case help = "h" case unknown init(value: String) { switch value { case "a": self = .anagram case "p": self = .palindrome case "h": self = .help default: self = .unknown } } } This defines an enum with String as its base type so you can pass the option argument directly to init(_:). Panagram has three options: -p to detect palindromes, -a for anagrams and -h to show the usage information. Everything else will be handled as an error. Next, add the following method to the Panagram class: func getOption(_ option: String) -> (option:OptionType, value: String) { return (OptionType(value: option), option) } The above method accepts an option argument as a String and returns a tuple of OptionType and String. In the Panagram, class replace the contents of staticMode() with the following: //1 let argCount = CommandLine.argc //2 let argument = CommandLine.arguments[1] //3 let (option, value) = getOption(argument.substring(from: argument.index(argument.startIndex, offsetBy: 1))) //4 consoleIO.writeMessage("Argument count: \(argCount) Option: \(option) value: \(value)") Here’s what’s going on in the code above: - You first get the number of arguments passed to the program. Since the executable path is always passed in (as CommandLine.arguments[0]), the count value will always be greater than or equal to 1. - Next, take the first “real” argument (the option argument) from the argumentsarray. - Then you parse the argument and convert it to an OptionType. The index(_:offsetBy:)method is simply skipping the first character in the argument’s string, which in this case is the hyphen (`-`) character before the option. - Finally, you log the parsing results to the Console. In main.swift, replace the line panagram.staticMode() with the following: if CommandLine.argc < 2 { //TODO: Handle interactive mode } else { panagram.staticMode() } If your program is invoked with fewer than 2 arguments, then you're going to start interactive mode - you'll do this part later. Otherwise, you use the non-interactive static mode. You now need to figure out how to pass arguments to your command-line tool from within Xcode. To do this, click on the Scheme named Panagram in the Toolbar: Select Edit Scheme... from the menu that appears: Ensure Run is selected in the left pane, click the Arguments tab, then click the + sign under Arguments Passed On Launch. Add -p as argument and click Close: Now build and run,. To keep things simple, Panagram will ignore capitalization and white spaces, but will not handle punctuation. named StringExtension.swift: func isAnagramOf(_ s: String) -> Bool { //1 let lowerSelf = self.lowercased().replacingOccurrences(of: " ", with: "") let lowerOther = s.lowercased().replacingOccurrences(of: " ", with: "") //2 return lowerSelf.sorted() == lowerOther.sorted() }cased().replacingOccurrences(of: " ", with: "") //2 let s = String(f.reversed()) / call to writeMessage(_:to:) in staticMode() with the following: //1 switch option { case .anagram: //2 if argCount != 4 { if argCount > 4 { consoleIO.writeMessage("Too many arguments for option \(option.rawValue)", to: .error) } else { consoleIO.writeMessage("Too few arguments for option \(option.rawValue)", to: .error) } consoleIO.printUsage() } else { //3 let first = CommandLine.arguments[2] let second = CommandLine.arguments[3] if first.isAnagramOf(second) { consoleIO.writeMessage("\(second) is an anagram of \(first)") } else { consoleIO.writeMessage("\(second) is not an anagram of \(first)") } } case .palindrome: //4 if argCount != 3 { if argCount > 3 { consoleIO.writeMessage("Too many arguments for option \(option.rawValue)", to: .error) } else { consoleIO.writeMessage("Too few arguments for option \(option.rawValue)", to: .error) } consoleIO.printUsage() } else { //5 let s = CommandLine.arguments[2] let isPalindrome = s.isPalindrome() consoleIO.writeMessage("\(s) is \(isPalindrome ? "" : "not ")a palindrome") } //6 case .help: consoleIO.printUsage() case .unknown: //7 consoleIO.writeMessage("Unknown option \(value)") consoleIO.printUsage() } Going through the above code step-by-step: - First, switch based on what argument you were passed, to determine what operation will be performed. - In the case of an anagram, there must be four command-line arguments passed in. The first is the executable path, the second the -aoption and finally the two strings to check. If you don't have four arguments, then print an error message. - If the argument count is good, store the two strings in local variables, check them to see if they are anagrams of each other, and print the result. - In the case of a palindrome, you must have three arguments. The first is the executable path, the second is the -poption and finally the string to check. If you don't have three arguments, then print an error message. - Check the string to see if it is a palindrome and print the result. - If the -hoption was passed in, then print the usage information. - If an unknown option is passed, print the usage information. Now, modify the arguments inside the scheme. For example, to use the -p option you must pass two arguments (in addition to the first argument, the executable's path, which is always passed implicitly). Select Edit Scheme... from the Set Active Scheme toolbar item, and add a second argument with the value "level" as shown below: Build and run, and you'll see the following output in the console: level is a palindrome Program ended with exit code: 0 Handle Input Interactively Now that you have a basic version of Panagram working, you can make it even more useful by adding the ability to type in the arguments interactively via the input stream. In this section, you will add code so when Panagram is started without arguments, it will open in interactive mode and prompt the user for the input it needs. First, you need a way to get input from the keyboard. stdin is attached to the keyboard and is therefore a way for you to collect input from users interactively. Open ConsoleIO.swift and add the following method to the class: func getInput() -> String { // 1 let keyboard = FileHandle.standardInput // 2 let inputData = keyboard.availableData // 3 let strData = String(data: inputData, encoding: String.Encoding.utf8)! // 4 return strData.trimmingCharacters(in: CharacterSet.newlines) } Taking each numbered section in turn: - First, grab a handle to stdin. - Next, read any data on the stream. - Convert the data to a string. - Finally, remove any newline characters and return the string. Next, open Panagram.swift and add the following method to the class:) = getOption(consoleIO.getInput()) switch option { case .anagram: //4 consoleIO.writeMessage("Type the first string:") let first = consoleIO.getInput() consoleIO.writeMessage("Type the second string:") let second = consoleIO.getInput() //5 if first.isAnagramOf. - If the option was for anagrams,. In Panagram.swift add the following line to the OptionType enum: case quit = "q" Next, add the following line to the enum's init(_:): case "q": self = .quit In the same file, add a .quit case to the switch statement inside interactiveMode(): case .quit: shouldQuit = true Then, change the .unknown case definition inside staticMode() as follows: case .unknown, .quit: Open main.swift and replace the comment //TODO: Handle interactive mode with the following: panagram.interactiveMode() To test interactive mode, you must not have any arguments defined in the Scheme. So, remove the two arguments you defined earlier. Select Edit Scheme... from the toolbar menu. Select each argument and then click the - sign under Arguments Passed On Launch. Once all arguments are deleted, click Close: Build and run, and you'll see the following output in the Console: Welcome to Panagram. This program checks if an input string is an anagram or palindrome. Type 'a' to check for anagrams or 'p' for palindromes type 'q' to quit. Try out the different options. Type an option letter (do not prefix with a hyphen) followed by Return. You will be prompted for the arguments. Enter each value followed by Return. In the Console you should see something similar to this: a Type the first string: silent Type the second string: listen listen is an anagram of silent Type 'a' to check for anagrams or 'p' for palindromes type 'q' to quit. p Type a word or sentence: level level is a palindrome Type 'a' to check for anagrams or 'p' for palindromes type 'q' to quit. f Error: Unknown option f Type 'a' to check for anagrams or 'p' for palindromes type 'q' to quit. q Program ended with exit code: 0 Launching Outside Xcode Normally, a command-line program is launched from a shell utility like Terminal (vs. launching it from an IDE like Xcode). The following section walks you through launching your app in Terminal. There are different ways to launch your program via Terminal. You could find the compiled binary using the Finder and start it directly via Terminal. Or, you could be lazy and tell Xcode to do this for you. First, you'll learn the lazy way. Launch your app in Terminal from Xcode Create a new scheme that will open Terminal and launch Panagram in the Terminal window. Click on the scheme named Panagram in the toolbar and select New Scheme: Name the new scheme Panagram on Terminal: Ensure the Panagram on Terminal scheme is selected as the active scheme. Click the scheme and select Edit Scheme... in the popover. Ensure that the Info tab is selected and then click on the Executable drop down and select Other. Now, find the Terminal.app in your Applications/Utilities folder and click Choose. Now that Terminal is your executable, uncheck Debug executable. Your Panagram on Terminal scheme's Info tab should look like this: Next, select the Arguments tab, then add one new argument: ${BUILT_PRODUCTS_DIR}/${FULL_PRODUCT_NAME} Finally, click Close. Now, make sure you have the scheme Panagram on Terminal selected, then build and run your project. Xcode will open Terminal and pass through the path to your program. Terminal will then launch your program as you'd expect. Launch your app directly from Terminal Open Terminal from your Applications/Utilities folder. In the Project Navigator select your product under the Products group. Copy your debug folder's Full Path from Xcode's Utility area as shown below (do not include "Panagram"): Open a Finder window and select the Go/Go to Folder... menu item and paste the full path you copied in the previous step into the dialog's text field: Click Go and Finder navigates to the folder containing the Panagram executable: Drag the Panagram executable from Finder to the Terminal window and drop it there. Switch to the Terminal window and hit Return on the keyboard. Terminal launches Panagram in interactive mode since no arguments were specified: Displaying Errors Finally, you will add some code to display error messages in red. Open ConsoleIO.swift and in writeMessage(_:to:), replace the two case statements with the following: case .standard: // 1 print("\u{001B}[;m\(message)") case .error: // 2 fputs("\u{001B}[0;31m\(message)\n", stderr) Taking each numbered line in turn: - The sequence \u{001B}[;mis used in the standard case to reset the terminal's text color back to the default. - The sequence \u{001B}[0;31mare control characters that cause Terminal to change the color of the following text strings to red. [;mat the beginning of the output might look a bit awkward. That's because the Xcode Console doesn't support using control characters to colorize text output. Build and run, this will launch Panagram in Terminal. Type f for option, the Unknown option f error message will display in red: Where to Go From Here? You can download the final project for this tutorial the article Scripting in Swift is pretty awesome if you're interested in Swift for scripting. I hope you enjoyed this Command Line Programs on macOS tutorial; if you have any questions or comments, feel free to join the forum discussion below!
https://www.raywenderlich.com/511-command-line-programs-on-macos-tutorial
CC-MAIN-2021-04
refinedweb
2,832
66.44
> -----Original Message----- > From: Martin Sebor [mailto:sebor@roguewave.com] > Sent: Saturday, September 30, 2006 1:43 AM > To: stdcxx-dev@incubator.apache.org > Subject: Re: [PATCH] Scripts, generating solution and > projects for MSVC/ICC [2] > > Farid Zaripov wrote: > > Patch for scripts of Windows build infrastructure is here: > > > > Btw., I noticed that the _RWBUILD_std macro is (still) being > #defined. It shouldn't be. The _RWBUILD_std macro used to define properly _RWSTD_EXPORT macro. _defs.h, line 454: ======================== // set up Win32/64 DLL export/import directives // _DLL - defined by the compiler when either -MD or -MDd is used // RWDLL - defined for all Rogue Wave(R) products built as shared libs // _RWSHARED - defined for libstd built/used as a shared lib #if (defined (_WIN32) || defined (_WIN64)) && \ (defined (RWDLL) || defined (_RWSHARED)) # ifdef _RWBUILD_std # define _RWSTD_EXPORT __declspec (dllexport) # else # define _RWSTD_EXPORT __declspec (dllimport) # endif // _RWBUILD_std ======================== Should we replace #ifdef _RWBUILD_std to #ifdef _RWSTD_LIB_SRC in _defs.h? >. The CPPFLAGS, LDFLAGS are used in libraries, examples and tests builds also. Thus LD variable should contain additiona options for configure step. We can rename LDFLAGS to LDFLAGS.wide and add LDFLAGS.config=-qnoipo. BTW it seems to me -qnoipo flags is unnecessary (I just copied this flags from the previous scripts). All works fine without this flag. > And shouldn't we be using cl (or icl) to link instead of invoking the linker directly? I not found where MS recommends invoke cl.exe instead of link.exe to link files. Farid.
http://mail-archives.apache.org/mod_mbox/stdcxx-dev/200610.mbox/%3CF92433E3D38672499C549EB615AFADA08EAD43@exkiv.kyiv.vdiweb.com%3E
CC-MAIN-2020-34
refinedweb
242
58.38
The QIconDragEvent class signals that a main icon drag has begun. More... #include <qevent.h> Inherits QEvent. List of all member functions.. Constructs an icon drag event object with the accept parameter flag set to FALSE. See also accept(). Sets the accept flag of the icon drag event object. Setting the accept flag indicates that the receiver of this event has started a drag and drop oeration. The accept flag is not set by default. See also ignore() and QWidget::hide(). Clears the accept flag of the icon drag object. Clearing the accept flag indicates that the receiver of this event has not handled the icon drag as a result other events can be sent. The icon drag event is constructed with the accept flag cleared. See also accept(). Returns TRUE if the receiver of the event has started a drag and drop operation; otherwise returns FALSE. See also accept() and ignore(). This file is part of the Qt toolkit. Copyright © 1995-2007 Trolltech. All Rights Reserved.
http://idlebox.net/2007/apidocs/qt-x11-free-3.3.8.zip/qicondragevent.html
CC-MAIN-2014-10
refinedweb
167
79.16
NAME eventfd - create a file descriptor for event notification SYNOPSIS #include <sys/eventfd.h> int eventfd(unsigned int initval, int flags); DESCRIPTION.: read(2)), ppoll(2), and epoll(7). close(2) When the file descriptor is no longer required it should be closed. When all file descriptors associated with the same eventfd object have been closed, the resources for object are freed by the kernel. A copy of the file descriptor created by eventfd() is inherited by the child produced by fork(2). The duplicate file descriptor is associated with the same eventfd object. File descriptors created by eventfd() are preserved across execve(2). RETURN VALUE On success, eventfd() returns a new eventfd file descriptor. On error, -1 is returned and errno is set to indicate the error. ERRORS EINVAL flags is invalid; or, in Linux 2.6.26 or earlier, flags is nonzero. EMFILE The per-process limit on open file descriptors has been reached. ENFILE The system-wide limit on the total number of open files has been reached. ENODEV Could not mount (internal) anonymous inode device. ENOMEM There was insufficient memory to create a new eventfd file descriptor. VERSIONS. CONFORMING TO eventfd() and eventfd2() are Linux-specific. NOTES kernel-userspace bridge).):. EXAMPLE Program source "); } } SEE ALSO futex(2), pipe(2), poll(2), read(2), select(2), signalfd(2), timerfd_create(2), write(2), epoll(7), sem_overview(7) COLOPHON This page is part of release 3.24 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at.
http://manpages.ubuntu.com/manpages/maverick/man2/eventfd2.2.html
CC-MAIN-2014-52
refinedweb
258
68.77
A namespace is a collection of element and attribute names that can be used in an XML document. To draw a comparison between an XML namespace and the real world, if you considered the first names of all the people in your immediate family, they would belong to a namespace that encompasses your last name. XML namespaces represent groups of names for related elements and attributes. Most of the time an individual namespace corresponds directly to a custom markup language, but that doesn't necessarily have to be the case. You also know that namespaces aren't a strict requirement of XML documents. The purpose of namespaces is to eliminate name conflicts between elements and attributes. To better understand how this type of name clash might occur in your own XML documents, consider an XML document that contains information about a video and music collection. You might use a custom markup language unique to each type of information (video and music), which means that each language would have its own elements and attributes. However, you are using both languages within the context of a single XML document, which is where the potential for problems arises. If both markup languages include an element named title that represents the title of a video or music compilation, there is no way for an XML application to know which language you intended to use for the element. The solution to this problem is to assign a namespace to each of the markup languages, which will then provide a clear distinction between the elements and attributes of each language when they are used. In order to fully understand namespaces, you need a solid grasp on the concept of scope in XML documents. The scope of an element or attribute in a document refers to the relative location of the element or attribute within the document. If you visualize the elements in a document as an upside-down tree that begins at the top with the root element, child elements of the root element appear just below the root element as branches (see Figure 5.1). Each element in a "document tree" is known as a node. Nodes are very important when it comes to processing XML documents because they determine the relationship between parent and child elements. The scope of an element refers to its location within this hierarchical tree of elements. So, when I refer to the scope of an element or attribute, I'm talking about the node in which the element or attribute is stored. Figure 5.1. An XML document coded in ETML can be visualized as a hierarchical tree of elements, where each leaf in the tree is known as a node. In this figure, the hypothetical ETML example markup language first mentioned in Defining Data With DTD Schemas, "Defining Data with DTD Schemas," is used to demonstrate how an XML document consists of a hierarchical tree of elements. Each node in the tree of an XML document has its own scope, and can therefore have its own namespace. Scope is important to namespaces because it's possible to use a namespace within a given scope, which means it affects only elements and attributes beneath a particular node. Contrast this with a namespace that has global scope, which means the namespace applies to the entire document. Any guess as to how you might establish a global namespace? It's easy you just associate it with the root element, which by definition houses the remainder of the document. You learn much more about scope as it applies to namespaces throughout the remainder of this tutorial. Before you get to that, however, it's time to learn where namespace names come from.
https://www.brainbell.com/tutorials/XML/Understanding_Namespaces.htm
CC-MAIN-2020-40
refinedweb
620
57
KDEUI #include <kimagecache.h> Detailed Description A simple wrapping layer over KSharedDataCache to support caching images and pixmaps. This class can be used to share images between different processes, which is useful when it is known that such images will be used across many processes, or when creating the image is expensive. In addition, the class also supports caching QPixmaps in a single process using the setPixmapCaching() function. Tips for use: If you already have QPixmaps that you intend to use, and you do not need access to the actual image data, then try to store and retrieve QPixmaps for use. On the other hand, if you will need to store and retrieve actual image data (to modify the image after retrieval for instance) then you should use QImage to save the conversion cost from QPixmap to QImage. KImageCache is a subclass of KSharedDataCache, so all of the methods that can be used with KSharedDataCache can be used with KImageCache, with the exception of KSharedDataCache::insert() and KSharedDataCache::find(). - Since - 4.5 Definition at line 58 of file kimagecache.h. Constructor & Destructor Documentation Constructs an image cache, named by cacheName, with a default size of defaultCacheSize. - Parameters - Definition at line 82 of file kimagecache.cpp. Deconstructor. Definition at line 92 of file kimagecache.cpp. Member Function Documentation Removes all entries from the cache. In addition any cached pixmaps (as per setPixmapCaching()) are also removed. Definition at line 164 of file kimagecache.cpp. Copies the cached image identified by key to destination. If no such image exists destination is unchanged. - Returns - true if the image identified by keyexisted, false otherwise. Definition at line 122 of file kimagecache.cpp. Copies the cached pixmap identified by key to destination. If no such pixmap exists destination is unchanged. - Returns - true if the pixmap identified by keyexisted, false otherwise. - See also - setPixmapCaching() Definition at line 136 of file kimagecache.cpp. Inserts the image into the shared cache, accessible with key. This variant is preferred over insertPixmap() if your source data is already a QImage, if it is essential that the image be in shared memory (such as for SVG icons which have a high render time), or if it will need to be in QImage form after it is retrieved from the cache. - Parameters - - Returns - true if the image was successfully cached, false otherwise. Definition at line 97 of file kimagecache.cpp. Inserts the pixmap given by pixmap to the cache, accessible with key. The pixmap must be converted to a QImage in order to be stored into shared memory. In order to prevent unnecessary conversions from taking place pixmap will also be cached (but not in stored memory) and would be accessible using findPixmap() if pixmap caching is enabled. - Parameters - - Returns - true if the pixmap was successfully cached, false otherwise. - See also - setPixmapCaching() Definition at line 111 of file kimagecache.cpp. - Returns - The time that an image or pixmap was last inserted into a cache. Definition at line 170 of file kimagecache.cpp. - Returns - The highest memory size in bytes to be used by cached pixmaps. - Since - 4.6 Definition at line 190 of file kimagecache.cpp. - Returns - if QPixmaps added with insertPixmap() will be stored in a local pixmap cache as well as the shared image cache. The default is to cache pixmaps locally. Definition at line 175 of file kimagecache.cpp. Sets the highest memory size the pixmap cache should use. - Parameters - - Since - 4.6 Definition at line 195 of file kimagecache.cpp. Enables or disables local pixmap caching. If it is anticipated that a pixmap will be frequently needed then this can actually save memory overall since the X server or graphics card will not have to store duplicate copies of the same image. - Parameters - Definition at line 180 of file kimagecache.
https://api.kde.org/4.x-api/kdelibs-apidocs/kdeui/html/classKImageCache.html
CC-MAIN-2019-30
refinedweb
631
57.37
SPI controlling LED Strip UCS1903 - Paul Chabot I am trying to control a strip of lights that I have using a UCS1903. I am not understanding things correctly. I understand that a square wave can be used to indicate a 1 or a 0 and that pauses in sending a signal can indicate other functions. How does this translate to sending infomation over spi. Im not sure. If I could watch was is happening on the MOSI as it is attached to the flash storage...if I connect the DIN of my light strip to MOSI and install software or boot up the machine, the lights start going about changing colours and lighting up... But plugged into CS1 and trying to send data.. The lights take a 24bit piece of data r(8bits) g(8bits) and b(8bits) Here is code showing how my brain is comprehending this. import onionSpi import time busnum = 1 deviceid = 32766 spi = onionSpi.OnionSpi(busnum, deviceid) spi.speed = 400000 spi.delay = 1 spi.mosi = 18 spi.mode = 0 #spi.bitsPerWord = 1000 # spi.bitsPerWord = 24 # spi.modeBits = ['lsbfirst'] spi.modeBits = 0x8 spi.setupDevice() spi.registerDevice() #spi.bitsPerWord = 3 device_check = spi.checkDevice() print device_check print 'SPI MOSI GPIO: %d'%(spi.mosi) print 'SPI Speed: %d Hz (%d kHz)'%(spi.speed, spi.speed/1000) print 'Mode Bits: 0x%x'%(spi.modeBits) # R7 R6 R5 R4 R3 R2 R1 R0 G7 G6 G5 G4 G3 G2 G1 G0 B7 B6 B5 B4 B3 B2 B1 B0 led_rgb = [] led_full = [ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff ] led_red = [ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff ] led_green = [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ] led_blue = [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ] # ret1 = spi.writeBytes(0x00, led_red) # ret2 = spi.writeBytes(0x00, led_green) # ret3 = spi.writeBytes(0x00, led_blue) # print ret1 # print ret2 # print ret3 vals = [0x00, 0x1C, 0x07, 0x12, 0x37, 0x32, 0x29, 0x2D] ret = spi.write(vals) # spi.write(led_red) # time.sleep(1) # spi.write(led_green) # time.sleep(1) # spi.write(led_blue) # time.sleep(1) @Paul-Chabot: From the datasheet you linked, these UCS1903 chips are close relatives to the WS281x family of LED chain chips. To generate the required signal with SPI, you'd need to have a SPI interface available exclusively for the purpose (which you don't on Omega2), and you need to have tight control of the SPI to send a long uninterrupted stream of data (which usually works on Arduino&Co, but is difficult on a Linux system). But luckily, there's hardware better suited for the task than the SPI in Omega2's MT7688 chip: the PWM unit. It's still a bit tricky to meet all timing constraints, but definitely possible. I know because I wrote a kernel driver named p44-ledchain exactly for the purpose ;-) I needed it for Omega2 based projects like this (with 200 WS2813 LEDs). Now, the UCS1903 has slightly different timings specs than the chips already supported in p44-ledchain(WS2811, WS2812, WS2813, P9823, SK6812). Still, I think it should work with the P9823 setting. If not, just let me know and I can add another option for the UCS1903 chip to the driver. If you want to give it a try: Install the driver (needs --force-dependsbecause there's no 100% kernel version match): cd /tmp wget ledchain_4.4.61%2B0.9-2_mipsel_24kc.ipk opkg install --force-depends kmod-p44-ledchain* Then load the driver and configure it for a chain of 100 P9823 (see here for detailed description of the module parameters): insmod /lib/modules/4.4.61/p44-ledchain.ko ledchain0=0,100,3 Now you need to configure one of the GPIO pins to provide PWM0 output (GPIO 18 or 46 have that option): omega2-ctrl gpiomux set pwm0 pwm; # for GPIO 18 omega2-ctrl gpiomux set uart1 pwm01; # for GPIO 46 Finally you need to connect your DIN of the first UCS1903 in the chain to the PWM0 output pin of the Omega2 (GPIO 18 or 46). As the Omega2 is 3.3V and the UCS1903 is 5V powered, the high level coming from the Omega2 might not be sufficient for the UCS1903. In my experience with WS281x chips, it can work sometimes, but not reliably. So the right way to do it is adding a level shifter such as a 74AHCT1G125. Now you can just write a string of RGB values into /dev/ledchain0 to control the LEDs, for example: echo -en '\xFF\x00\x00\x00\xFF\x00\x00\x00\xFF' >/dev/ledchain0 to make the first LED red, second green, third blue. There's more info and details in this forum thread
http://community.onion.io/topic/2782/spi-controlling-led-strip-ucs1903
CC-MAIN-2019-13
refinedweb
788
72.36
ohammad Elsheimy(10) Mahesh Chand(7) Hirendra Sisodiya(4) manish Mehta(3) Mostafa Kaisoun(3) Sanjeev Kumar(3) Srinivasa Sivkumar(2) R. Seenivasaragavan Ramadurai(2) Rick Malek(2) Sushila Patel(2) Nipun Tomar(2) Jon Person(2) Satyapriya Nayak(2) Kishor Patil(2) Scott Lysle(2) Graham (2) Pramod Singh(1) Ashish Banerjee(1) Bulent Ozkir(1) casper boekhoudt(1) Ricardo Federico(1) Filip Bulovic(1) kamalpatel125 (1) Chandrasekaran Sakkarai(1) Anton Knieriemen(1) Sreejumon Purayil(1) Rick Meyer(1) Gangadhara BD(1) Kovan Abdulla(1) Binoy R(1) Sarvesh Damle(1) Santhi Maadhaven(1) Ivy Tang(1) Jaish Mathews(1) Moses Soliman(1) Michael Livshitz(1) Amrish Deep Ravidas(1) Raj Kumar(1) John Penn(1) Bechir Bejaoui(1) Kalyan Bandarupalli(1) Kevin Rou(1) Ashish Tripathi(1) Sunil Atkari(1) Puran Mehra(1) Rick Malek(1) Ankur Gupta(1) Anupama Singh(1) Mattia Baldinger(1) shurland moore(1) Ibrahim Ersoy(1) Jaganathan Bantheswaran(1) Mickey Marshall(1) Tom (1) Jawed MD(1) Manoj Bhoir(1) Deepak Verma(1) Varesh Tuli(1) Amit Patel(1) Charles Stratton(1) Vishal Shukla(1) Yildirim Kocdag(1) Enrico Lorenzo De Vito(1) Yvan (1) Saravana Kumar(1) Tajwer Jal.. Line numbering utility in C# and Java May 08, 2001. After reading this article Java programmers should be able to decipher and de-jargonize the .NET architecture and relate it with the proposed ECMA standard.. . .NET Framework and Web Services - Part 3 Jan 31, 2002. Here I am going to explain Web methods and how to write Web methods in C# and VB.NET. Working with Strings in VB.NET Feb 05, 2002. This article is VB.NET version of Working with Strings in .NET using C#. xBase Engine for C# and VB.NET Feb 25, 2002. This library is written to handle DBF files from C# or VB.NET.. MacroMagic .NET for VB and C# Sep 09, 2002. MacroMagic.NET contains macros for VB and C# developers that can be added to Visual Studio .NET.. 14, 2006. Reusability and component oriented development is one of the features of .NET development. This approach may be applied to any project. In this article I share how you can build your own Windows control derived from an Windows Forms control in Visual Studio 2005. The examples are written using C#. Word automation using C# May 11, 2007. Word Automation through C# is all about programmatically generating the Word Document using C# code. Almost all of the tasks which we perform on word 2003 can be done programmatically using C# or VB.. Writing Your Own GPS Applications: Part II Aug 19, 2008.. How to create a COM object using VS 2008 and consume it from VB 6.0 client application: Part II Nov 04, 2008. In this article, we will see how to create a simple COM application in Visual Studio 2008 and how to consume it from a VB6 client application. Error Result 1 Returned from 'C:\WINDOWS\system32\cmd.exe' Feb 04, 2009. I keep getting the following error message every time I try to run or build a C++ application in Visual Studio.. An Introduction to LINQ Jun 06, 2009. LINQ stands for Language INtegrated Query. Means query language integrated with Microsoft .NET supporting languages i.e. C#.NET, VB.NET, J#.NET etc. Need not to write\ use explicit Data Access Layer. Read and write the text file using vb.net Jul 31, 2009. The code snippet in this article shows how to read and write text files in VB.NET. Coding style models in ASP.NET Aug 24, 2009. In the article I will explain about different coding style in ASP.NET. Sending Mails in .NET Framework Oct 20, 2009. In this article learn how to send e-mail messages via SMTP in .NET Framework. WPF PasswordBox Dec 18, 2009. This article demonstrates how to create and use a PasswordBox control in WPF using XAML, C# and Visual Basic .NET. Converting C# to COBOL Mar 12, 2010. . This article is intended to be used as a model for you to follow when you run into a C# example and need to convert it to COBOL. Add Image on DatagridView Cell Header May 26, 2010. This tip shows how to add images to a Windows Forms DataGridView control cell header using VB.NET.! Creating a Custom DateTextbox User Control: Part I Aug 08, 2010. In this article you will learn how to create a custom date textbox user control.. - Cligs Aug 30, 2010. This is another article that talks about URL shortening services. Today we are going to talk about Cligs, one of the popular shortening services on the web.. Consuming URL Shortening Services – 1click.at Dec 26, 2010. This article is talking about the 1click.at shortening service; how you can use it and how to access it via your C#/VB.NET application. . ! Building Applications that Can Talk Jan 21, 2011.! Configuring ASP.NET with IIS Jan 21, 2011.. How to make image editor tool in C# : Cropping image Mar 23, 2011. This article describes how to crop an image in C# LightSwitch Solution Explorer Views May 15, 2011. One of the feature in Microsoft Visual Studio LightSwitch is Views in the Solution Explorer. You cannot find a feature like that in previous Microsoft IDEs like VB.. Script to Get Microsoft Product's Installed on Your Machine With Version Number Jan 16, 2012. Using this set of script files you will be able to get all the Microsoft products installed on your machine with version number. Paging in a DataGrid Using DropDownList Mar 07, 2012. In this article we learn how to do paging in a DataGrid using a DropDownList. How to Make Help File With VB.NET Apr 04, 2012. Using a TreeView control and a XML file to create a help file. Using Grid ActiveX Control With VB.NET Apr 05, 2012. Using the new ActiveX control (MKGrid) with VB.Net, you can read my article about using MKGrid control with C#. MBScrollBar in VB.NET Apr 08, 2012. MBScrollBar is a ContextMenuStrip which inherits all the properties of a simple Scroll Bar control. Button Array Using VB.NET Apr 10, 2012. In this article we will create an array of buttons using VB.NET Save an Image to Database in WPF using Visual Basic May 29, 2012. Here we learn how it comes in effect using WPF and VB.net. To store an image to database, I created a table in database. How to Record QTP Script in QTP Tool in Testing Jul 30, 2012. In this article I discuss how to record a QTP Script in the QTP Tool. How to Call COM VB6 DLL in WCF Application Sep 12, 2012. How to call a COM\VB6 DLL in a WCF Application. What is VB.NET Namespace Sep 14, 2012. This article describe namespaces in VB.Net. Active Directory Account Expires Sep 19, 2012. This article shows how to set the Active Directory AccountExpires Attribute in .Net. Introduction to ADO.NET Sync Services Sep 21, 2012. This article, using a very basic example in VB .Net, shows how easily you can use ADO .Net Sync services in applications for occasionally-connected architectures. XYDataGrid in VB.NET Sep 22, 2012. XYDataGrid is a web datagrid control which helps to developers to put fixed headers and fixed columns.. Export Gridview Data to pdf format in VB.NET Sep 23, 2012. In this article we will know how to export gridview data to pdf format. Save and Retrieve Image From SQL in VB.NET Oct 14, 2012. This article is about storing and retrieving images from SQL Database using a VB.NET. Send Mail Using Gmail, Yahoo Account in VB.Net and C#.Net Oct 19, 2012. In this article I am going to show how to send mail from Gmail or Yahoo using vb.net & C#.NET without login your Gmail account. Speed of Light C in VB.NET Nov 08, 2012. Speed of light c = the speed of light = 299 792 458 m / s.. Array Redefined in VB.NET Nov 08, 2012. This is article is helpful to get the basic idea of arrays in VB.Net. Silverlight Interaction with php in VB.NET Nov 08, 2012. Silverlight run on client side (Win/Mac/MoonLight) Php on LAMP server. Communication use HTTP protocol. OCR Functionality Through MODI for Extracting text Information from Image file in VB.NET Nov 08, 2012. Article show that how to extract text and layout information from image file like MDI and TIFF file format Outlook Custom Forms - An Introduction in VB.NET Nov 08, 2012. In this article we will see what are outlook custom forms and how to create custom form. Exception Handling in Silverlight Application From WCF in VB.NET Nov 08, 2012. This article explains exception handling in a Silverlight application from WCF. Outlook Custom Forms and VB.NET- Controls and fields Nov 08, 2012. In this article we will see how to add various controls in our custom forms and how to use Built-in Fields on custom forms. Test for User Group Membership in VB.NET Nov 08, 2012. This article describes a simple approach to determining whether or not a logged in user is a member of a group within the context of an asp.net web based application. Simple Fixed Array: Part III Nov 08, 2012. This is the last part of three tutorials on arrays. Application Level Security System in VB.NET Nov 08, 2012. This article will provide help in developing an Application Level Security System. Simple Fixed Array: Part II Nov 08, 2012. This is the second part in the array set of tutorials. About VB VB stand for Visual Basic which is a high level programming language and developed from earlier DOS version called BASIC. BASIC means Beginners' All-purpose Symbolic Instruction Code which is easy programming language to learn. The code looks like English Language. In software development Different software companies produced different versions of BASIC, such as Microsoft QBASIC, QUICKBASIC, GWBASIC ,IBM BASICA and so on. But mostly people are used Microsoft Visual Basic today because it is well developed programming language and supporting resources are available everywhere. In addition Visual Basic 6 is Event-driven because we need to write code in order to perform some tasks in response to certain events. Some of the events are load, click, double click, drag and drop, pressing the keys and more. We will learn more about events in later lessons..
http://www.c-sharpcorner.com/tags/VB
CC-MAIN-2016-30
refinedweb
1,760
69.18
Java String Exercises: Check if two given strings are rotations of each other Java String: Exercise-52 with Solution Write a Java program to check if two given strings are rotations of each other. Sample Solution: Java Code: import java.util.*; class Main { static boolean checkForRotation (String str1, String str2) { return (str1.length() == str2.length()) && ((str1 + str1).indexOf(str2) != -1); } public static void main (String[] args) { String str1 = "ABACD"; String str2 = "CDABA"; System.out.println("The given strings are: "+str1+" and "+str2); System.out.println("\nThe concatination of 1st string twice is: "+str1+str1); if (checkForRotation(str1, str2)) { System.out.println("The 2nd string "+str2+" exists in the new string."); System.out.println("\nStrings are rotations of each other"); } else { System.out.println("The 2nd string "+str2+" not exists in the new string."); System.out.printf("\nStrings are not rotations of each other"); } } } Sample Output: The given strings are: ABACD and CDABA The concatination of 1st string twice is: ABACDABACD The 2nd string CDABA exists in the new string. Strings are rotations of each other Flowchart: Java Code Editor: Improve this sample solution and post your code through Disqus Previous: Write a Java program to count and print all the duplicates in the input string. Next: Write a Java program to match two strings where one string contains wildcard characters. What is the difficulty level of this exercise? New Content: Composer: Dependency manager for PHP, R Programming
https://www.w3resource.com/java-exercises/string/java-string-exercise-52.php
CC-MAIN-2019-18
refinedweb
237
57.16
Summary So I wanted to try out MongoDB and see what it was all about. In this blog post I’m going to give a quick run-down of how to get things up and running just to show how easy it is to install and connect to a MongoDB database. Where to Get MongoDB The official MongoDB website is here, but you can skip right to the download page () and download the windows version of MongoDB. MongoDB is very easy to install and setup. Just run the installer like any other windows install program, then you can go straight to the “Windows Quickstart” page (here) to get things setup. I setup the default configuration by creating a “C:datadb” directory, then I navigated into my C:Program FilesMongoDB 2.6 Standardbin” directory and double-clicked on the mongod.exe file. I spent some time with the mongo.exe program to manually create “collections” (mongo’s equivalent to a table), but you can skip right to the C# code if you’d like. The MongoDB website has a great webpage for getting started with the MongoDB commands if you’re familiar with SQL. You can go here for this page. The C# Code I created a console application in Visual Studio 2012 and then I went straight to NuGet and typed in MongoDB in the search box. The “Official MongoDB C# driver” showed up on top and I installed that one. Next, I went to the Getting Started With the C# Driver page (here) and started typing in some sample code. One of the first things I discovered with MongoDB is that an insert will create a collection. Also any field that is misspelled can cause a record with a different field name to be created in that collection. To get started, include the following using statements: using MongoDB.Bson; using MongoDB.Driver; using MongoDB.Driver.Linq; using MongoDB.Driver.Builders; using MongoDB.Driver.GridFS; Then setup a connection and open your database using these commands: var connectionString = “mongodb://localhost“; var client = new MongoClient(connectionString); var server = client.GetServer(); var database = server.GetDatabase(“test“); var collection = database.GetCollection<Users>(“users“); These are for the standard MongoDB installation. Next, you’ll need an object to represent your data, similar to the way that NHibernate declares records: public class Users { public ObjectId Id { get; set; } public string FirstName { get; set; } public int Age { get; set; } } Now let’s insert some data just to populate a few records: var entity = new Users { FirstName = “Joe“, Age = 27 }; collection.Insert(entity); var id = entity.Id; I ran the program as is and then changed the FirstName and Age and ran the program again to insert another record. You can set up a program to insert a bunch of data if you like, I only needed a couple of records to test the LINQ capabilities. The last part of my program looks like this: var query = from e in collection.AsQueryable<Users>() where e.Age < 34 select e; foreach (var item in query) { Console.WriteLine(item.FirstName); } Console.ReadKey(); My result, as expected, is a list of first names that were inserted into the sample database. In a nutshell, this was a very simple example just to demonstrate the basics of getting things up and running. In order to turn this technology into something serious, we would need to setup MongoDB on a server and make sure it runs reliably (i.e. auto-starts when the machine is rebooted). We would also need to make sure it is secure and that we can make a connection from the machine running the C# program. After that, it’s a matter of designing software pretty much the same as any SQL Sever or Oracle program. Obviously the mappings are simpler than Fluent NHibernate. My next test will be to create two collections and join them. Then I need to test performance differences between MongoDB and NHibernate CRUD operations using a long list of names. After that, I hope to move on to what makes MongoDB “different” and more powerful than a standard SQL server.
http://blog.frankdecaire.com/2014/09/14/introduction-to-mongo-db-and-c/
CC-MAIN-2018-13
refinedweb
686
64.41
So what is Ruby on Rails? Here's an introduction. From Wikipedia: is a beautiful language – you'll love it. Read more on ruby-lang.org and try it here. Rails is a web framework built on Ruby, hence the name Ruby on Rails. It enables the programmer to easily create advanced database-driven websites using scaffolding and code generation, following convention over configuration, which means that if you stick to a certain set of conventions, a lot of features will work right out of the box with very little code. Rails is based on a programming pattern called MVC, which stands for Model-View-Controller. Here I'll try to explain what it is and why it makes sense to use it. The model in MVC is a class for each entity in your application. Example models are User, Category, or Product. The models hold all business logic, for example what should happen if you delete a product, add a new category, or create a new user. See the ActiveRecord section for example models. The views in MVC hold all your presentation and presentation logic, normally HTML. It is based on ERuby which is a templating system that allows for Ruby embedded into HTML and other languages. You probably know this kind of templating system from ASP, PHP, or JSP. Example view: <h1><%= @user.name %></h1> <p> <%= @user.description %> </p> The controller is what binds together the models and views, for example tells the show product view which product it should show, or handles the data from a form post when a user updates a shopping basket. Example controller: class SiteController < ApplicationController def home end def about end end MVC allows for perfect separation of business logic from presentation logic, giving you a much cleaner application that is easier to maintain and, on top of that, a lot more fun to develop. So, how is a request from a visitor's browser sent down to the controller that handles this request? This is done by a routing engine that interprets the request and passes it on to the matching controller: match 'about' => 'site#about' # => /about match 'contact' => 'site#contact' # => /contact root :to => 'site#home' # => / In the heart of the Rails routing engine lies CRUD, or Create, Read, Update, Delete, which comes from a notion that all web pages are made up of these four actions. For example, you create a product, view, or read a user, edit, or update a category, and delete an order. If you follow this pattern, you'll get a lot of work done for you. For example, all it takes to create all of these actions for a product is to tell the routing engine that you have an entity called product, and it will wire up all the routing logic that binds the request to the matching controller for you: resources :products # => /products/23 resources :orders do # => /orders/124 resources :items # => /orders/124/items end ActiveRecord is a pattern that allows for all database access to be written without a single line of database access. You tell the class, or model, what kind of entity you want it to be, which relations it has, and it automagically does the rest for you, creating properties based on the fields from the database, giving you database operation methods like create, update, and delete for free. You write only your custom business logic. The ActiveRecord classes are almost always what makes up the Model part of the aforementioned MVC pattern. Example ActiveRecord model: class Order < ActiveRecord::Base belongs_to :user has_many :items end Then you can: order = Order.find(123) order.user.name # => user name order.items # => array of items In Ruby on Rails, you almost never talk directly to your database like you know it from PHP or other scripting languages. Instead, as part of ActiveRecord, comes a complete database migration framework. Database migrations mean that, instead of manually editing your database, you create Ruby code for creating tables and adding columns. What this does is that it allows for migrating multiple databases with the same changes, for example, a development and production database, without having to remember what changes you made in your development database when deploying to production – you just run the same migrations in a different environment. Migrations are also created using code generation, so you can create a table or add a column using a single shell command: # creates a 'users' table with the specified fields rails generate model User name:string email:string age:integer # adds a description field to the 'users' table rails generate migration AddDescriptionToUsers description:text # runs the migration rake db:migrate In Rails, you have a perfect separation of environments. This means that you can run your system with different settings based on which environment you are currently in, for example, you want your development environment to display verbose error messages where your production site shows a user friendly message to the end user. The Rails 3.1 assets pipeline allows for all your assets (images, stylesheets, and JavaScript) to be managed for you. In your development environment you have your full folder structure with stylesheets and JavaScript written in different languages like CoffeeScript and SCSS. When you deploy, all your assets are compiled and fetched from the same folder, all stylesheets compiled together, the same with your JavaScript. This also means that you don't have to include, for example, jQuery – this is included for you via the jQuery Rails plug-in. Coding in Ruby on Rails means that you get a butt load of plug-ins already written for you. Not in the Rails core (it's very clean) but as RubyGems which is a kind of packaging for Ruby. For example, you could have plug-ins for pagination, search engine optimization, or image processing. As of the time of writing, there are over 27,000 RubyGems to be used for free. Examples of installing plug-ins: gem 'will_paginate' # installs a pagination plugin gem 'dynamic_sitemaps' # installs a sitemap generation plugin Ruby on Rails is a great framework for creating advanced web applications writing very little code in comparison to what you get. I recommend it for almost any kind of application, and especially for prototyping. To inspire you, I created a video where I create a blog in 10 minutes using Ruby on Rails. Check it out and be sold. I also recommend the documentation section of the official Ruby on Rails site. For those of you used to Ruby on Rails, I recommend this blog post about the changes from version 3.0 to version.
http://www.codeproject.com/Articles/312486/What-is-Ruby-on-Rails-an-introduction/?fid=1677707&df=90&mpp=10&noise=3&prof=True&sort=Position&view=Quick&fr=11
CC-MAIN-2014-52
refinedweb
1,101
59.23
. General Advice If you get an error in the console, scroll to the top! The later errors are not very helpful. Look at the first one. Some of these can be really tricky to track down. As a general strategy, make small changes and test as you go. At least that way it’ll be easier to figure out which bit of code broke (like when the stack traces are not so helpful). Styles don’t seem to cascade to subcomponents by default… (this can be controlled by the encapsulationproperty… From Igor: This is a problem with polyfilling ES Modules. Something outside of Angular, and in fact a well known issue with all ES module polyfills. Once we have a native implementation you will get an error, but in the meantime if you use the TypeScript compiler you’ll get a compile time error.) EXCEPTION: Error during instantiation of UsersCmp TypeError: this.http.get(…).map is not a function I thought TypeScript was supposed to save us from TypeErrors! Removing .map fixed the error… but it seems like it should work. I don’t know too much about this new Http service so, maybe the request failed? Nope: You have to explicitly include the map operator from RxJS. Awesome. Add this line to app.ts (or whatever your main file is): import 'rxjs/add/operator/map'; For a step-by-step approach to learning React,
https://daveceddia.com/angular-2-errors/
CC-MAIN-2017-51
refinedweb
235
74.29
Mean, Variance, Standard Deviation, Standard Score, Covariance & Data Projection Variance – It is the measure of squared difference from the Mean. To calculate it we follow certain steps mentioned below: - Calculate average of numbers - For each numbers subtract the mean and square the result - Calculate the average of those squared differences i.e. Variance Example: – Suppose you have weights of 5 different persons as [88 , 34 , 56 , 73 , 62]. You need to find out Mean, Variance and Standard Deviation. Mean = (88 , 34 , 56 , 73 , 62)/5 = 62.6 Variance, Average of square of differences. Variance = ((25.4)2 + (10.4)2 + (-28.6)2 +(-6.6)2 + (-0.6)2) / 5 = 323.04 Standard Deviation, Square root of Variance Standard Deviation = (323.05)1/2 = 17.97 So, With Standard deviation we figure out the “standard” way of knowing what is normal in data and what are extra large or small values. Like in this case having a weight of 88 or 34 is extra large or too small as compared to other entities. We can expect around 68% of values within plus or minus of standard deviation. Here 3 out of 5 data points are within 1 standard deviation i.e. 17.97 and 5 out of 5 are within 2 standard deviation i.e. 17.97*2 = 35.94 In General what we figure out from the concept pf standard deviation is as follow- - likely to be within 1 standard deviation (68 out of 100 sample points) - very likely to be within 2 standard deviation (95 out of 100 sample points) - almost certainly to be within 3 standard deviation (97 out of 100 sample points) Standard Score or Standardization Standardization is process of generating standard normal distribution of data. We need to first transform the data in a way that its mean becomes 0 and standard deviation is 1. Steps are as follows- - First subtract the mean - Then divide by standard deviation z = standard score x = value to be standardised µ = mean of data points σ = standard deviation Why Standardize ? Standardization helps in making decisions about a set of data by creating uniform distribution around the mean. Example: – Suppose there is a test conducted and students get marks out of 50 as follows- 22,17,28,30,20,26,37,16,26,22,19 Most of the student are below 25 so most will fail as per conventional assumptions. As test is quite hard so decision can be made using standardise data by failing those who are 1 standard deviation below the mean. Here the mean is 24 and standard deviation is 5.96, which results into following standard score. -0.33, -1.17 , 0.67, 1.00, -0.67 , 0.33 , 2.18 , -1.34 , 0.33, -0.33, -0.83 The information that we gather are following- - Out of total 11 samples 7 are within 1 standard deviation 10 are within 2 standard deviation and 11 i.e. all samples are within 3 standard deviation. - Only two student will fail with standard score -1.17 and -1.34 as they are below the mean by standard deviation 1. This process makes calculation much easier as we need only one table which is Standard normal distribution, rather than individual calculations for each value of mean and standard deviation. Covariance Suppose we are having data sample with 3 features than Covariance matrix show how similar the variances of the features are ? Our data samples represented by X with 3 features x1, x2, x3. The features had been transformed in a way that their mean becomes zero. i.e. x1 = x1 – mean(x1), x2 = x2 – mean(x2), x3 = x3 – mean(x3) standard normal distribution. Now we need to calculate covariance matrix using X which is the similarity between the features. We know to figure out similarity we can use dot product. We can represent the procedure as follow. The matrix generated is meant to give us certain information as listed below. - (XTX)ij represents similarity of change of ith and jth feature but using this procedure will let us deal with huge number as dimension increases. - So, we divide it by n to solve the problem, which gives us result like below: Cov(X) = (XTX) / n It shows that ith and jth row of a covariance matrix shows the co(variance) of the ith and jth features Let’s take an example to understand it. Suppose there are two stocks A and B and we are having data of their daily return as follows. Now we will calculate the average return of each stock. Average, A = (1.1+1.7+2.1+1.4+0.2) / 5 = 1.30 Average, B = (3+4.2+4.9+4.1+2.5) / 5 = 3.74 To calculate covariance, we take take products differences between return of A and the average calculated and the difference of B from its average calculated. i.e. Covariance = ∑((Return of A – Average of A) * (Return of B – Average of B)) / Sample size = ([(1.1 – 1.30) * (3 – 3.74)] + [(1.7 – 1.30) * (4.2 – 3.74)] + [(2.1 – 1.30) * (4.9 – 3.74)] + ……)/5 = 2.66 / 5 = 0.53 The Covariance calculated is a positive number which indicates both returns are in same direction. i.e. When A is having high return B is also having a high return. Example of Covariance and Scaling: – Consider a data with two features defined as x and y as follow. import numpy as np import matplotlib.pyplot as plt plt.style.use('ggplot') # Normal distributed x and y vector with mean 0 and # standard deviation 1 x = np.random.normal(0, 1, 500) y = np.random.normal(0, 1, 500) X = np.vstack((x, y)).T plt.scatter(X[:, 0], X[:, 1], color = 'red') plt.title('Generated Data') plt.axis('equal') plt.show() # Covariance def cov(x, y): xbar, ybar = x.mean(), y.mean() return np.sum((x - xbar)*(y - ybar))/(len(x) - 1) # Covariance matrix def cov_mat(X): return np.array([[cov(X[0], X[0]), cov(X[0], X[1])], \ [cov(X[1], X[0]), cov(X[1], X[1])]]) print(cov_mat(X.T)) [[ 0.9904346 , -0.04658066], [-0.04658066, 0.83919946]] It shows covariances of column x and y. Now we well transform our data to make it uncorrelated by using a scaling matrix as mentioned below. # Center the matrix at the origin X = X - np.mean(X, 0) # Scaling matrix sx, sy = 5, 1 Scale = np.array([[sx, 0], [0, sy]]) print(Scale) #Output [[5, 0], [0, 1]] # Apply scaling matrix to X Y = X.dot(Scale) plt.figure(figsize=(9,6)) plt.scatter(Y[:, 0], Y[:, 1],color='green') plt.title('Transformed Data') plt.axis('equal') # Calculate covariance matrix print(cov_mat(Y.T)) The Covariance matrix of transformed data shows that x and y are now uncorrelated with Covariance values close to zero and variance for x and y are enhanced upto 24.76 and 0.839. Introduction to Projection of Vector Suppose there is a Line L and and vector X needs to be projected over L. Then vector on L represented by perpendicular from vector X on L is known as projection of Vector X over L i.e. Some vector in L where [vector(X) – Proj L V(X)] is orthogonal to L. Scaler Projection of a Vector Vector Projection over a Line Here the magnitude of projection is 7/5 over the line L and the direction of projection will be observed by vector [2.8 , 1.4]. Note: – In case of PCA we use magnitude of projection over eigenvector. For Detailing of Eigenvector and Eigenvalues Click Here One thought on “Mean, Variance, Standard Deviation, Standard Score, Covariance & Data Projection” Luckily for Alice, the little magic bottle had now had its full effect, and she grew no larger: still it was very uncomfortable, and, as there seemed to be no sort of chance of her ever getting out of the room again, no wonder she felt unhappy.
http://indianaicouncil.org/mean-variance-standard-deviation-standard-score-covariance-projection-eigenvalues-and-eigenvectors/
CC-MAIN-2021-43
refinedweb
1,338
64.71
35307/creating-aws-elasticache-redis-readreplica-in-ec2-instance import boto3 ec2 = boto3.resource('ec2') instance = ec2.create_instances( ...READ MORE Hey @Vanshika there could be many factors ...READ MORE You could always use the Amazon RDS ...READ MORE No, you don't need an Elastic IP address for ...READ MORE AWS ElastiCache APIs don't expose any abstraction ...READ MORE Hi, Here for the above mentioned IAM user ...READ MORE Check if the FTP ports are enabled ...READ MORE To connect to EC2 instance using Filezilla, ...READ MORE Yes, the general limit for creating on-demand ...READ MORE Try launching the Instance using CLI or ...READ MORE OR At least 1 upper-case and 1 lower-case letter Minimum 8 characters and Maximum 50 characters Already have an account? Sign in.
https://www.edureka.co/community/35307/creating-aws-elasticache-redis-readreplica-in-ec2-instance?show=37533
CC-MAIN-2021-49
refinedweb
131
70.19
In this android tutorial we are going to learn how to create an android dictionary application with Search Suggest and Text to Speech feature. The android application can be used in defining terms or words use in a particular field. You can found an example of Biology Dictionary I built in one of my apps in the Google Play Store. The app will consist of different words and their meaning. When a word is selected, it will display the definition or meaning of the word with an option to convert it to speech. The app will also has a search functionality with integrated search suggestion. When a user type in two characters the search box will display all the words that contain the type in characters. If you still don’t understand what search suggest means you can read my post on Android ListView with EditText Search Filter We will start by designing android SQLITE database that will house our data. There are different ways we can use to create our database. In this tutorial, I am going to use a SQLITE Manager to create and manager the database file. The database will be create using SQLite Expert Professional Manager which is a paid software but there are many free to use SQLite Manager you can get online and use. I will go ahead and create a database called dictionary. Now, we have to create a table inside our database called dictionary. The table will have three columns – id, word and meaning. The SQLite code for the table is shown below. Create Table [dictionary] ( [_id] INTEGER PRIMARY KEY, [word] TEXT, [meaning] TEXT ) Before we start, the first thing I will do is to list the environment and tools I used in this android tutorial: AndroidDictionaryApplication Package: com.inducesmile.androiddictionaryapplication Keep other default selections. Continue to click on next button until Finish button is active, then click on Finish Button Once you are done with creating your project, make sure you change the package name if you did not use the same package. SQLITE Database We will start from the backend and build the application to finish. The first thing we will do is to create a folder called databases inside assets folder. Since we created our SQLite database file using SQLite database manager, we will drag and drop the file inside the databases folder and zip. We are preparing our database file this way since we are going to use a third party library called android sqlite asset helper. This library will help us to create and manage your database file. You can read more about this library here The next to do is the import the library to our project. Since the library makes use of gradle, just open your build.gradle file and copy and paste the code below under the dependence section. compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:+' Now you can build your project and the library will be added automatically to your project. If you are using Eclipse for you android development, you can search on how to import library inside android project. We will go ahead with the SQLite database code now that we have finished setting up our database library. We will create three different files – DictionaryDatabase.java, DatabaseObject.java and DbBackend.java. The DictionaryDatabase java class will inherit from SQLiteAssetHelper which is a class from our imported library. We will define our database name and version. The version number is use to control our application database update. Whenever there is a change in the database file, the version number will be updated. The code sample is shown below. Copy and paste it to your project file. package inducesmile.com.androiddictionaryapplication; import android.content.Context; import com.readystatesoftware.sqliteasset.SQLiteAssetHelper; public class DictionaryDatabase extends SQLiteAssetHelper { private static final String DATABASE_NAMES = "quiz"; private static final int DATABASE_VERSION = 5; public DictionaryDatabase(Context context) { super(context, DATABASE_NAMES, null, DATABASE_VERSION); // TODO Auto-generated constructor stub } } We are going to establish a connection for our database and return the instance of our database in DatabaseObject.java file. An instance of the DictionaryDatabase is created and the getReadableDatabase of the class is used to get the connection object. The getter and close methods in the class is used to return and close the database connection. The code for this class is shown below. package inducesmile.com.androiddictionaryapplication; import android.content.Context; import android.database.sqlite.SQLiteDatabase; public class DbObject { private static DictionaryDatabase dbHelper; private SQLiteDatabase db; public DbObject(Context context) { dbHelper = new DictionaryDatabase(context); this.db = dbHelper.getReadableDatabase(); } public SQLiteDatabase getDbConnection(){ return this.db; } public void closeDbConnection(){ if(this.db != null){ this.db.close(); } } } Finally, to finish up with our backend, will create two queries in DbBackend.java file which will be use to retrieve data from our SQLite database. The code is shown below. package inducesmile.com.androiddictionaryapplication; import android.content.Context; import android.database.Cursor; import java.util.ArrayList; public class DbBackend extends DbObject{ public DbBackend(Context context) { super(context); } public String[] dictionaryWords(){ String query = "Select * from dictionary"; Cursor cursor = this.getDbConnection().rawQuery(query, null); ArrayList<String> wordTerms = new ArrayList<String>(); if(cursor.moveToFirst()){ do{ String word = cursor.getString(cursor.getColumnIndexOrThrow("word")); wordTerms.add(word); }while(cursor.moveToNext()); } cursor.close(); String[] dictionaryWords = new String[wordTerms.size()]; dictionaryWords = wordTerms.toArray(dictionaryWords); return dictionaryWords; } public QuizObject getQuizById(int quizId){ QuizObject quizObject = null; String query = "select * from dictionary where _id = " + quizId; Cursor cursor = this.getDbConnection().rawQuery(query, null); if(cursor.moveToFirst()){ do{ String word = cursor.getString(cursor.getColumnIndexOrThrow("word")); String meaning = cursor.getString(cursor.getColumnIndexOrThrow("meaning")); quizObject = new QuizObject(word, meaning); }while(cursor.moveToNext()); } cursor.close(); return quizObject; } } Activity_Main.xml The back-end code for database interaction is done, we will move ahead to create our main application. The main layout of our application will contain a ListView and an EditText. You can drag and drop the View controls to the project activity_main.xml. The xml code snippet for the <ListView android: </RelativeLayout> Some string associated with the View names are placed in the string.xml file. The updated code is shown below. <resources> <string name="app_name">AndroidDictionaryApplication</string> <string name="hello_world">Hello world!</string> <string name="action_settings">Settings</string> <string name="title_activity_dictionary">DictionaryActivity</string> <string name="text_to_speech">Convert Text to Speech</string> </resources> MainActivity.java In the MainActivity.java file, we will get the instances of our View controls (ListView and EditText Views). We create an object of the DbBackend class and call its method dictionaryWords() which will return all the words stored in the database. We create an ArrayAdapter and pass String array as parameter, the android default ListView layout. The ListView instance uses the ArrayAdapter class for its own adapter. ItemClickListener event listener is attached to the ListView so that when a ListView item is clicked, it will transfer its id value to DictionaryActivity class. The code of the MainActivity.java is shown below. package inducesmile.com.androiddictionaryapplication; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.text.Editable; import android.text.TextWatcher; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; public class MainActivity extends ActionBarActivity { private EditText filterText; private ArrayAdapter<String> listAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); filterText = (EditText)findViewById(R.id.editText); ListView itemList = (ListView)findViewById(R.id.listView); DbBackend dbBackend = new DbBackend(MainActivity.this); String[] terms = dbBackend.dictionaryWords(); listAdapter = new ArrayAdapter<String> Toast.makeText(getApplicationContext(), "Position " + position, Toast.LENGTH_LONG).show(); Intent intent = new Intent(MainActivity.this, DictionaryActivity.class); intent.putExtra("DICTIONARY_ID", position); startActivity(intent); } }); filterText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { MainActivity.this.listAdapter.getFilter().filter(s); } @Override public void afterTextChanged(Editable s) { } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu); } } Activity_Dictionary.xml Just like in our main layout, we are going to add three View Controls in our activity_dictionary.xml file. 1. A TextView that will hold the word we will look-up its meaning 2. A View that we will use to create a horizontal demarcation line 3. A TextView that will hold the meaning of our search word. 4. A Button View for word to speech conversion. The xml <TextView android: <View android: <TextView android: <Button android: </RelativeLayout> DictionaryActivity.java We will finish up the project by writing the code that will let us display the terms and the definition of the terms. We will follow the steps we used in MainActivity.java file by getting the instances of our View controls. We have to create an instance of the TextToSpeed class which implements onInit callback method that signify when the TextToSpeech engine is ready to be used. The TextToSpeech object is instantiated inside the button’s event listener and the speak method is called on the object. The code for the class is shown below. package inducesmile.com.androiddictionaryapplication; import android.annotation.TargetApi; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.speech.tts.TextToSpeech; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.util.Locale; public class DictionaryActivity extends ActionBarActivity { private TextView wordMeaning; private TextToSpeech convertToSpeech; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dictionary); Intent intent = getIntent(); Bundle bundle = intent.getExtras(); int dictionaryId = bundle.getInt("DICTIONARY_ID"); int id = dictionaryId + 1; TextView word = (TextView)findViewById(R.id.word); wordMeaning = (TextView)findViewById(R.id.dictionary); Button textToSpeech = (Button)findViewById(R.id.button); DbBackend dbBackend = new DbBackend(DictionaryActivity.this); QuizObject allQuizQuestions = dbBackend.getQuizById(id); word.setText(allQuizQuestions.getWord()); wordMeaning.setText(allQuizQuestions.getDefinition()); textToSpeech.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String convertTextToSpeech = wordMeaning.getText().toString(); convertToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() { @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void onInit(int status) { if(status != TextToSpeech.ERROR){ convertToSpeech.setLanguage(Locale.US); convertToSpeech.speak(convertTextToSpeech, TextToSpeech.QUEUE_FLUSH, null, null); } } }); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_dictionary,); } @Override protected void onPause() { if(convertToSpeech != null){ convertToSpeech.stop(); convertToSpeech.shutdown(); } super.onPause(); } } Save the file and run your project. If everything works for you, the project will appear like this in your device. You can download the code for this tutorial below. If you are having hard time downloading the tutorials, kindly contact me. Remember to subscribe with your email so that you will be among the first to receive our new post once it is published hi henry. wonderful tut. please im thinking of developing my own dic app. but i want to ask how will i input the words into the mysqli db? manually? thanks bro. God bless you for all the help rendered so far……..p.s when does your next beginners competition code start? Search SQLite Manager software online and you can get a free one to use. Check also a chrome extension that you can use to do it. Let me know if you have more questions. Fine tutorial. I completed the tutorial but i faced challenge on retrieving the contents when the new window appears whilst typing on searchview. Incorrect view is been retreived. How can l manage this. Thank you Please can you make your question clearer. I did not fully understood it. I have error when I click zygote,it shows the meaning of abdomen. And other words show same error. please help me I mean that after filter zygote,when click zygote it show abdomen meaning . public class QuizObject { private String word; private String definition; public QuizObject(String word, String definition) { this.word = word; this.definition = definition; } public String getWord() { return word; } public void setWord(String word) { this.word = word; } public String getDefinition() { return definition; } public void setDefinition(String definition) { this.definition = definition; } } I have been using your source code, but I still found the problem (when I type “H” and the search list appears, then I click Antidiuretic Hormone that appears is the abdomen). Can you fix this issue? Thanks for the observation. I will fix the bug when I have a little time but if you want to do it yourself it is simple. You should use the table id instead of adapter position to retrieve words and meaning. Hello Henry, I’m having the same issue. I tried changing position to Id but no luck. Any idea how i can fix it? Thanks Nice tutorial, but how i replace sqlite database file with my own file? Bcoz even if i remove your file still the app fetches data from your database. Why so? Any help will be appreciated. Thanks. You can replace the sqlite database file with you own file but make sure that it is the same name. If you want to change your database filename then you must also change the name in the database java file. Please remember to uninstall the application and install a fresh copy before you test it. Hi sir, thanks for your reply. I will work on that. I also contacted you for code services but you didn’t reply. I’m trying to develop a Thesaurus app but i’m stuck with some issues. Thanks in advance. I removed your email from the message. I have contacted your through the email you provided. Thanks hello sir! i’m having a problem with the editText search functionality can you please tell me which code should i look into, as u have mentioned earlier we have to use ID instead of POSITION in search so please let me know how to fix it!! thanks in advance you are doing a great work here bro i admire you work. 🙂. Hello people i have fixed the search bug if you want to know it you can tell me. @Shahbaz may you please tell me how you fixed the search bug. How to fix it? I try but i cant do it. Let me know. My mail = bluemr(at)fejm.pl. Thanks! Need your fix, bro! My edits: link to screenshot code in mainactivity listAdapter = new ArrayAdapter String word = listAdapter.getItem(position); // Toast.makeText(MainActivity.this, terms2, Toast.LENGTH_SHORT).show(); String[] words = dbBackend.dictionaryWords(); for(int i=0; i < words.length; i++) if(words[i].contains(word)) position = i; Toast.makeText(MainActivity.this, word + " " +position , Toast.LENGTH_SHORT).show(); Intent intent = new Intent(MainActivity.this, DictionaryActivity.class); intent.putExtra("DICTIONARY_ID", position); startActivity(intent); } }); Hovewer it stops working on word Photomorphogenesis 218 id. It crashes on this word, but next words are ok (with +1 id). I dont know whats wrong with it. May be its too long charachters…I have my own db with 103 words in Ukrainian. It works just fine with them. Something must be wrong with that row in your database table. You can look inside the table and see. Also check if you are returning an id value before navigating to the next activity page. Just tested your db with app from post with no edits.. Try to navigate to this word and click. App is crashing. Id returns well. With your db id after Photomorphogenesis becomes +1. Like we have no id on that word. Magic. I tried just another db – everything works well Have you guys fixed the search bug? //replace with this code. //hope the search issue will be solved. //it worked for me. itemList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { // make Toast when click String itemName = (String) parent.getItemAtPosition(position); int position_fo_item = Arrays.asList(terms).indexOf(itemName); Toast.makeText(getApplicationContext(), “position ” + (position_fo_item), Toast.LENGTH_LONG).show(); Intent intent = new Intent(MainActivity.this, DictionaryActivity.class); intent.putExtra(“DICTIONARY_ID”,position_fo_item); startActivity(intent); } }); @Shahbaz, plz let me know the search & view bug resolution, tried several things but didnt work Can you tell me to how to fix the search problem?? @mohd shahbaz may you please tell me how you fixed the search bug Henry can you fix this search bug? I try but I can’t do it by myself. Thanks! Sir, I have a problem. After I install the apk in my phone, I can’t run the application. It says “it suddenly stopped”. How can I fix this? I need to see the logcat message to understand the problem. We’re can I upload the screenshot of the logcat sir? And I wanna also ask what minimum android version does this code works? You can just add the Image file you want to use in your project drawable folder. I will make the changes later. Thanks I don’t seem to understand sir. I’m sorry for that. But thank you for understanding and cooperating. We’re can I upload the screenshot of the logcat sir? And I wanna also ask what minimum android version does this code works? You can send it to me. Thanks Sir I finally got the system work. thank you very much. But I have a problem with the database. It uses a biology database not a dictionary database. How can I fix that sir? I would also like to change the database with my own database. Can you please teach me that? It would be a great help for my school project. Thank very much in advance sir. I have explained the concept in the comment section. I will fix it when I have some free time.. No, you are not being annoying. We learn through asking questions about what we don’t understand. Back to your question To change the database file, go to your project assets folder. Inside the folder, there is another folder name databases. Inside the databases folder is where the sqlite database file is. You can open the database file in any SQLite Manager Software or you can create a new database file with the same name. You can check DB Browser for SQLIte. That is the software I use all the time. If you want to rename the database file then you can create a new database file and name it whatever you want. Then go to the file named DictionaryDatabase.java . Inside the Class, you will see the class variable DATABASE_NAMES. Replace the old database filename with the new name. Finally, you need to uninstall and install a fresh copy of the application. Test it and get back to me if it works for you. Thank for your understanding sir! I finally got it. I’ve successfully changed the database. The only problem left is the search engine. For the search, try and get the id value of each word from the database and add it in the Intent Extra. When you navigate to the details activity page, you should use the id of the selected work to search the database. In this case you will always return the correct meaning of the word you are searching. I hope this will be of help to you. Thank you Sir, it helped a lot! It’s already working. =) Sir have u fix the bug, if u have please tell me how to fix it, can u give me the example to fix it, thanks before Sorry, I am busy now. Once I have time I will fix it and let you know? Sir, I am new to android software development and new to this site. I want to create a dictionary like app with search function from the content of a pdf book and its index. Is it possible to get it work with your source code here in ANDROID DICTIONARY APP SOURCE CODE FOR $5. By editing the .db file in SQLITE Database Manager. Can you give some simple instruction on how to edit the .db file with my own content. Sorry for asking here in this section. I couldn’t find comment box on that section. How can I comment and contact for that section?. I really need this kind of dictionary. please help me . when i run your app . befor any chang . i got this errors. E/SQLiteLog: (1) no such column: _id Caused by: android.database.sqlite.SQLiteException: no such column: _id (code 1): , while compiling: select * from dictionary where _id = 1 As you can see the problem is from the column _id. To fix it, you can create your own database file and replace the old database file. You can go through the comment section to see how to create a new database if you don’t know. Get back to me if you have more questions. sir , i changed the database . but i have one problem in search engine . when i chose word the app give me another word . Go through the comment you will see how you can fix it.? It is a string. You can use subString() method to cut off the first part of the string. I hope you understand it How to do this sir? I don’t know how to use subString() method. Please just google who to use subString() in java then if you still don’t understand it you can get back to me hello dear, it’s best tutorial ever thank you so much… but i want to add favourite list, how can i create favourite list ? please help me best regards It involves more to do. But you can create a table in the database where you can store user favorites when a user click on the favorite icon. can you explain more please how can i store data into database? what should i store into fav table just id or all of them? Thank you for your source code. I have the same problem as other developers have above. When I search a word and click on it, it shows word of position 0. means it always show first word. I have created my own database. Please help. Thanks This is very perfect tutorial. But I have a question! In Squl database, Myanmar Font won’t appear..just see small blocks..! How to solve it? Thanks a lot for ur sharing. Sorry, I did not understand your question. Thanks Hello Henry, Please I need your help on the app am developing which is similar to this dictionary app so would you mind text me on this email sandrinesangwa@yahoo.com so that we can discuss about it. Sir! I have followed all the steps given by you in developing this dictionary app. There are no errors, but when I run the application in emulator it is not opening and giving a message “Dictionary Application has stopped”. Sir, I’ve checked everything but not able to find a solution for this problem. I would be grateful if you could please help me! Thank you! Hello, Henry! Sorry for my English, my bad. How can you make Your app category, according to the letters. Clicked on the letter and will only display words that begin with that letter. Further search in this category. Here is a link to a picture about how it should work. Здравствуйте, Henry! Извините за мой английский, я плохо говорю. Как можно сделать в Вашем приложении категории, по буквам. Нажал на букву и будут отображаться только те слова которые начинаются на эту букву. Далее уже поиск в этой категории. Вот ссылка на картинку как примерно должно работать. Hi sir, Thank you very much for your tutorial. I have never thought that I would be able to create my own dictionary app with your help. After reading and testing with the above codes, I found an issue in my project. I am developing a biology database with more words than in example quiz database. There are several words contained in another word. For eg, the word “mening” is an individual word with own definition. But, when I search and click on that “mening”, it’s related word “pachymeningitis” is shown.I don’t have any clue why this is happening.If you could be help me to figure out the cause, it would be greatly appreciated. Hi, Is there anyway to change the package name? Yes, just search in google you will see some examples on how to change android project package name Hello Henry, this is a nice tutorial! i want to try to build a dictionary with 2 different tables, but the problem is, that tables have different start id, first table start with id = 1, and the second table start with id =3, my question is, how do i get the dictionary id if the starting id is different from this two tables? i’ll appreciate any answer You can use the database table id rather than the reccylerview or list adapter item position
https://inducesmile.com/android/android-dictionary-application-with-search-suggest-and-text-to-speech/
CC-MAIN-2019-35
refinedweb
4,164
60.61
Scons doesn't build a simple D program on OSX I get an error when I try to use Scons to create a simple D file. I tested scons by building a simple helloworld.c, but the equivalent in D just doesn't happen and I'm not smart enough about Scons to know if it's a bug or a problem with my setup. The error I am returning is ld: library not found for -lphobos My SConstruct file: SConscript('SConscript', variant_dir='release', duplicate=0, exports={'MODE':'release'}) SConscript('SConscript', variant_dir='debug', duplicate=0, exports={'MODE':'debug'}) My SConscript file: env = Environment() env.Program(target = 'helloworld', source = ['hello.d']) hello.d import std.stdio; void main() { writeln("Hello, world!"); } EDIT: Full scons output: MyComputer:thedbook me$ scons scons: Reading SConscript files ... scons: done reading SConscript files. scons: Building targets ... scons: building associated VariantDir targets: release debug gcc -o debug/helloworld debug/hello.o -L/usr/share/dmd/lib -L/usr/share/dmd/src/druntime/import -L/usr/share/dmd/src/phobos -lphobos -lpthread -lm ld: library not found for -lphobos collect2: ld returned 1 exit status scons: *** [debug/helloworld] Error 1 scons: building terminated because of errors. The reason I'm puzzled is that file creation is usually dead easy (that's one thing with the helloworld file): dmd hello.d -v binary dmd version v2.058 config /usr/bin/dmd.conf parse hello importall hello <significant amount of imports here> ... code hello function D main function std.stdio.writeln!(string).writeln function std.stdio.writeln!(string).writeln.__dgliteral834 function std.exception.enforce!(bool,"/usr/share/dmd/src/phobos/std/stdio.d",1550).enforce gcc hello.o -o hello -m64 -Xlinker -L/usr/share/dmd/lib -lphobos2 -lpthread -lm Note that I had to include verbosity in the compiler to show it anything. He was usually silent and linked the file. source to share After I figured out what the message gave me thanks to the comment, I played around with the config files a bit and got the result I wanted. I feel like this is a workaround that undermines the "cruise control" that Sconsers is going to do, but I have a build so I can't complain. I had to change my SConscript file like this: env = Environment() target = 'helloworld' sources = ['hello.d'] libraries = ['phobos2', 'pthread', 'm'] libraryPaths = ['/usr/share/dmd/lib', '/usr/share/dmd/src/druntime/import', '/usr/share/dmd/src/phobos'] env.Program(target = target, source = sources, LIBS = libraries, LIBPATH = libraryPaths) The key change here is the addition of LIBS and explicitly defining which libraries to include, rather than relying on SCons to figure it out. Unfortunately, the moment you add it, you must explicitly link them all. However, I hope this helps anyone looking to get up and running quickly with D and SCons. source to share
https://daily-blog.netlify.app/questions/1896157/index.html
CC-MAIN-2021-43
refinedweb
474
50.02
Why you should use column-indentation to improve your code’s readability . Four examples of improvements using code indentation First example Take a look at this code: The readability is not so good, and you could end up with something like this to avoid the mess: And your seven lines have turned into almost 40 lines. This with just three or four properties per object. If it was eight properties, it would become 70 lines. The idea that I’m talking about is to use something like this (I call it “column- indented” code): Second example It’s not just for object literals. It can be used for any piece of code that is a group of similar lines. This process can be quick. You can copy the first line, paste it, and then overwrite the changing pieces in each line. It can be used in JS import too. Compare these two versions: These thirteen imports are alphabetically ordered by the path. All of them are from the vs folder — five from vs/base and eight from vs/platform. You can’t see that without moving your eyes back and forth across each line. Doing this is annoying. Of course, you don’t need to make statistics about how your files are importing others. But at some time you will read this code to see if you imported something from the correct file, or if a file was already imported. Now see how it looks when the same code is column-indented: Doesn’t that make it a little better? Third example In this example, we have a method declaration from TypeScript compiler: Again, you can see the difference between the lines more easily. It helps you to read all the five lines at the same time, spending way less effort. And, if you need to add a parameter in each of these 5 lines, you can do it just one time, using the multiline cursor in almost all code editors. Fourth example Here is the final example, with the original and comparison together: Pros: - Your code looks cleaner. - Your code has improved readability - You may be able to reduce the number of lines in your code Cons: - The auto-formatting option of code editors can interfere with the layout - When adding one line to a block of lines, sometimes you have to change all the other lines - It can be time-consuming to write code What tools can help to achieve this? I did indentation this way, manually, for some time. It’s boring, but once you start doing it, you can’t stop. You look at your code, all those repeated lines that could be column-indented to be more readable, and you can’t go on without doing it. It’s addictive. I use Visual Studio and Visual Studio Code, so I tried to find an extension or plugin that helps achieve this. I didn’t find any. So in November 2017 I started to create my own extension for Visual Studio Code and named it Smart Column Indenter. I published a first usable version in the same month. Take a look at how it works: There are areas where the extension could be improved. Currently, it only works with *.ts, *.js and *.json files. I think that it could help with XML and HTML files too, like column-indenting the same attributes of repeated tags, or different tags that are repeated in a group of lines. Once the code is selected for column-indentation, the algorithm works in three steps: - Lexical analysis (or tokenization) of the code. I installed the TypeScript npm package as a dependency and used the Compiler API to avoid reinventing the wheel here. - Execute the Longest Common Subsequence (LCS) algorithm passing each line of code as a sequence of tokens. This is the hard part. A lot of references on the internet talk about the LCS for just two sequences as input, which is easily solved with dynamic programming. As we usually want to column-indent more than two lines of code, the problem becomes finding the longest common sequence (LCS) of multiple strings. This is a NP-hard problem. As this is a generic problem, I created a separated npm package (multiple-lcs) with a basic implementation to accomplish this. It isn’t the best solution in some cases, but it is workable. - Rewrite the code to column-indent the tokens that appear in the LCS. Each token in the LCS is placed in a new column. For some types of tokens, such as strings or variables names, the type name is used instead the content in the LCS algorithm. The result is a larger sub-sequence. I put all the logic in a separate npm package (smart-column-indenter). If you want to create an extension or plugin like this for another JavaScript-based IDE, you can use this package. My initial reason to create this solution was proof-of-concept. I would like to know what other programmers think about my solution. If you liked it, please clap. If you have constructive criticism, or know of other tools that do the same thing, please leave a comment. This is an article that I found useful. Thanks for reading. Update (2018–03–29): After it was published a few days ago, I got a lot of feedback, most of them are negatives, but thank you all anyway, it’s good to know why a lot of people don’t like it. I found out later that people usually call it “code alignment”, you won’t find anything about “column indentation”, so if you want to search more about this, search for “code alignment” instead. I did it, and I found an interesting blog post from Terence Eden’s Blog, as most of the negative comments are about issues with VCS merges, history and dirty diffs, I’ll copy his conclusion: “If our tools make understanding those ideas more difficult, it’s the tools which need to change — not us.” Update (2018–05–03): As if someone at GitHub team had read the negative comments about code alignment here, now you can ignore white spaces in code review. Update (2018–05–20): If you use Visual Studio (not Code), Shadman Kudchikar made a similar extension, you can read about it here or download it here. Factoid We have now 22" screens with 1920x1080 resolution. There is no reason to limit yourself to 80 characters per line, although you need to decide on the maximum limit. The origin of this 80-characters limit is:
https://medium.com/free-code-camp/how-to-columnize-your-code-to-improve-readability-f1364e2e77ba?source=---------1------------------
CC-MAIN-2019-39
refinedweb
1,102
70.53
How the flatten phase works c○ Miguel Garcia, LAMP, EPFL July 4 th , 2011 Abstract flatten runs in forJVM mode because Java bytecode doesn’t accomodate nested types (unlike Microsoft’s CLR, with the caveat that a nested class in CLR is not an inner class with access to a unique outer instance, instead CLR class nesting serves namespace structuring and grants access privileges only). Given the focus of this phase, its implementation allows seeing first hand “type re-attribution” (in contrast to other phases where most of the code deals with “tree rewriting”). liftcode 8 reify trees uncurry 9 uncurry, translate function values to anonymous classes tailcalls 10 replace tail calls by jumps specialize 11 @specialized-driven class and method specialization explicitouter 12 this refs to outer pointers, translate patterns erasure 13 erase types, add interfaces for traits lazyvals 14 allocate bitmaps, translate lazy vals into lazified defs lambdalift 15 move nested functions to top level constructors 16 move field definitions into constructors /*-----------------------------------------------------------------------------*/ flatten 17 eliminate inner classes /*-----------------------------------------------------------------------------*/ mixin 18 mixin composition cleanup 19 platform-specific cleanups, generate reflective calls icode 20 generate portable intermediate code inliner 21 optimization: do inlining closelim 22 optimization: eliminate uncalled closures dce 23 optimization: eliminate dead code jvm 24 generate JVM bytecode terminal 25 The last phase in the compiler chain 1 Contents 1 On tree descent: collecting keys 3 2 On the way up 3 2.1 Eliding, Collecting trees to relocate . . . . . . . . . . . . . . . . . 3 2.1.1 It reads “object P” but it’s a ClassDef . . . . . . . . . . 4 2.1.2 Rewriting . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 2.2 Pasting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 3 Sometime later: re-typing trees 5 3.1 Idioms around TypeMap and TypeTraverser . . . . . . . . . . . . 6 3.2 TypeRef . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 3.3 ClassInfoType . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 3.3.1 Flatten-aware ClassSymbol and ModuleSymbol . . . . . . 9 3.4 The rest: MethodType, PolyType, etc. . . . . . . . . . . . . . . . 10 2 Figure 1: Sec. 1 1 On tree descent: collecting keys The structure of this transform is depicted in Figure 1. We start with the transform’s transformer, Flattener (the difference between a Transform and an InfoTransform was covered in the lazyvals write-up). Moving from root to leaves, a map is populated to hold keys for packages that can potentially hold classes to unnest (there may be no classes to unnest). override def transform(tree: Tree): Tree = { tree match { case PackageDef(_, _) => liftedDefs(tree.symbol.moduleClass) = new ListBuffer case Template(_, _, _) if tree.symbol.owner.hasPackageFlag => liftedDefs(tree.symbol.owner) = new ListBuffer case _ => } postTransform(super.transform(tree)) } Although it’s unnesting what this phase is about, the map is called liftedDefs, just like the map in lambdalift that serves a completely different purpose. private val liftedDefs = new mutable.HashMap[Symbol, ListBuffer[Tree]] 2 On the way up 2.1 Eliding, Collecting trees to relocate Before returning a Tree on the way back to the root, it’s postTransform’s chance to make a difference: • any ClassDef with isNestedClass symbol is sent into oblivion (i.e., an EmptyTree takes its place but the original tree will stay for a while in the liftedDefs map, under the key of its future home). This pattern also matches a nested “object P” as described in Sec. 2.1.1. 3 • references to a nested object are replaced with another one “after relocation” (that’s what the “atPhase(phase.next)” is for) because at that point the navigation path to reach the object will be different (with fewer Selects), and because mkAttributedRef bases the tree it builds on sym.owner.thisType. Example in Sec. 2.1.2. private def postTransform(tree: Tree): Tree = { val sym = tree.symbol val tree1 = tree match { case ClassDef(_, _, _, _) if sym.isNestedClass => liftedDefs(sym.toplevelClass.owner) += tree EmptyTree case Select(qual, name) if (sym.isStaticModule && !sym.owner.isPackageClass) => atPhase(phase.next) { atPos(tree.pos) { gen.mkAttributedRef(sym) } } case _ => tree } tree1 setType flattened(tree1.tpe) } 2.1.1 It reads “object P” but it’s a ClassDef One more detail about postTransform. The pattern case ClassDef(_, _, _, _) if sym.isNestedClass => also matches “object P” in the program below. Why? Because although parser delivers a ModuleDef for it, refchecks replaces it with a ClassDef. class C { class D object P } Quoting from refchecks: /** Eliminate ModuleDefs. * - A top level object is replaced with their module class. * - An inner object is transformed into a module var, created on first access. * * In both cases, this transformation returns the list of replacement trees: * - Top level: the module class accessor definition * - Inner: a class definition, declaration of module var, and module var accessor */ (Frequently, scalac phases can’t be understood in isolation). 2.1.2 Rewriting The case Select in Sec. 2.1 “rewrites” a tree node. For example, originally: 4 After rewriting: 2.2 Pasting Given that postTransform collected on tree descent classes for unnesting, they will be ready in liftedDefs by the time the following runs, and thus are “pasted” (“relocated” sounds better?) in their new home (a package): override def transformStats(stats: List[Tree], exprOwner: Symbol): List[Tree] = { val stats1 = super.transformStats(stats, exprOwner) if (currentOwner.isPackageClass) stats1 ::: liftedDefs(currentOwner).toList else stats1 } 3 Sometime later: re-typing trees Remember the very last line of Flattener.postTransform()? It maps the type of every tree (unnested or not) with a TypeMap (i.e., sthg that extends Function1[Type, Type]): private def postTransform(tree: Tree): Tree = { val sym = tree.symbol . . . tree1 setType flattened(tree1.tpe) } and not to forget the overload in Flatten: def transformInfo(sym: Symbol, tp: Type): Type = flattened(tp) There are four cases that flattened handles (TypeRef, ClassInfoType, MethodType, and PolyType) as covered in Sec. 3.2 to Sec. 3.4. 5 Figure 2: Sec. 3.1 3.1 Idioms around TypeMap and TypeTraverser Basically, there are TypeMaps (with an inner TypeMapTransformer, which “leaves the tree alone except to remap its types”) and TypeTraverser. Subtypes of TypeMapTransformer are used in: 1. the abstract TypeMap itself: /** Map a tree that is part of an annotation argument. * If the tree cannot be mapped, then invoke giveup(). * The default is to transform the tree with * TypeMapTransformer. */ def mapOver(tree: Tree, giveup: ()=>Nothing): Tree = (new TypeMapTransformer).transform(tree) 2. in annotationArgRewriter as part of AsSeenFromMap 3. in SubstSymMap 4. in SubstTypeMap There are too many TypeMap subclasses so we just show: There are fewer TypeTraverser subclasses, Figure 3 depicts them all. 3.2 TypeRef case TypeRef(pre, sym, args) if (pre.typeSymbol.isClass && !pre.typeSymbol.isPackageClass) => assert(args.isEmpty) /*- Scala.NET alarm: not necessarily the case (although ‘flatten‘ isn’t forMSIL, it’s still useful to track its dependencies on ‘erasure‘) */ 6 Figure 3: Sec. 3.1 assert(sym.toplevelClass != NoSymbol, sym.ownerChain) typeRef(sym.toplevelClass.owner.thisType, sym, args) 3.3 ClassInfoType Upon entry to def transformInfo(sym: Symbol, tp: Type): Type only some combinations of symbol and its type are possible: • a ModuleClassSymbol (e.g., for a package) has a type given by a ClassInfoType • a ClassSymbol may show up with a ClassInfoType or a PolyType • a MethodSymbol has always a MethodType to represent its type. • a TermSymbol goes together with a (Unique)TypeRef. It’s useful to keep in mind that both (a) what gets unnested; and (b) the new home of sthg that got unnested; well both those things, have a ClassInfoType. One more pre-requisite to understand what follows: /** A class representing a class info */ case class ClassInfoType( override val parents: List[Type], override val decls: Scope, override val typeSymbol: Symbol) extends CompoundType { . . . } Regarding the re-mapping for ClassInfoType, there are two sub-cases: 7 Figure 4: Sec. 3.3 1. a package may have become home to ClassDefs which were unnested, Therefore the package’s info’s Scope needs to include entries for those ClassDefs. 2. An unnested ClassDef N was unnested from some ClassDef C. Therefore N should not appear atPhase(phase.next) among the entries in the scope of the info of C. Both situations are handled in a single case handler: case ClassInfoType(parents, decls, clazz) => Both of the above are achieved by iterating over the decls of N, • Case 2.1: if(sym.isTerm && !sym.isStaticModule) keep it (i.e., add it to the scope being populated). • Case 2.2: if(sym.isClass) don’t enter it in the scope being populated. Instead liftClass(sym), to enter it in its now home. That’s possible because of the way ClassSymbol *overrides* owner (and, there’s more to it! Sec. 3.3.1): override def owner: Symbol = if (needsFlatClasses) rawowner.owner else rawowner case ClassInfoType(parents, decls, clazz) => var parents1 = parents val decls1 = new Scope if (clazz.isPackageClass) { /*- item (1) above */ atPhase(phase.next)(decls.toList foreach (sym => decls1 enter sym)) } else { /*- item (2) above */ val oldowner = clazz.owner atPhase(phase.next)(oldowner.info) parents1 = parents mapConserve (this) for (sym Figure 5: Sec. 3.3 // Nested modules (MODULE flag is reset so we access through lazy): if (sym.isModuleVar && sym.isLazy) sym.lazyAccessor.lazyAccessor setFlag LIFTED } else if (sym.isClass) { /*- item (2.2) above */ liftClass(sym) if (sym.needsImplClass) liftClass(erasure.implClass(sym)) } } } ClassInfoType(parents1, decls1, clazz) 3.3.1 Flatten-aware ClassSymbol and ModuleSymbol We saw needsFlatClasses in Sec. 3.3 and its effect on ClassSymbol.owner. There’s more to it (Find usages tells the whole story): /** * Returns the rawInfo of the owner. If the current phase has flat classes, * it first applies all pending type maps to this symbol. * * assume this is the ModuleSymbol for B in the following definition: * package p { class A { object B { val x = 1 } } } * * The owner after flatten is "package p" (see "def owner"). The flatten type map enters * symbol B in the decls of p. So to find a linked symbol ("object B" or "class B") * we need to apply flatten to B first. Fixes #2470. */ private final def flatOwnerInfo: Type = { if (needsFlatClasses) info owner.rawInfo } Also related to this, there’s isFlatAdjusted in ModuleSymbol (Figure 5), this time affecting ModuleSymbol’s def owner and def name behavior. 9 Listing 1: Sec. 3.4 /** A type function or the type of a polymorphic value (and thus of kind *). * * Before the introduction of NullaryMethodType, a polymorphic nullary method * (e.g, def isInstanceOf[T]: Boolean) * used to be typed as PolyType(tps, restpe), * and a monomorphic one as PolyType(Nil, restpe) * * This is now: PolyType(tps, NullaryMethodType(restpe)) and NullaryMethodType(restpe) * by symmetry to MethodTypes: PolyType(tps, MethodType(params, restpe)) and MethodType(params, restpe) * * Thus, a PolyType(tps, TypeRef(...)) unambiguously indicates * a type function (which results from eta-expanding a type constructor alias). * Similarly, PolyType(tps, ClassInfoType(...)) is a type constructor. * * A polytype is of kind * iff its resultType is a (nullary) method type. */ case class PolyType(override val typeParams: List[Symbol], override val resultType: Type) extends Type { //assert(!(typeParams contains NoSymbol), this) // used to be a marker for nullary method type, illegal now (see @NullaryMethodType) assert(typeParams nonEmpty, this) . . . 3.4 The rest: MethodType, PolyType, etc. Background on PolyType in Listing 1. case MethodType(params, restp) => val restp1 = apply(restp) if (restp1 eq restp) tp else copyMethodType(tp, params, restp1) case PolyType(tparams, restp) => val restp1 = apply(restp); if (restp1 eq restp) tp else PolyType(tparams, restp1) case _ => mapOver(tp) /*- Scala.NET alarm. For example, */ package p class C[X] { class D[Y] } /*- We said "both situations are handled with a single case handler" */ case ClassInfoType(parents, decls, clazz) => /*- but without erasure the info of a ClassDef.symbol can be a type constructor that should be handled via */ case PolyType(typeParams, resultType) => /*- (although ‘flatten‘ isn’t forMSIL, it’s still useful to track its dependencies on ‘erasure‘) */ 10
https://www.yumpu.com/en/document/view/23305499/how-the-flatten-phase-works-lamp-epfl
CC-MAIN-2019-35
refinedweb
1,934
56.15
To keep things simple though, the article doesn’t discuss how to implement database-backed web pages with Python, concentrating only on how to connect Python with MySQL. Sample Application The best way to learn new programming techniques is to write an application that exercises them. This article will walk you through the process of building a simple Python application that interacts with a MySQL database. In a nutshell, the application picks up some live data from a web site and then persists it to an underlying MySQL database. For the sake of simplicity, it doesn’t deal with a large dataset. Rather, it picks up a small subset of data, storing it as a few rows in the underlying database. In particular, the application gets the latest post from the Packt Book Feed page available at. Then, it analyzes the post’s title, finding appropriate tags for the article associated with the post, and finally inserts information about the post into the posts and posttags underlying database tables. As you might guess, a single post may be associated with more than one tag, meaning a record in the posts table may be related to several records in the posttags table. Diagrammatically, the sample application components and their interactions might look like this: Note the use of appsample.py. This script file will contain all the application code written in Python. In particular, it will contain the list of tags, as well as several Python functions packaging application logic. Software Components To build the sample discussed in the article you’re going to need the following software components installed on your computer: - Python 2.5.x - MySQLdb 1.2.x - MySQL 5.1 All these software components can be downloaded and used for free. Although you may already have these pieces of software installed on your computer, here’s a brief overview of where you can obtain them. You can download an appropriate Python release from the Downloads page at Python’s web site at. You may be tempted to download the most recent release. Before you choose the release, however, it is recommended that you visit the Python for MySQL page at to check what Python releases are supported by the current MySQLdb module that will be used to connect your Python installation with MySQL. MySQLdb is the Python DB API-2.0 interface for MySQL. You can pick up the latest MySQLdb package (version 1.2.2 at the time of writing) from the sourceforge.net’s Python for MySQL page at. Before you can install it, though, make sure you have Python installed in your system. You can obtain the MySQL 5.1 distribution from the mysql.com web site at, picking up the package designed for your operating system. Setting up the Database Assuming you have all the software components that were outlined in the preceding section installed in your system, you can now start building the sample application. The first step is to create the posts and posttags tables in your underlying MySQL database. As mentioned earlier, a single post may be associated with more than one tag. What this means in practice is that the posts and posttags tables should have a foreign key relationship. In particular, you might create these tables as follows: CREATE TABLE posts ( title VARCHAR(256) PRIMARY KEY, guid VARCHAR(1000), pubDate VARCHAR(50) ) ENGINE = InnoDB; CREATE TABLE posttags ( title VARCHAR(256), tag VARCHAR(20), PRIMARY KEY(title,tag), FOREIGN KEY(title) REFERENCES posts(title) ) ENGINE = InnoDB; As you might guess, you don’t need to populate above tables with data now. This will be automatically done later when you launch the sample. Developing the Script Now that you have the underlying database ready, you can move on and develop the Python code to complete the sample. In particular, you’re going to need to write the following components in Python: - tags nested list of tags that will be used to describe the posts obtained from the Packt Book Feed page. - obtainPost function that will be used to obtain the information about the latest post from the Packt Book Feed page. - determineTags function that will determine appropriate tags to be applied to the latest post obtained from the Packt Book Feed page. - insertPost function that will insert the information about the post obtained into the underlying database tables: posts and posttags. - execPr function that will make calls to the other, described above functions. You will call this function to launch the application. All the above components will reside in a single file, say, appsample.py that you can create in your favorite text editor, such as vi or Notepad. First, add the following import declarations to appsample.py: import MySQLdb import urllib2 import xml.dom.minidom As you might guess, the first module is required to connect Python with MySQL, providing the Python DB API-2.0 interface for MySQL. The other two are needed to obtain and then parse the Packt Book Feed page’s data. You will see them in action in the obtainPost function in a moment. But first let’s create a nested list of tags that will be used by the determineTags function that determines the tags appropriate for the post being analyzed. To save space here, the following list contains just a few tags. You may and should include more tags to this list, of course. tags=["Python","Java","Drupal","MySQL","Oracle","Open Source"] The next step is to add the obtainPost function responsible for getting the data from the Packt Book Feed page and generating the post dictionary that will be utilized in further processing: Now that you have obtained all the required information about the latest post on the Packt Book Feed page, you can analyze the post’s title to determine appropriate tags. For that, add the determineTags function to appsample.py: def determineTags(title, tagslist): curtags=[] for curtag in tagslist: if title.find(curtag)>-1:curtags.append(curtag) return curtags By now, you have both the post and tags to be persisted to the database. So, add the insertPost function that will handle this task (don’t forget to change the parameters specified to the MySQLdb.connect function for the actual ones): def insertPost(title, guid, pubDate, curtags): db=MySQLdb.connect(host="localhost",user="usrsample",passwd="pswd",db="dbsample") c=db.cursor() c.execute("""INSERT INTO posts (title, guid, pubDate) VALUES(%s, %s,%s)""", (title, guid, pubDate)) db.commit() for tag in curtags: c.execute("""INSERT INTO posttags (title, tag) VALUES(%s,%s)""", (title, tag)) db.commit() db.close() All that is left to do is add the execPr function that brings all the pieces together, calling the above functions in the proper order: def execPr(): p = obtainPost() t = determineTags(p["title"],tags) insertPost(p["title"], p["guid"], p["pubDate"], t) Now let’s test the code we just wrote. The simplest way to do this is through Python’s interactive command line. To start an interactive Python session, you can type python at your system shell prompt. It’s important to realize that since the sample discussed here is going to obtain some data from the web, you must connect to the Internet before you launch the application. Once you’re connected, you can launch the execPr function in your Python session, as follows: >>>import appsample >>>appsample.execPr() If everything is okay, you should see no messages. To make sure that everything really went as planned, you can check the posts and posttags tables. To do this, you might connect to the database with the MySQL command-line tool and then issue the following SQL commands: SELECT * FROM posts; The above should generate the output that might look like this: |title |guid |pubDate ------------------------------------------------------------------ Open Source CMS Award Voting Now Closed | article/2008-award-voting-closed | Tue, 21 Oct 2008 09:29:54 +0100 Then, you might want to check out the posttags table: SELECT * FROM posttags; This might generate the following output: |title |tag Open Source CMS Award Voting Now Closed | Open Source Please note that you may see different results since you are working with live data. Another thing to note here is that if you want to re-run the sample, you first need to empty the posts and posttags tables. Otherwise, you will encounter the problem related to the primary key constraints. However, that won’t be a problem at all if you re-run the sample in a few days, when a new post or posts appear on the Packt Book Feed page. Conclusion In this article you looked at a simple Python application persisting data to an underlying MySQL database. Although, for the sake of simplicity, the sample discussed here doesn’t offer a web interface, it illustrates how you can obtain data from the Internet, and then utilize it within your application, and finally store that data in the database.
https://www.packtpub.com/books/content/python-data-persistence-using-mysql
CC-MAIN-2016-50
refinedweb
1,487
61.26
I have a set of news articles in JSON format and I am having problems parsing the date of the data. The problem is that once the articles were converted in JSON format, the date successfully got converted but also did the edition. Here is an illustration: {"date": "December 31, 1995, Sunday, Late Edition - Final", "body": "AFTER a year of dizzying new heights for the market, investors may despair of finding any good stocks left. Navistar plans to slash costs by $112 million in 1996. Advanced Micro Devices has made a key acquisition. For the bottom-fishing investor, therefore, the big nail-biter is: Will the changes be enough to turn a company around? ", "title": "INVESTING IT;"} {"date": "December 31, 1995, Sunday, Late Edition - Final", "body": "Few issues stir as much passion in so many communities as the simple act of moving from place to place: from home to work to the mall and home again. It was an extremely busy and productive year for us, said Frank J. Wilson, the State Commissioner of Transportation. There's a sense of urgency to get things done. ", "title": "ROAD AND RAIL;"} {"date": "December 31, 1996, Sunday, Late Edition - Final", "body": "Widespread confidence in the state's economy prevailed last January as many businesses celebrated their most robust gains since the recession. And Steven Wynn, the chairman of Mirage Resorts, who left Atlantic City eight years ago because of local and state regulations, is returning to build a $1 billion two-casino complex. ", "title": "NEW JERSEY & CO.;"} import json import re import pandas for i in range(1995,2017): df = pandas.DataFrame([json.loads(l) for l in open('USAT_%d.json' % i)]) # Parse dates and set index df.date = pandas.to_datetime(df.date) # is giving me a problem df.set_index('date', inplace=True) You can split column date by str.split, concanecate first and second column - month, day and year together ( December 31 and 1995)and last call to_datetime: for i in range(1995,2017): df = pandas.DataFrame([json.loads(l) for l in open('USAT_%d.json' % i)]) # Parse dates and set index #print (df) a = df.date.str.split(', ', expand=True) df.date = a.iloc[:,0] + ' ' + a.iloc[:,1] df.date = pandas.to_datetime(df.date) df.set_index('date', inplace=True) print (df) body \ date 1995-12-31 AFTER a year of dizzying new heights for the m... 1995-12-31 Few issues stir as much passion in so many com... 1996-12-31 Widespread confidence in the state's economy p... title date 1995-12-31 INVESTING IT; 1995-12-31 ROAD AND RAIL; 1996-12-31 NEW JERSEY & CO.;
https://codedump.io/share/lHbCmc8davWf/1/parsing-date-in-json-format-using-python
CC-MAIN-2016-50
refinedweb
440
65.12
You are advised to follow the Fluid installation document to confirm whether the Fluid components are operating properly. The Fluid installation document uses Helm 3 as an example. If you use a version below Helm 3 to deploy Fluid and encounter the situation of CRD not starting properly, this may be because Helm 3 and above versions will automatically install CRD during helm install but the lower version of Helm will not. See the Helm official documentation. In this case, you need to install CRD manually: $ kubectl create -f fluid/crds Please check the related Pod running status and Runtime events. As long as any active Pod is still using the Volume created by Fluid, Fluid will not complete the delete operation. The following commands can quickly find these active Pods. When using it, replace <dataset_name> and <dataset_namespace> with yours: kubectl describe pvc <dataset_name> -n <dataset_namespace> | \ awk '/^Mounted/ {flag=1}; /^Events/ {flag=0}; flag' | \ awk 'NR==1 {print $3}; NR!=1 {print $1}' | \ xargs -I {} kubectl get po {} | \ grep -E "Running|Terminating|Pending" | \ cut -d " " -f 1 driver name fuse.csi.fluid.io not found in the list of registered CSI driverserror appear when I create a task to mount the PVC created by Runtime? Check whether the kubelet configuration of the node on which the task is scheduled is the default value /var/lib/kubelet. Check whether Fluid's CSI component is operating properly. The following command can find the Pod quickly. When using it, replace the <node_name> and <fluid_namespace> with yours: kubectl get pod -n <fluid_namespace> | grep <node_name> # <pod_name> indicates the pod name in the last step kubectl logs <pod_name> node-driver-registrar -n <fluid_namespace> kubectl logs <pod_name> plugins -n <fluid_namespace> csidriverobject exists: kubectl get csidriver csidriverobject exists, check whether the csiregistered node contains <node_name>: kubectl get csinode | grep <node_name> If the above command has no output, check whether the kubelet configuration of the node on which the task is scheduled is the default value /var/lib/kubelet. Because Fluid's CSI component is registered with kubelet through a fixed address socket, the default value is --csi-address=/var/lib/kubelet/csi-plugins/fuse.csi.fluid.io/csi.sock --kubelet-registration-path=/var/lib/kubelet/csi-plugins/fuse.csi.fluid.io/csi.sock. kubectl getcommand? During the Fluid upgrade, we may have upgraded CRDs. The dataset created in the older version will set the new fields in the CRDs to null. For example, if you upgrade from v0.4 or before, the dataset did not have a FileNum field in those earlier versions. After Fluid is upgraded, if you use the kubectl get command, you cannot query the FileNum of the dataset. You can recreate the dataset, and the new dataset will display these fields properly. The Volume Attachment timeout problem is a timeout caused by the kubelet not receiving a response from the CSI Driver when making a request to it. This problem is caused by the fact that the CSI Driver of Fluid is not installed, or kubelet does not have permission to access the CSI Driver. Since the CSI Driver is called back by kubelet, if the CSI Driver is not installed or kubelet does not have permission to view the CSI Driver, the CSI Plugin will not be triggered correctly. Run the command kubectl get csidriver to check whether the CSI Driver is installed. kubectl apply -f charts/fluid/fluid/templates/csi/driver.yamlto install it, and then observe whether the PVC is successfully mounted to the application. export KUBECONFIG=/etc/kubernetes/kubelet.conf && kubectl get csidriverto check whether kubelet has permission to view the CSI?
https://intl.cloud.tencent.com/ind/document/product/436/42232
CC-MAIN-2022-33
refinedweb
602
51.58
#include <Servo.h>int switchpin=7; //Input From buttonServo myservo;int pos=1;int value;void setup(){ pinMode(switchpin, INPUT); myservo.attach(9); Serial.begin(9600);}void loop(){ value=digitalRead(switchpin); Serial.println(value); if(value==1) { for(pos = 1; pos < 45; pos += 1) { myservo.write(pos); delay(35); } for(pos = 45; pos>1; pos-=1) { myservo.write(pos); delay(1); } }} i connected it using the arduino power supplythe 5v and the ground pins on the arduino to the servo and the signal to the pin 9and my code just reads an input from pin 7 and executes it executes sweep once.... and yeah input is working fine ive checked the input readings on serial monitor using println function:)yeah so powering it i am doing it directly from arduino connected to pc via usb, and when ever i connect the servo the device unmounts itself from windows and device goes into unrecognized and yeah servo works fine with normal sweep but doesnot with my code in which i just pasted the sweep code into the if loop for(pos = 45; pos>1; pos-=1) { myservo.write(pos); delay(1); } Please enter a valid email to subscribe We need to confirm your email address. To complete the subscription, please click the link in the Thank you for subscribing! Arduino via Egeo 16 Torino, 10131 Italy
http://forum.arduino.cc/index.php?topic=85136.msg639099
CC-MAIN-2015-48
refinedweb
225
58.62
Excuse for newbie question but I want make all clear for myself. I have a problem accessing class variable from within function outside the class. In code below I need text, text2 text = var1 text2 = var2 from django.shortcuts import render class Someclass(): def method_1(self): self.var2 = 'var2' self.var1 = 'var1' return self.var1 ,self.var2 def func(request): cls = Someclass() text2 = cls.method_1() text = cls.method_1() content = { 'text': text, 'text2': text2, } return render(request, "web/page.html", content) Use tuple unpacking - you can return several results, and receive several results from a func text, text2 = cls.method_1() Also you better not name your variables text and text2. And also cls is a common word to use for a class, and in your code cls is an instance, that's a bit unpythonic :)
https://codedump.io/share/ec4wQRTcOVqH/1/refer-to-defined-variable-from-function-outside-python-class
CC-MAIN-2016-44
refinedweb
134
69.79
The fonts in a visual style are just as important as any other graphical image you create. Text in the title bars, start menu, taskbar, etc. are all things you see on a constant basis. You have gone through the process of creating all these graphics, so why stop when it comes to the fonts? Well you don't have to as SkinStudio allows you to easily change the fonts in your skin. The screenshot below is the Edit fonts window that will appear when you select Change skin fonts from the SkinStudio One of the most intimidating things about changing the fonts in your skin is knowing what exactly you are changing. Thankfully, SkinStudio will tell you what fonts belong to what section so you know what will be changed. As you see in the example above, I selected the Title bar Active font in the selection list, and in the lower right corner you will see the sections that this font is used in. To change the font used, just click the Change font button and the screen below will appear. Here we can select which font to use, the style, size, shadows, and text effects. Once you have the font set to your liking, click the OK button. You can see a preview of the font you have selected in the preview window in the upper right hand side of the window. But what if you want to change the font to something more obscure, that might not be on everyone's PC? SkinStudio takes care of this by allowing you to include up to 5 different fonts that will be installed on the users system when the skin is installed. SkinStudio will also allow you change certain colors in your visual style. There is a wide variety of color settings in this section, and some people would refer to some of these as "classic" colors. You can access this section via the Change skin colors button in the SkinStudio 6 menu. Here are a few examples of the items in this section: Active title bar. If there is an application that is excluded from being skinned, or uses its own title bar, then you can change this color to closely match the rest of your skin. Desktop Background. If there is no wallpaper selected, then this is the color that will be displayed. Selected item. When you select an item in explorer windows, this is the color that is used. Now these are just a few of the choices that you can find, but it should give you a pretty good idea of the types of colors you can change in this section. In this configuration window you have a drop-down menu to select from the skin defined system colors, and the skin color presets. In similar fashion as changing the fonts, selecting each of the color boxes will then show a description of where that color is used. If you want to import the current system colors into this section, then you can do that by selecting the import existing system colors button at the bottom of the window. Above the description you have the "Change color" button and the color picker, both of which will allow you to change the selected color. Another selection in the drop-down menu will be the skin color presets. The color sets here might look familiar because we have visited this window before when changing colors in areas like the title bar caption. The color changes you have made previously in the various sections of your skin will be shown here. It can be easier as you can change the colors again without having to go through the skin sections again. Don't forget, you can also change the names of the color presets for easy reference again. You can also add your own custom color preset here by selecting the add new color preset button. There is also a special color section for Vista. There are new color options for Vista and in this window you can change those colors for the specific areas. When changing your colors, take the time and choose colors that match the rest of your theme. It might take a little extra time to try different color schemes out, but it will be worth it in the end. Well we are getting close to the end of the tutorial series. In the final chapters, we will cover some tips and tricks of SkinStudio 6, along with a few other things to finish off your skin.
http://www.stardock.com/products/skinstudio/help/fonts_and_coloring.htm
crawl-002
refinedweb
764
68.1
SYNOPSYS #include "mph.h" int delphvia(ptfig, ptvia) phfig_list *ptfig; phvia_list *ptvia; PARAMETERS - ptfig - Pointer to the figure in which the via should be deleted - ptvia - Pointer to the via to be deleted. DESCRIPTIONdelphvia delete the via pointed to by ptvia in the figure pointed to by ptfig. The list consistency is maintainded, and the space freed. RETURN VALUEdelphvia returns 1 if the via has been deleted, 0 if no such via exists in the list. EXAMPLE #include "mph.h" char *was_existing(ptfig, ptvia) phfig_list *ptfig; phvia_list *ptvia; { /* if only one exists, it's this one */ return delphvia(ptfig, ptvia) ? "you just killed it!" : "wasn't here anyway"; }
http://manpages.org/delphvia/3
CC-MAIN-2019-18
refinedweb
108
68.57
Home automation is a hot topic nowadays and even the simplest components of such a system can cost a lot. Therefore building custom devices with cost-effective parts can be an attractive alternative for makers. I’ll discuss the process of building a very basic system in this article. Before You Begin Experimenting is fun, but make sure to take all necessary precautions when working with mains voltage which has the potential to kill you. Take a look at the tutorial on controlling high voltage devices to learn how to switch high power devices and this summary of good and cheap IoT developer boards. The Hardware The main component of this build is a simple relay board that can be used to switch voltages up to 250V AC and a maximum current of 10 amperes: A simple relay board for higher voltage projects. It’ll be controlled by an ESP8266 based IoT developer board which is fully compatible with the Arduino IDE. Alternatively, you could also use a standard Arduino and an ESP8266 (or similar) breakout board. The ESP8266. You only need to make two connections between these devices. One of them is ground, the other is a control line for switching the relay which I chose to connect to D2 (digital pin two) of the developer board. The relay and the MCU need to be connected to a five-volt power supply which, in my case, is accomplished with a simple DC jack. Other than that, you’ll also need a standard mains socket, an IEC plug, preferably one with an earth pin, and a switch for turning the MCU ON and OFF. Furthermore, an enclosure is needed. I chose to go with a standard grey project box: Use a standard grey project box to house the build. The Build The process of building this device is pretty straight-forward. Start by making the necessary cutouts in the enclosure: Make the necessary cuts in the project box. Once you create them, you can mount the components. Most of the components snap in place. I still decided to add hot glue to seal the case so that dust won’t get into it easily: Use glue to ensure nothing moves and to make the box less susceptible to dust. Once that’s done, it’s time to connect these components and the other electronics. I added cable shoes on one side of the three mains wires and connected them to the IEC connector: Add cable shoes on one side of the three mains wires and connect to the IEC connector. The phase and neutral lines (brown and blue in Europe, black/red and white in the US) may be swapped. The earth connection, however, has to be in the middle. I connected the phase to the mains socket directly and ran the neutral line to the COM2 terminal of the relay before connecting the NO2 (normally open) terminal of the relay to the socket as well: Connect the phase to the mains socket and run the neutral line to the COM2 terminal of the relay before connecting the NO2 (normally open) terminal of the relay to the socket. I then added the necessary cables to the DC plug. These are used for supplying the voltage to the microcontroller as well as the relay. The last thing to do is connecting the relay and the MCU, as described above. I then added heat shrink tubing to the critical sections to prevent shorts and test-fitted the components: Add the necessary cables to the DC plug. Once everything fits, tuck away the cables and close the case. The Software The software that runs on the MCU connects you to your wireless network and accepts client requests on port 80 like a web server. You can then access the device via any web browser: Access the device via any web browser. I won’t discuss the code in detail to keep the article short. However, I thoroughly documented the source code so it should be easy to understand. It is available at the end of the article. Conclusion As you can see, it’s not terribly difficult to build such a device. Most of the work is done by the software. While this is the most basic approach, you can add sensors, timers, and other devices for automatically controlling the connected appliance. Furthermore, I recommend adding a fuse if you plan on using this device unattended. Full Project Code #include <ESP8266WiFi.h> #define RELAY_PIN D2 const char*<button>Device on</button></a>"); client.println("<a href=\"/state=off\"><button>Device off</button></a>"); client.println("</body>"); client.println("</html>"); } else { // Return a response header client.println("HTTP/1.1 400 Bad Request"); client.println("Content-Type: text/html"); client.println(""); client.println("<html>"); client.println("Unknown request parameter supplied!<br/>"); client.println("<a href=\"/\">Back to main page</a>"); client.println("</html>"); } }
https://maker.pro/esp8266/projects/how-to-build-a-very-simple-diy-home-automation-system
CC-MAIN-2020-34
refinedweb
819
62.98
I have an abstract class and a child that extends the abstract class. The child is supposed to be a sigleton. Here is simplified example of the abstract class: abstract class AbstractClass{ protected static $instance = NULL; abstract protected functi I have a singleton class. This class has methods which use core data and are to be used only for some build configuration. +(AClass*) singletonInstance { static dispatch_once_t dispatchCall; static AClass *shared=nil; dispatch_once(&dispatchCall, ^{ I currently have a logging setup that looks like this: require 'active_support' require 'singleton' class Worker def initialize(logger) @logger = logger end def perform @logger.with_context(["tag1"], "Started work") Provider.say_hello end end class V I am super new to Java programming. Here is a confusion I have. public class Singleton { public static Singleton GetInstance() { if (sInstance == null) { sInstance = new Singleton(); } return sInstance; } private Singleton() { // No code here } priva so I have this project that's kind of grown past the original scope it was created for- so I'm trying to adapt what I have to fit a larger purpose. Before it was a singleton that managed the execution of some classes and now I'm trying to pre-compile Sorry if anything I say is completely wrong but I am new to swift. I have a UIViewController that contains a uicollectionsview. I then have a data manager that gets json data from instagram and then parses it. What I want to know is how make the data I'm struggling with this. I've added the subview correctly and get no errors, however no iAd is ever shown, even though the method bannerViewDidLoadAd definitely gets called. Any advice what I'm doing wrong? #import "Advertisments.h" @implementation Singletons in C++ (at least prior C++11 AFAIK) can be a nightmare. With the whole static initialisation order fiasco. But boost::call_once seems to offer a robust way to implement singletons. I've tried to come up with an easy to use idiom I'd like t Trying to use database connection with singleton. __constructor has been private and returning instance from static function. class MyDbConn { protected $_conn; protected $database; protected $user; protected $password; protected $host = "localhost"; When memory will be created for myClass object pointed by ptr? Is below singleton thread safe? Class myClass { static myClass* ptr; public: myClass(){} ~myClass(){} static myClass* getPtr(); }; myClass* myClass::ptr = new myClass(); myClass* myClass: I know that what is singleton pattern and how to create it and how to make it thread safe using locking and double checking but all I want to know " let's consider a scenario I have a .dll which does a have class that is singleton. Now there are two i have a object in my application which is needed at several points. That means, there are a lot of objects, which holds a reference to this object. Is there an easy way, to spread this reference to all the other objects? One possibility might be to First of all, I'm using Storyboards, the Parse backend and objective-c (IOS8 project) I've a got a ViewController that downloads a specific column from the row that is currently open. I also got a container within this ViewController that sends a new Background Most of my experience with OOP comes from Objective-C. In that language there's a clear distinction between instance and class methods. As a result it is fairly easy to work with a singleton without any side effects. In C++ I haven't been I'm currently having some trouble with data getting lost when transferring from a ViewController to a subclass of PFFile. The data being passed is image data to upload to a users profile. Here's the code for selecting the image: - (void)imagePickerCo I have a pretty simple singleton that uses holder pattern (I've shown just the pattern, not other details): public class Foo { private static class FooHolder { private static final Foo INSTANCE = new Foo(); } public static Foo getInstance() { return here is my code: + (instancetype)sharedInstance { static PanoramaDataManager *sharedInstance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [[PanoramaDataManager alloc] init]; [NSURLConnection sendAsynchron I got the following method in a singleton/shared instance and would like update the user with the progress of fetching emails. - (void)getAllImapEmailsForMailbox:(NSString *)mailbox completionBlock:(void (^)(BOOL success, NSString *errorString, NSArr I do recognize that this question has been asked many times before, but I can't get the answer I want out of it. And that question is, "Should I use a singleton or a class with all static members and methods?" I only ever need one instance for what I I just read this article about the Symfony2 container concept. I got the impression that every class which is instantiated through a container is a singleton object, means that it is only instantiated once and reused all the time. The example in the
http://www.dskims.com/tag/singleton/
CC-MAIN-2018-30
refinedweb
812
51.28
Why do we need pointers in C? -To allocate memory dynamically -To refer to the same space in memory from multiple locations. This means that if you update memory in one location, then that change can also be seen from another location in your code – To navigate arrays -To obtain and pass around the address to a specific spot in memory Working of pointers: The working of a pointer can be best understood with the help of a code. Consider the below code snippet: #include <stdio.h> int main(void) { int *numPtr; //Declaring a pointer numPtr of int type int num = 10; //Intialising a normal variable numPtr = # //Intialising numPtr as a pointer to num printf("Address of num variable: %x\n", &num); printf("Address stored in numPtr variable: %x\n", numPtr ); printf("Value of *numPtr variable: %d\n", *numPtr ); return 0; } In this code, we are creating two variables – a normal variable num that stores the integer 10, and a pointer numPtr that stores the address of num. When we run this program, we get the following output: Address of num variable: d58d03c4 Address stored in numPtr variable: d58d03c4 Value of *numPtr variable: 10 num stores the value ten. The address of num is d58d03c4. The pointer numPtr stores this very address i.e. d58d03c4 as it points to num. To see what value is stored in the variable pointed by numPtr, we make use of the * operator. As we know, printing *numPtr will display 10, as num stores 10. By this logic, printing num and *numPtr will give the same output. The below diagram will help to understand how the above code works: Report Error/ Suggestion
https://www.studymite.com/blog/why-do-we-need-pointers-in-c/
CC-MAIN-2019-43
refinedweb
277
67.49
Created on 2018-02-08.16:55:32 by jamesmudd, last changed 2018-02-27.22:34:42 by jeff.allen. If you have a python module eg. test_mod/ ├── hello.py <<<<< Contains only foo = 4 └── __init__.py <<<<< Contains only _version__ = '1.1.1' If you import this in cpython you will not have access to hello e.g. >>> import test_mod >>> dir(test_mod) ['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', '__version__'] >>> test_mod.hello Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute 'hello' Which is correct because you didn't import test_mode.hello and the __init__.py doesn't import it. In Jython (master) >>> import test_mod >>> dir(test_mod) ['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', '__version__'] <<<<< Looks good at this point >>> test_mod.hello <module 'test_mod.hello' from '/scratch/test_mod/hello.py'> <<<<< This is wrong shouldn't be able to see hello >>> test_mod.hello.foo 4 >>> dir(test_mod) ['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', '__version__', 'hello'] <<<<< And now its added to the module I think this happens because of a change made to fix #2455 which means if you lookup an attribute on a Pyhton module and don't find it try to import it. The bug described in that ticket is when you have a mixed Python/Java package. However i'm not sure it should have been fixed and now the behaviour is wrong for Python. To fix this I think the support for the mixed Python/Java package needs to be removed which I don't see as an issue. Oh great: automatic imports. This is better than plain old Python! But seriously ... I confirm the observation and agree this is incorrect behaviour. PS issue2654> dir test_mod ... -a---- 27/02/2018 21:55 270 Bad.class -a---- 27/02/2018 21:50 69 Bad.java -a---- 27/02/2018 07:56 28 hello.py -a---- 27/02/2018 07:56 28 __init__.py PS issue2654>. >>> import test_mod Executed: test_mod\__init__.py >>> dir(test_mod) ['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__'] >>> test_mod.Bad.x ### This magical import we want (I think) 42 >>> dir(test_mod) ['Bad', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__'] >>> type(test_mod.hello) ### This magical import is not Python :( Executed: test_mod\hello.py <type 'module'> It's not as bad as at first I thought. It would still have my vote to be fixed before 2.7.2 goes out. The business of package/module import is difficult enough in plain Python. We add Java packages to the mix, which are syntactically similar and semantically different, so it is bound to be difficult. The first thing is to be clear what behaviour we want. The Jython Book has something useful to say here: The word "disastrous" should give us pause. On the other hand, the Java semantics are a lot like Python 3 namespace packages (PEP 420). There the first __init__.py still defines a regular package exclusively at that location.
http://bugs.jython.org/issue2654
CC-MAIN-2018-22
refinedweb
487
69.79
The Resurgence of C Programming High-level programming languages may win most popularity contests, but the venerable C language isn't going away. High-level programming languages may win most popularity contests, but the venerable C language isn't going away. In the preface to their book The C Programming Language, Brian W. Kernighan and Dennis M. Ritchie note that C “is not specialized to any particular area of application. But its absence of restrictions and its generality make it more convenient and effective for many tasks than supposedly more powerful languages.” To some degree, C was written for the purpose of elevating UNIX from a machine-level operating system to something resembling a universal platform for a wide range of software applications. Since its inception in 1972, C has been the common language of UNIX, which essentially means that it’s everywhere. /* Blinker Demo */ // ------- Preamble -------- // #include <avr/io.h>/* Defines pins, ports, etc */ #include <util/delay.h> /* Functions to waste time */ int main(void) { // -------- Inits --------- // DDRB = 0b00000001; /* Data Direction Register B: writing a one to the bit enables output. */ // ------ Event loop ------ // while (1) { PORTB = 0b00000001; /* Turn on first LED bit/pin in PORTB */ _delay_ms(2000); /* wait */ PORTB = 0b00000000; /* Turn off all B pins, including LED */ _delay_ms(2000); /* wait */ } /* End event loop */ return (0); /* This line is never reached */ } C and C++ are at the heart of Arduino, the open source project for building do-it-yourself devices and hardware. “Arduino code is essentially C and C++,” says Massimo Banzi, a cofounder of the Arduino project. “Right now, you can write Arduino code on an 8-bit microcontroller and then on an ARM processor. You can go right up to a Samsung Artik, which is essentially a Linux machine with an 8-core processor. We can run Arduino on top of Windows } How does this play out in the real world? Let’s say you’re an aerospace engineer and you’re asked to improve the functionality of an actuator that moves a control surface, such as an aileron on the wing of an airplane. You might begin by using components from an Arduino kit to create a low-cost prototype of the actuator. After you’ve got your prototype working, you can tinker around with it and optimize its performance. “If you are an engineer, you can take your idea and use Arduino to build prototypes very fast,” says Banzi. “So you might begin with Arduino and then decide to reimplement the code using another tool. But you might also wind up using Arduino all the way. Or you could use a C compiler to move your code to a piece of hardware that doesn’t run Arduino, but will run C or C++.” Transferring the code isn’t difficult. The hard part, says Banzi, is writing the algorithm that controls the actuator moving the aileron. Fixing the problem with the aileron means you need to develop a new algorithm. Then you need to tweak and adjust your algorithm. “If it were my project, I would write my Arduino code for the tool and then I would use a pure C or C++ file for my algorithm,” says Banzi. “Once my project is working and I can tweak the algorithm, I would just take the algorithm and paste it into the tool.” If you’re working in closely regulated industries—such as automotive, aviation, or healthcare—you might need to redesign your Arduino prototype before deploying it. But there are lots of situations in which regulatory compliance wouldn’t pose a hurdle. Let’s say you decide to build a digital watch for yourself. You could buy a Time II DIY watch kit from SpikenzieLabs, follow the instructions that come with the kit, and create a nifty timepiece. But here’s the really cool part: the watch is designed to be hackable. You can reprogram the watch with Arduino IDE (integrated development environment) software. Basically, the kit empowers you to create a one-of-a-kind smartwatch by tweaking a few lines of Arduino code. Some obstacles are more difficult to overcome than others. When you’re building an open source wristwatch, for example, you might decide to follow your muse, ignore the instructions, and install a bigger battery or use a different color display. “If you’re designing it yourself, you’re going to have a lot more research to do because you’re going to need to know how much power you want to use. You’re going to need to figure out how to program the display and what type of display you want to use,” says Brian Jepson, an author, editor, and experienced digital fabricator. “Once you’ve got the parts, you’ve got to put them together and pack them into a case that you can wear on your wrist.” Manufacturing a custom case for your open source watch will likely involve 3D printing, which often requires some basic programming skills. “Each part has to sit really close to the other parts. You don’t have a lot of space. You can’t have wires running too long or too short. It’s a tight fit and you have to make sure you make good, reliable connections between the components,” Jepson says. When all the parts are connected and packed securely in place within the case, you can seal it up. But your work isn’t necessarily done at that point. “If I were building it from scratch, following somebody else’s instructions, I might have had to program it myself. Or, if I ever want to customize it, to display things in a different way, maybe to graph things, I’d have to download the source code, make some changes, and then load it onto the device,” says Jepson. In a cosmic sense, Arduino fulfills the vision of C’s creators, who foresaw a world of portable software applications. What they did not anticipate, however, was the emergence of open source hardware, the maker movement, and maker culture. For the early pioneers of computing, creating functional software was an end in itself. Today, it’s not enough to just create software that runs without crashing. The world wants software that can run devices and machines such as trains, planes, automobiles, and pacemakers—without crashing. That puts a lot of weight on C, which is used widely to write embedded software. “C is the Latin of programming languages,” says Ptah Pirate Dunbar, an open source hacker and professor of computer science. He notes that many commonly used high-level languages are influenced by C through syntax, function, or both. “Learning C empowers developers with the mental flexibility required for transitioning across C-influenced languages with ease and agility.” George Alexandrou, vice president and chief information officer at Mana Products, a global manufacturer of private-label cosmetics, says there are two kinds of software developers: mechanics and engineers. “The mechanics will fix things when they break. But when you want to design something new, you need an engineer,” says Alexandrou. “If you want to be an engineer, you need to know how to program in C. Programming in C can get you out of trouble. It can also get you into trouble.” Suman Jana, an assistant professor in the Department of Computer Science at Columbia University and a member of the Data Science Institute, says the C language “allows expert programmers to extract maximum performance from the underlying hardware resources.” With C, programmers can control and customize almost every aspect of their programs. “However, as a side effect, it is also very easy for a programmer using C to inadvertently make serious mistakes, like memory corruption, that lead to security vulnerabilities,” Jana says. Buffer overflow is a “classic example of memory corruption in C code,” he says. It can happen when a programmer copies data into a preallocated buffer without checking whether or not the data will fit into the buffer. If the user input is longer than the buffer, it will overwrite past the boundary of the buffer. That can pose serious security risks. When user input, for example, is written into a buffer without bounds checking, the system can be susceptible to an injection attack. Why is that? When buffer overflow is triggered by user input, the user can probe the system and potentially take control of it. Caveats aside, C is especially relevant to developers working on embedded software for smart machines. “Embedded software often runs in resource-constrained environments. The target devices have small memory and limited computational power. For such environments, C is a very good fit because it allows programmers to get good performance even with limited resources,” says Jana. “Learning C is a good exercise to understand the underlying system and hardware. Even if a Java/Python programmer does not use C on a day-to-day basis, learning C can potentially help them understand how different Java/Python features are actually implemented by virtual machines. In fact, many Java/Python virtual machines are written in C.” Jana sees plenty of good reasons for coders to learn C. “The C community is a large and thriving group. Some of the most popular and widely used software—like the Linux kernel, Apache HTTP server, and Google Chrome browser—are written in C/C++,” he notes. While there might be some vague similarities between C and Latin, there are also stark differences. Latin is a dead language. C is most definitely alive and well. A hardware hacker recently compared C to Jason Voorhees, the main character in the Friday the 13th series of horror movies. Just when you think Jason is dead, he comes roaring back to life. “Hardware has gotten more complex and there’s more to debug,” says John Allred, an experienced developer of embedded software and hardware interfaces. “Nowadays, the programmer is expected to help with the debugging. I still believe that C programmers have a mindset that helps them see the big picture. When you know C, it helps you solve problems with hardware. It gives you a different way of looking at the world.” Allred is senior manager of cybersecurity at Ernst and Young (EY). After graduating from MIT and before joining EY, he participated in a number of technical firsts: the first internal hard drive for the Macintosh; SIMNET, the first large-scale networked simulation of military vehicles; and RTIME, the first large-scale networking engine for video games and distributed systems. He is an unabashed fan of older programming languages like C, which require a thorough understanding of how computers actually work. “When you program in C, you control the memory. But when you program in Java, it does the memory management for you. When Java decides it’s time to clean up the memory, it goes ahead and does it—even if you’re in the middle of doing something else,” says Allred. “With Java, there’s a higher level of abstraction. You’re not driving the hardware directly.” If you’re writing code for an online retailer, the loss of 100 milliseconds probably won’t ring any alarm bells. But when you’re programming software for real-time applications, lost moments can make a big difference. “When you’re writing code for drones or driverless cars or oil refineries—situations where you need real-time performance—then Java and Python shouldn’t be your choices,” says Allred. In some respects, Allred represents a vanishing generation of programmers who are comfortable with assembly code and have a deep appreciation for its intrinsic value. Bare-metal coders are in the minority, but many of their ideas are gaining new currency as the lines between software development and hardware design become less distinct. “I think it’s always really good to know how the software interfaces with the hardware,” says Limor “Ladyada” Fried, founder of Adafruit. “Understanding the limits of the hardware will help you understand optimizations that are possible in the software.” If your project involves pushing data from a sensor across a wireless link, for example, you need to know the limitations of the hardware. Until you actually begin experimenting with that wireless link, says Fried, you won’t know how much data it can handle. In those types of situations, which are becoming more common, there is no substitute for hands-on experience. Ideally, your choice of a programming style should be determined by the requirements of the project before you. “I think it depends on your needs,” says Fried. “There are some times when you’re really optimizing and you want to go to machine code or FPGAs [field-programmable gate arrays] or CPLDs [complex programmable logic devices]; especially when you’re doing extremely advanced, very time-sensitive stuff like SDR [software-defined radio] or video extreme handling, you might go with an FPGA. For most people, C or C++ seems to dominate.” Simon Monk, a prolific author and experienced builder of open hardware projects, says C is still the optimal choice for programming on machines. “On a microcontroller, I would always use C. It’s a good compromise between the performance of assembler and the readability of a high-level language,” Monk says. But he is not enthusiastic about the idea of hardware developers replacing software engineers. “With a few honorable exceptions, hardware developers should not be allowed to program…although they would probably say the converse is true of software engineers like me designing electronics,” he says. He faults machine code for being “almost universally opaque and badly structured, with functions dozens of lines long.” And he raises an interesting point about the inherent differences between hardware and software developers, arguing that hardware developers are often more focused on how a particular piece of hardware works, instead of thinking more deeply about the service the hardware is designed to provide. For software engineers who want to write embedded code for hardware, Monk advises taking small steps. “Don’t use the first library you find on GitHub. Try out a few examples and if you don’t like the API or the code smells, don’t be afraid to write your own,” he says. “Also, don’t get carried away with overstructuring or overpatterning your code. A 50-line Arduino program does not benefit from being split into three classes and a suite of unit tests and an implementation of the observer pattern.” Edward Amoroso, chief executive officer of TAG Cyber and former chief information security officer at AT&T, says knowing C is handy, but no longer absolutely essential. “You can drive your car to Buffalo and not know how the engine works,” says Amoroso. “I think the analogy holds for software. On the other hand, if something goes wrong or some kind of weird issue arises and you have no understanding of the underlying logic of the software and the hardware, it might be more difficult for you to fix the problem.” From Amoroso’s perspective, the advantages of knowing C are at best marginal in today’s world of highly abstracted software. “It gave you a huge advantage 20 years ago and a good advantage 5 years ago,” he says. “In the near future, however, it will probably be even less of an advantage, given the level of abstraction and the power of translators.” Still, he isn’t ready to throw in the towel and abandon C to the ash heap of history. “If you’re programming on bare metal, then it’s helpful to know C. It’s like learning how to drive a stick shift—it gives you more control,” says Amoroso. “But for the most part, the trend in software development is more toward the logical connection of working software components that are plucked from libraries and put together.” Amoroso says he misses the old days when students would actually learn to write code. “Today, much to my chagrin, young people are taught to code using programming environments where they’re moving widgets around and creating little games. They’re basically adding logic to widgets. I’m not saying it’s necessarily harmful, but I’d rather see them learn how a computer operates first, and then build up to writing software. But that’s not the way it’s typically done in schools today.” Educators and cognitive psychologists have long known the value of hands-on learning. When you work with your hands, your brain is actually more engaged than when you are simply listening or reading. Dale Dougherty, the founder and CEO of Maker Media, sees a renaissance in hands-on education. Nowhere is this renaissance more evident than at Maker Faire, a series of live events produced by Maker Media. Maker Faire is “a family-friendly festival of invention, creativity, and resourcefulness, and a celebration of the maker movement.” At a recent Maker Faire at the New York Hall of Science, Dougherty emphasized the importance of combining “art, science, craft, and engineering” in bold new ways that encourage both creativity and technical capabilities. “What we see here at Maker Faire is a flourishing of creative spirit and technical skills…coming together to make new things possible,” he said in a talk at the event. Visitors to the event saw dozens of exhibits from makers of drones, robots, 3D printers, electric vehicles, rockets, wearables, alternative energy solutions, and various combinations of hardware and software. Dougherty is one of several voices in the maker movement, which has already transformed or disrupted many aspects of traditional technology culture. The Raspberry Pi, for example, was developed by a team at the University of Cambridge’s Computer Laboratory as a tactic for enticing more students to study computer science. The first version of the Pi, which is essentially an inexpensive single-board computer, was released in early 2012. Since then, the Raspberry Pi Foundation has sold 10 million devices. Although the Pi was initially designed for students, it is now used widely by engineers and developers all over the world—a truly amazing demonstration of the maker movement’s influence, both inside and outside the classroom. Tom Igoe is an associate arts professor at ITP, a two-year graduate program within the Tisch School of the Arts at New York University. Officially, ITP’s mission is exploring “the imaginative use of communications technologies,” and it’s become a launch pad for the expression of creativity through novel combinations of hardware and software. Igoe leads two areas of curriculum at ITP: physical computing and networks. He has a background in theater lighting design and is a cofounder of the Arduino open source microcontroller environment. “All of the various technologies we’re talking about play a big role in our everyday life. It doesn’t matter whether we are a technologist or engineer or whatever, they influence our everyday life,” says Igoe. “But if we don’t have an understanding of them…then we don’t have much control.” One of the ITP’s primary goals, says Igoe, is “breaking the barrier” that prevents or discourages people from making their own devices and machines. One of his students was a physical therapist who wanted to create a device for helping patients improve their range of motion following an illness or injury. “She didn’t just want to describe what she wanted and have someone else build it,” Igoe explains. “She wanted to build it herself, so she could make the design decisions based on her actual experience with her patients.” From Igoe’s viewpoint, the traditional tech industry has become too doctrinaire in its approach to valuing talent. “They assume that technical proficiency is the only measure of a person’s work. The truth is that you need people with a lot of different capabilities,” he says. “You need a lot of different skills and a lot of different ways of seeing the world.” It’s not necessary for every student to become an engineer or designer. “When I’ve got students who are not technically gifted, I try to help them figure out what they’re really good at and apply it to making the kinds of things we’re talking about,” says Igoe. Much of the inspiration for Arduino, says Igoe, came from working with students who were not engineers, but who were very interested in using electronics and controllers in their projects. “Arduino is a microcontroller that’s not designed for engineers; it’s designed for everyday people,” he explains. That said, Arduino is now used by a wide variety of people—including engineers and designers—as a physical sketchbook for hardware projects. Increasingly, it’s seen as an integral part of the prototyping process. The popularity of low-cost kits based on Arduino or Raspberry Pi components has led to “an explosion of creativity,” says Mark Gibbs of Gibbs Universal. He is an author, journalist, and serial tech entrepreneur. “It’s easier now for people to enter the tech market with little or no technical knowledge and then acquire the skills they need to become very proficient at building devices and machines.” It’s not just the low cost that makes Arduino and Raspberry Pi so attractive—they’re also easy to work with, says Gibbs. “The impact has been enormous. Now you have the ability to bring technology into the arts, which is a huge thing in itself because it changes the nature of what we consider to be art.” Gibbs cites the example of Sketchy, a drawing device created by Richard Sewell (aka Jarkman) that combines an Android phone with a delta robot based on Arduino components. Another example is Robot Army, a team of artists and engineers that make easy-to-build robot kits for people interested in learning and experimenting with inexpensive robots. “Those kinds of projects would have been inconceivable just a few years ago. You would have needed hundreds of thousands of dollars to build a robot. Now you can build one for under $100,” says Gibbs. The professional engineering community is not immune to the lure of low-cost, easy-to-use tech like Arduino and Raspberry Pi. “In the beginning, many professional developers laughed at our tools,” recalls Banzi. “They thought they were toys or kind of stupid.” Many of those professionals are no longer laughing. “Now they’re using our tools to build quick and inexpensive prototypes,” says Banzi. “More important, developer teams use tools like Arduino to onboard beginner programmers more quickly. Now you can give new programmers small tasks and projects that will help them build their skills faster.” In many ways, the maker movement has blurred—or in some cases, erased—the traditional boundaries between professional and amateur science. While some people might reflexively argue against that type of blurring, it harkens back to the times before the Industrial Revolution, when practically all scientists were amateurs. Today, it seems we no longer have to choose between being amateurs or professionals—we can enjoy the best of both worlds, whether we choose to write code in C or assemble parts from a kit.
https://www.oreilly.com/radar/the-resurgence-of-c-programming/
CC-MAIN-2019-39
refinedweb
3,851
61.16
I’ve a dataset that has different datatypes and used label encoder for encoding the non-numeric values. Then, I split the data to 80-20 % of Train – Test of input/output data. Then, ran the data across multiple models like Cartesian, LogisticRegression, LinearDiscriminantAnalysis, KNeighborsClassifier, DecisionTreeClassifier. Then, I found the best accuracy score out of all the .. Category : model init() got an unexpected keyword argument ‘presort’ This is the error that occurred while working on the coding part of the problem. Pls, can anyone suggest to me how to rectify this error? Source: Python.. import numpy as np def frame(x, frame_len, hop_len): assert(x.shape == (len(x), 3)) assert(x.shape[0] >= frame_len) assert(hop_len >= 1) n_frames = 1 + (x.shape[0] – frame_len) // hop_len shape = (n_frames, frame_len, x.shape[1]) strides = ((hop_len * x.strides[0],) + x.strides) return np.lib.stride_tricks.as_strided(x, shape=shape, strides=strides) x_frames = [] y_frames = [] for i in range(x_recordings.shape[0]): # frames .. I wanted to run my Vosk voice recognition project but got this error. How can I fix this? ERROR (VoskAPI:DecodableNnetLoopedOnlineBase():decodable-online-looped.cc:50) Ivector feature dimension mismatch: got -1 but network expects 40 In folder "model" from Vosk I have the files: model Source: Python.. When we train ML model, we can see prdiction graph like below. Where orange color is for real data nad blue for prediction, If the mentioned plot is for 3 steps ahead, how can we elabrate this plot? Further more how can we make decision after seeing this real and prediction plot? what does x-axis .. I’m trying to create an object in my Order model. My js return a list of multiple values for Model database however I can not save multiple values that I received from ajax as a list. I see it’s an array in js and a list in django but it’s not happening. I’ve tried ManyToManyField .. I am studying the Tensorflow classification from textbook and compiled the following code: from sklearn.metrics import classification_report, confusion_matrix def train_model(X_train, y_train, X_test, y_test, learning_rate, max_epochs,batch_size): in_X_tensors_batch = tf.placeholder(tf.float32, shape=(None, RESIZED_IMAGE[0],RESIZED_IMAGE[0],1)) in_y_tensors_batch = tf.placeholder(tf.float32, shape=(None, N_CLASSES)) is_training = tf.placeholder(tf.bool) logits=model(in_X_tensors_batch, is_training) out_y_pred=tf.nn.softmax(logits) loss_score=tf.nn.softmax_cross_entropy_with_logits(logits=logits,labels=in_y_tensors_batch) loss=tf.reduce_mean(loss_score) optimizer=tf.train.AdamOptimizer(learning_rate).minimize(loss) with tf.Session() as session: session.run(tf.global_variables_initializer()) for epoch in range(max_epochs): print("Epoch=", epoch) .. I am using VS Code and pytorch library for python to train models LSTM and ResNet, the problem I am trying to reach more than 160K iteration, but to reach 20K it take almost a week, and some times it throw full memory exception (my device i7 11th and 16 G Ram memory) I also .. I have complete pipeline in place from data inputs to final predictions. I have 10 models in place (wrote function to automate the whole process) then , Choose 1 model based on accuracy. Now, I need to store all the model(because any model can have better accuracy as data changes) and reuse it with new .. I have build a model and saved it using pickle library but I wanna use it again by changing the values of my input variables and for that I don’t have any output. Here is the code : # Save Model Using Pickle import pandas from sklearn import model_selection from sklearn.linear_model import LogisticRegression import pickle .. Recent Comments
https://askpythonquestions.com/category/model/
CC-MAIN-2022-05
refinedweb
585
50.12
Chapter 1. Modularity Introduction Dealing with change is one of the most fundamental issues in building applications. It doesn’t have to be difficult, however, since we are dealing with software that is not constrained to any physical laws. Change is an architectural issue, but unfortunately, it is often overlooked as such. This is logical to some extent, because most of the time you simply cannot see it coming. Traditional software development processes can make it hard to cope with change. In waterfall, and even DSDM and RUP to some extent, the big design is being done up front. Once the design is created, it is carved in stone, and further down the line, there is rarely any possibility to divert from the original ideas. As soon as the first big chunks of functionality are built, it is pretty much impossible to get a fundamental change in the software design. When using an agile methodology, you must have all disciplines involved: requirements, architecture, development, testing, and so on. As most activities of the software development process are performed in short iterations (or sprints), this affects the way that one activity can influence the remainder of the development process. Shorter development cycles can lead to a greater transparency. But they can also keep you from seeing the entire effect of certain architectural decisions when you first encounter them. Some parts of an application’s architecture are harder to change than others. The key thing when dealing with change is to predict where it is coming, and delay any permanent architectural decisions until you have all necessary information for those decisions. This is hard, of course. On the other hand, a completely flexible application architecture is also impossible to achieve. Flexibility will likely cause so many abstractions that the complexity of the resulting application is unreasonably high. Complexity is a monster and should be avoided at all cost. It was Leonardo da Vinci who said, “Simplicity is the ultimate sophistication,” and he is absolutely right about that. A number of studies have been conducted that show how the number of lines of code double about every seven years. Not only are we building bigger applications, but we are also using more diverse technologies. Advanced mechanisms such as Aspect Oriented Programming, Polyglot Programming (using multiple programming languages within the same solution), the enormous amount and availability and diversity of open source frameworks for all layers of the application, using alternative storage solutions in the form of NoSQL, the need for multitenancy in PaaS and SaaS environments, dealing with massive scale and elastic resource allocation, etc, etc. Currently, complexity is rising at such a disturbing pace that we have to put mechanisms in place to bring it to a halt. More complexity usually means spending more time understanding what the application actually does. Not to mention the amount of time, energy, and money that has to be invested in maintaining these applications for a long time. As an example, how many times have you looked at some code that you had written yourself a couple of years ago and had a hard time understanding what it actually does? With the evolution in which open source frameworks are being made available into the market, the amount of knowledge to keep up with in your teams is also very hard to deal with. This is also why writing readable code is so important. Rather name your variable l instead of listOfBooks? You save some typing now but will regret it later on. Divide and Conquer Why is it difficult to maintain a large code base over many years? Many projects get into more and more problems as soon as the code base becomes larger. The core of the problem is that the code is not modular: there is no clear separation between different parts of the code base. Because of that, it becomes difficult to understand what the code is doing. To understand a nonmodular code base, you basically need to understand all the code, which is unrealistic. Working on a large code base that you can only partly comprehend will introduce bugs in places you couldn’t foresee whenever you make any changes. We have all seen these kind of projects, and we all know what is wrong with them; they ended up as spaghetti code. This can be improved by identifying separate parts of a system and strictly separating them from other parts of the code. Doing so starts with one of the most basic object orientation best practices: program to interfaces, not to implementations. By programming to interfaces only, you can make changes to implementations without breaking consumers of the interface. We all know and apply this every day, but code bases still end up as an unmaintainable mess. In real applications, we are dealing with several interfaces and implementation classes when working on a part of a system. How do you know which interfaces and classes belong together and should be seen as one piece when looking at the bigger picture? By programming to interfaces, we try to prevent coupling. At the same time, there is always some coupling, between classes. Without any coupling there wouldn’t be any useful code. Again, we are looking at a basic object orientation best practice: promote cohesion; prevent coupling. In fact, this best practice can be seen as the golden rule of modular software design. Code that logically belongs together should be cohesive; it should do only one thing. The goal is to prevent coupling between these logical cohesive parts. How can we communicate and enforce cohesion in separated parts of the code base while keeping coupling between them low? This is a far more difficult question. Object orientation and design patterns do give us the tools to deal with this at the finest level of single classes and interfaces. It doesn’t give much guidance in dealing with groups of classes and interfaces. The Java language itself doesn’t have any tools for this. We need something at a higher level: techniques to deal with well-defined groups of classes and interface, i.e., logical parts of a system. Let’s call them modules. Modularizing a software design refers to a logical partitioning of the system design that allows complex software to be manageable for the purpose of implementation and maintenance. The logic of partitioning may be based on related functions, implementation considerations, data, or other criteria. The term modularity is widely used, and systems are deemed modular when they can be decomposed into a number of components that may be mixed and matched in a variety of configurations. Such components are able to connect, interact, or exchange resources (data) in some way by adhering to a standardized interface. Modular applications are systems of components that are loosely coupled. Service Oriented Architecture All Over Again? If you have ever heard of Service Oriented Architecture (SOA), you might recognize that it proposes a solution to the problems discussed. The SOA promise is in fact even better (on paper). With SOA, we reuse existing systems, creating flexible and reusable business process services to an extent that new business requirements can be implemented by simply mixing and matching services. Theoretically speaking. Many of the SOA promises were never delivered and probably never will be because integrating systems at this level has many challenges. There is something very valuable in the concept, however. Isolating reusable parts of a larger system makes a lot of sense. SOA is not the solution for the problems discussed in this book. SOA is on a very different architectural level: the level of integrating and reusing systems. Modularity is about implementing systems and about separating concerns within such a system. Modularity is about writing code; SOA is about system integration. Some have tried to apply patterns from the SOA world within a single system because it does theoretically solve the spaghetti code problem. You could identify parts of an application and implement them as separate “services.” This is basically what we are looking for, but the patterns that are related to SOA are not fit for use within a single system. Applying integration patterns introduces a lot of complexity and overhead, both during development and runtime. It’s an extreme form of over-engineering and dramatically slows down development and maintenance. Instead, we need something to apply the same concepts in a way that makes sense on the scale of classes and interfaces, with minimal development and runtime overhead. A Better Look at Modularity and What It Really Means Understanding the golden rule of software design and designing a system on paper such that it promotes cohesion between separate parts of the application and minimizes coupling between them is not the hardest part of applying modularity to software design. To create a truly modular system, it is important to not only have it modular in the design phase, but to also take that design and implement it in such a way that it is still modular at runtime. Modularity can therefore be subdivided in both design time modularity and runtime modularity. In the next few paragraphs, we are going to explore them a bit. Modularity is an architectural principle that starts at design time. Modules and relationships between modules have to be carefully identified. Similar to object-oriented programming, there is no silver bullet that will magically introduce modularity. There are trade-offs to be made, and patterns exist to help you do so. We will show many examples of this throughout the book. The most important step toward modularity is coming up with a logical separation of modules. This is basically what most architects will do, but they do this on the level of systems and layers. We need to do this on the code level as well, on a much more fine-grained level. This means that modularity doesn’t come for free: we need to actively work toward it. Just throwing a framework in the mix will not make a system modular all of a sudden. Design time modularity can be applied to any code base, even if you are on a traditional nonmodular Java EE application server. Identifying modules in a design will already help, creating a clear design. Without a runtime environment that respects modules, it is very hard to enforce modularity. Enforcing sounds like a bad thing, and you might say that it is the role of developers to respect modularity. It certainly is our job as developers to do so, but we can use some help. It is very difficult to not accidentally break modularity by just relying on standards and guidelines when working in a large code base. The module borders are simply too vague to spot mistakes. Over time, small errors will leak into the code base, and finally modularity will just slowly evaporate. It’s much easier to work with modules if our runtime supports it. The runtime should at least: - Enforce module isolation - Enforce and clarify module dependencies - Provide a services framework to consume modules Enforcing module isolation is making sure that other modules are not using internal classes. A module should only be used by an explicitly defined API, and the runtime should make sure that other classes and interfaces are not visible to the outside world (other modules). Enforcing module dependencies is making sure that modules only depend on a well defined set of other modules, and a module should not load when its dependencies are not resolved to prevent runtime errors. Services are another key aspect of modularity, and we will talk a lot more about them in the next chapter. Modularity Solutions In essence, one could say that classes are a pretty modular concept. However, they are very limited in a way that you cannot have much structure materialized in just plain classes. Grouping classes can be done using the concept of packages, but the intention of packages is more to provide a mechanism to organize classes in namespaces belonging to a similar category or providing similar functionality. Within a package, it is not possible to hide certain classes from classes in other packages or even from classes in the same package. Sure there are some tricks, such as inner classes, or classes contained in other classes, but in the end this does not give you a truly modular concept. An important aspect of runtime modularity is the packaging of the deployment artifact. On the Java platform, the JAR file has been the traditional unit of deployment. A JAR file holds a collection of classes or packages of classes, and their resources, and has the ability to carry some metadata about that distribution. Unfortunately, the Java runtime treats all JAR files as equal, and the information in the metadata description is ignored by both the classloader and the virtual machine. In plain Java and Java EE, all classes found in deployed JAR files are put in one large space, the classpath. In order to get the concept of runtime modularity to work, an additional mechanism is needed. The basic idea of working on a modular approach using JAR files is not a bad one at all. JAR files are not only a unit of deployment, but also a unit of distribution, a unit of reuse, and a unit that you can add a version to. There have been a number of attempts of enabling Java with a modular runtime. OSGi was an early candidate, given its Java Specification Request (JSR 8) number, but mostly because of political reasons and colliding characters, this never had a chance of success. Halfway through the 2000s, the concept of the Java Module System (JSR 277) was introduced, but it never made it into the Java runtime. As part of the original plans for Java SE 7, in what was later to become the final days of Sun as the steward of Java, a new plan for modularity was launched under its codename Jigsaw. Then there is Maven, which was originally designed to be a building system isolating application modules and managing dependencies. Finally, vendors such as RedHat have attempted to create a modularity system. In the next paragraphs, we will take a better look at the solutions that are available in Java today. OSGi OSGi is the best known modularity solution for Java. Unfortunately, it also has a reputation for being an over-engineered, hard-to-use technology. To start with the latter: it’s not. Many of the complaints are due to misunderstanding and inadequate tooling. It is true that OSGi is a complex specification. OSGi has been in use for over 10 years, in many different kind of systems. Because of this, there are many corner cases that the specification should facilitate. This is not over-engineering, but the result of evolving a standard for many years. The good news is that you won’t have to deal with most of the complexity as an application developer or architect. Understanding the basics and, more important, understanding basic modularity patterns will get you a long way. That, combined with the greatly improved tooling available today, makes OSGi hardly any more difficult to use than Java without OSGi. And it gives you the power of modularity and some really nice development features as a side effect. The rest of the book will use OSGi as the technology to work with, and instead of trying to convince you that OSGi is easy to work with, we will get you started as soon as possible and let you see for yourself. Jigsaw The most interesting alternative for OSGi seems to be Jigsaw, as it is supposed to become the standard Java modularity solution. There is one problem however: it doesn’t exist yet and will not anytime soon. Jigsaw was delayed for Java SE 8 and then again deferred to Java SE 9, which is currently scheduled for 2015–2016. The current scope of Jigsaw is also far from sufficient to build truly modular applications. It will merely be the basis to modularize the JDK itself and a basis for future work, post Java 9. Jigsaw is trying to solve two problems at the same time: modularizing the JDK itself and pushing the same model to developers. Splitting the JDK into smaller pieces makes a lot of sense, especially on “small” devices. Because of all the legacy, this is a much more difficult challenge than creating modular applications. To facilitate the JDK modularization, there will be some new language constructs to define modules, and this will also be available to developers. Unfortunately the proposal is based on concepts that will not be sufficient for application modularization. If you are looking at modularity today, Jigsaw is simply not a viable alternative. Will Jigsaw eventually be an OSGi killer? That is for the future to tell. JBoss Modules JBoss Modules is the modularity solution developed by RedHat as the basis of JBoss Application Server 7. JBoss Modules was developed with one very specific goal: startup speed of the application server. Because of this goal, JBoss Modules does a lot less than OSGi to make it faster at startup time. This made JBoss AS7 one of the fastest application servers to start up, but JBoss Modules an inadequate modularity solution for general use. The most important concept that JBoss Modules lacks is a dynamic service layer, which is the most important modularity concept while building applications. So far, there has also been little effort on making JBoss Modules usable outside of JBoss; documentation and real-life examples are very limited. Maven Although Maven isn’t really a modularity solution, it is often discussed in this context. By separating a code base in smaller projects and splitting APIs and implementations in separate Maven projects, you can get pretty decent compile time modularity. As discussed previously, compile time modularity is only half of the solution. We need runtime modularity as well, and Maven doesn’t facilitate in this at all. However, you could very well use Maven for compile time modularity while using OSGi for runtime modularity. This has been done in many projects and works well. In this book, you will see that you do not need Maven at all when using OSGi. OSGi modules (bundles) already contain the metadata required to define modules, and we don’t need to duplicate this in our build environment. Maven itself is slow and painful to use, and it’s difficult to get very fast turnarounds on code changes. For those reasons, and the fact that we actually don’t need Maven at all, we don’t advise using it as a modularity solution. Choosing a Solution: OSGi OSGi is the only mature modularity solution for Java today, and that is unlikely to change anytime soon. Although OSGi has been criticized for being too complex to use in the past, recent improvements to tooling and frameworks have changed this completely. The remainder of this book will be focused on using OSGi to achieve modularity. Although the concepts discussed in this book would work with any modularity framework, we want to keep the book as practical as possible for solving today’s problems. What Is OSGi? OSGi is a modularity framework for the Java platform. The OSGi Alliance started work on this in 1999 to support Java on devices such as set-top boxes, service gateways, and all kinds of consumer electronics. Nowadays OSGi is applied in a much broader field and has become the de facto modularity solution in Java. The OSGi framework is specified in the OSGi Core Specification, which describes the inner workings of the OSGi framework. Next to the OSGi Core Specification there is the OSGi Compendium Specification, which describes a set of standardized OSGi services such as the Log Service, Configuration Admin, and the HTTP Service. Several of the compendium services will be used in this book. Additionally, there is Enterprise OSGi, a set of specifications focused on using OSGi in an enterprise environment. This includes Remote Services, the JDBC Service, and the JPA Service. Besides these specifications, there are a number of lesser-known compendiums for residential and mobile usage that are not covered in this book. When using OSGi, you need an implementation. The most popular OSGi implementations are Apache Felix and Equinox from the Eclipse Foundation. Both are mature implementations, but the authors of this book do have a preference for Apache Felix, because Equinox tends to be a little more heavyweight, and there are some implementation choices that only make sense for Eclipse usage. Therefore, Apache Felix is the implementation of our choice used throughout this book. It really doesn’t matter much which implementation is used however, because the bundles you create and the compendium services run on any implementation. You should understand that an OSGi framework such as Apache Felix only offers an implementation of the OSGi Core Specification. When you want to use the compendium or enterprise services, you will need implementations for those as well. The great thing about this is that you never bloat your runtime with anything that you are not using. Compare that to traditional application servers. OSGi in the Real World OSGi has a very long tradition of being used in all kinds of different systems. Its history started in embedded systems such as cars and home automation gateways, where modularity was mostly envisioned as a way for modules from different vendors to coexist in the same framework, giving them independent lifecycles so they could be added and updated without having to constantly reboot the system. Another well known example is the Eclipse IDE. Eclipse is built entirely on top of OSGi, which enables the Eclipse plug-in system. While Eclipse is probably the best known OSGi example, you can consider it the worst example as well. There are many Eclipse-specific design decisions that were necessary to support the Eclipse ecosystem but can be considered bad practices for most other applications. In more recent years, we have seen a move toward the enterprise world of software, starting with application servers that based their core inner constructs on OSGi, such as Oracle GlassFish Application Server and IBM WebSphere® Application Server. The main reasons for this move to OSGi was to isolate the complexity of various parts of the application server and to optimize startup speed along the way. There are also countless examples of applications built on top of OSGi. Just like with most other technology, it is hard to find exact usage numbers, but there is a very active user base. The authors of this book use OSGi as the primary technology for most of their projects, including some very large, high-profile applications. Tooling In the past few years, a lot of progress has been made on OSGi tooling. When considering a good tool for OSGi development, we have a list of requirements it should take care of: - Automatically generate bundle JAR files - Generate package imports using byte code analysis - Provide an easy way to start an OSGi container to run and test our code - Hot code updates in a running container for a fast development turnaround - Run in-container integration tests - Help with versioning of bundles Bndtools Bndtools is by far the tool that fits these requirements best, and we strongly advise using Bndtools for OSGi development. Bndtools is an Eclipse plug-in focused on OSGi development. Under the hood, it’s based on BND. BND is a library and set of command-line tools to facilitate OSGi development. Bndtools brings this to the Eclipse IDE. When using Bndtools, you don’t have to use Maven for builds, although there is some integration. Bndtools instead generates ANT build files that can be used out of the box for headless/offline builds on a build server, for example. Bndtools also provides wizards for editing manifest files and supports repositories. Similar to Maven, Bndtools supports the concept of repositories. Repositories are basically a place where bundles are stored and indexed. A Maven repository needs external metadata (the POM file), however; while in OSGi, the metadata is already included in the bundle itself. A repository in Bndtools contains OSGi bundles that you can use within your project. We will delve deeper into using and setting up repositories later. The most appealing feature of Bndtools is running an OSGi container directly from the IDE enabling hot code updates. This improves development speed enormously and would almost justify the use of OSGi by itself. We will use Bndtools in the remainder of this book, and we strongly recommend you do so as well. The BND Maven plug-in can generate bundles and calculate package imports directly from a Maven build. Similar to Bndtools, the plug-in is based on the underlying BND library, and the code analysis used to generate package imports is the same. Other manifest details such as the bundle name and version are extracted from the POM file. This works fine, and many projects use this approach. The major downside is Maven itself. Maven is a decent build tool, but it does a very bad job at facilitating the development process. Fast development requires a fast turnaround of code changes, and this is very difficult to achieve with Maven. Because OSGi bundles already contain all the metadata required to setup dependencies, etc., there is actually no real reason to still use Maven. Eclipse Tycho Eclipse Tycho is another Eclipse plug-in that facilitates OSGi development. It is more tied toward Eclipse plug-in development and less fit for general OSGi development. Tycho is also more an addition to Maven than a complete development environment. It helps, for example, to build p2 installation sites, which again is very Eclipse specific. NetBeans and IntelliJ NetBeans currently offers only very basic support for OSGi as described on the NetBeans Wiki. IntelliJ doesn’t offer support for OSGi out-of-the-box. However, both IDEs support Maven, and using the Maven Bundle plug-in, you can develop OSGi projects in a very similar way like any other types of Maven-based projects. Although this works just as well as other types of Java projects, this model misses features such as dynamic bundle reloads and editors for bundle descriptors that Bndtools offers. Without those features, the development experience is simply much less, and you simply don’t get all the potential out of OSGi. Even if you are a NetBeans or IntelliJ user, we recommend trying Bndtools with Eclipse. Hopefully, OSGi support in NetBeans and IntelliJ will improve in the near future. Get Building Modular Cloud Apps with OSGi now with O’Reilly online learning. O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.
https://www.oreilly.com/library/view/building-modular-cloud/9781449345143/ch01.html
CC-MAIN-2021-10
refinedweb
4,462
53
From Documentation Overview Each UI object is represented by a component (Component). Thus, composing an UI object is like assembling components. To alter UI one has to modify the states and relationships of components. For example, as shown below, we declared a Window component, enabling the border property to normal and setting its width to a definite 250 pixels. Enclosed in the Window component are two Button components. As shown above, there are two ways to declare UI: XML-based approach and pure-Java approach. You can mix them if you like. Forest of Trees of Components Like in a tree structure, a component has at most one parent, while it might have multiple children. Some components accept only certain types of components as children. Some do not allow to have any children at all. For example, Grid in XUL accepts Columns and Rows as children only. A component without any parents is called a root component. Each page is allowed to have multiple root components, even though this does not happen very often. Notice that if you are using ZUML, there is an XML limitation, which means that only one document root is allowed. To specify multiple roots, you have to enclose the root components with the zk tag. zk tag is a special tag that does not create components. For example, <zk> <window/> <!-- the first root component --> <div/> <!-- the second root component --> </zk> getChildren() Most of the collections returned by a component, such as Component.getChildren(), are live structures. It means that you can add, remove or clear a child by manipulating the returned list directly. For example, to detach all children, you could do it in one statement: comp.getChildren().clear(); It is equivalent to for (Iterator it = comp.getChildren().iterator(); it.hasNext();) { it.next(); it.remove(); } Note that the following code will never work because it would cause ConcurrentModificationException. for (Iterator it = comp.getChildren().iterator(); it.hasNext();) ((Component)it.next()).detach(); Sorting the children The following statement will fail for sure because the list is live and a component will be detached first before we move it to different location. Collections.sort(comp.getChildren()); More precisely, a component has at most one parent and it has only one spot in the list of children. It means, the list is actually a set (no duplicate elements allowed). On the other hand, Collections.sort() cannot handle a set correctly. Thus, we have to copy the list to another list or array and then sort it. Components.sort(List, Comparator) is a utility to simplify the job. Desktop, Page and Component A page (Page) is a collection of components. It represents a portion of the browser window. Only components attached to a page are available at the client. They are removed when they are detached from a page. A desktop (Desktop) is a collection of pages. It represents a browser window (a tab or a frame of the browser)[1]. You might image a desktop representing an independent HTTP request. A desktop is also a logic scope that an application can access in a request. Each time a request is sent from the client, it is associated with the desktop it belongs. The request is passed to DesktopCtrl.service(AuRequest, boolean) and then forwarded to ComponentCtrl.service(AuRequest, boolean). This also means that the application can not access components in multiple desktops at the same time. Both a desktop and a page can be created automatically when ZK Loader loads a ZUML page or calls a richlet (Richlet.service(Page)). The second page is created when the Include component includes another page with the defer mode. For example, two pages will be created if the following is visited: <!-- the main page --> <window> <include src="another.zul" mode="defer"/> <!-- creates another page --> </window> Notice that if the mode is not specified (i.e., the instant mode), Include will not be able to create a new page. Rather, it will append all components created by another.zul as its own child components. For example, <window> <include src="another.zul"/> <!-- default: instant mode --> </window> is equivalent to the following (except div is not a space owner, see below) <window> <div> <zscript> execution.createComponents("another.zul", self, null); </zscript> </div> </window> Attach a Component to a Page A component is available at the client only if it is attached to a page. For example, the window created below will not be available at the client. Window win = new Window(); win.appendChild(new Label("foo")); A component is a POJO object. If you do not have any reference to it, it will be recycled when JVM starts garbage collection. There are two ways to attach a component to a page: - Append it as a child of another component that is already attached to a page (Component.appendChild(Component), Component.insertBefore(Component, Component), or Component.setParent(Component)). - Invoke Component.setPage(Page) to attach it to a page directly. It is also another way to make a component become a root component. Since a component can have at most one parent and be attached at most one page, it will be detached automatically from the previous parent or page when it is attached to another component or page. For example, b will be a child of win2 and win1 has no child at the end. Window win1 = new Window; Button b = new Button(); win1.appendChild(b); win2.appendChild(b); //implies detach b from win1 Detach a Component from a Page To detach a Component from the page, you can either invoke comp.setParent(null) if it is not a root component or comp.setPage(null) if it is a root component. Component.detach() is a shortcut to detach a component without knowing if it is a root component. Invalidate a Component When a component is attached to a page, the component and all of its descendants will be rendered. On the other hand, when a state of a attached component is changed, only the changed state is sent to client for update (for better performance). Very rare, you might need to invoke Component.invalidate() to force the component and its descendants to be rerendered[1]. There are only a few reasons to invalidate a component, but it is still worthwhile to note them down: - If you add more than 20 child components, you could invalidate the parent to improve the performance. Though the result Ajax response might be longer, the browser will be more effective to replace a DOM tree rather than adding DOM elements. - If a component has a bug that does not update the DOM tree correctly, you could invalidate its parent to resolve the problem[2]. Don't Cache Components Attached to a Page in Static Fields As described above, a desktop is a logical scope which can be accessed by the application when serving a request. In other words, the application cannot detach a component from one desktop to another desktop. This typically happens when you cache a component accidentally. For example, the following code will cause an exception if it is loaded multiple times. <window apply="foo.Foo"/> <!-- cause foo.Foo to be instantiated and executed --> and foo.Foo is defined as follows[1]. package foo; import org.zkoss.zk.ui.*; import org.zkoss.zul.*; public class Foo implements org.zkoss.zk.ui.util.Composer { private static Window main; //WRONG! don't cache it in a static field public void doAfterCompose(Component comp) { if (main == null) main = new Window(); comp.appendChild(main); } } The exception is similar to the following: org.zkoss.zk.ui.UiException: The parent and child must be in the same desktop: <Window u1EP0> org.zkoss.zk.ui.AbstractComponent.checkParentChild(AbstractComponent.java:1057) org.zkoss.zk.ui.AbstractComponent.insertBefore(AbstractComponent.java:1074) org.zkoss.zul.Window.insertBefore(Window.java:833) org.zkoss.zk.ui.AbstractComponent.appendChild(AbstractComponent.java:1232) foo.Foo.doAfterCompose(Foo.java:10) - ↑ A composer (Composer) is a controller that can be associated with a component for handling the UI in Java. For the information, please refer to the Composer section. Component Cloning All components are cloneable (java.lang.Cloneable). It is simple to replicate components by invoking Component.clone(). main.appendChild(listbox.clone()); Notice - It is a deep clone. That is, all children and descendants are cloned too. - The component returned by Component.clone() does not belong to any pages. It doesn't have a parent either. You have to attach it manually if necessary. - ID, if any, is preserved. Thus, you cannot attach the returned component to the same ID space without modifying ID if there is any. Similarly, all components are serializable (java.io.Serializable). Like cloning, all children and descendants are serialized. If you serialize a component and then de-serialize it back, the result will be the same as invoking Component.clone()[1]. - ↑ Of course, the performance of Component.clone() is much better. Version History Last Update : 2014/7/17
http://books.zkoss.org/wiki/ZK_Developer's_Reference/UI_Composing/Component-based_UI
CC-MAIN-2014-41
refinedweb
1,488
58.69
We are about to switch to a new forum software. Until then we have removed the registration on this forum. i've tried a project that when the light sensor doesn't take any light, 3 movies files play with the if+mouseover. but i dont know how to stop movies, when the light sensor take some light over certain amount. i want the black screen. not the pausing or go to first frame. import processing.serial.*; import processing.video.*; Movie dali, inner, moon; Serial port; int sec = 1000; int start_time=0; float a; void setup() { port=new Serial(this, Serial.list()[2],9600); size(1024, 768); background(0); dali = new Movie(this, "clock1.mov"); dali.loop(); inner = new Movie(this, "clock2.mov"); inner.loop(); moon = new Movie(this, "clock3.mov"); moon.loop(); } void movieEvent(Movie m) { m.read(); } void draw() { int sensor = port.read(); if(sensor>200){ if(mouseX < width /3) { image(dali, 0, 0, width, height); } else if(mouseX < 2*width /3) { image(moon, 0, 0, width, height); } else { image(inner, 0, 0, width, height); } } one more, can i hide the mouse point? i'm very new for processing. thank you for your reading. Answers If you want a black screen, then just put background(0); if your condition is true in draw() and else everything you have now. The mouse pointer may be hidden with noCursor();
https://forum.processing.org/two/discussion/12615/how-to-stop-movies-not-pause-or-go-to-first-frame-i-want-the-black-background
CC-MAIN-2020-45
refinedweb
229
76.82
If you are looking to synthesize the sound of a plucked string, there is an amazingly simple algorithm for doing so called the Karplus-Strong Algorithm. Give it a listen: KarplusStrong.wav Here it is with flange and reverb effects applied: KPFlangeReverb.wav It works like this: - Fill a circular buffer with static (random numbers) - Play the contents of the circular buffer over and over - Each time you play a sample, replace that sample with the average of itself and the next sample in the buffer. Also multiplying that average by a feedback value (like say, 0.996) Amazingly, that is all there is to it! Why Does That Work?! The reason this works is that it is actually very similar to how a real guitar string pluck works. When you pluck a guitar string, if you had a perfect pluck at the perfect location with the perfect transfer of energy, you’d get a note that was “perfect”. It wouldn’t be a pure sine wave since strings have harmonics (integer multiple frequencies) beyond their basic tuning, but it would be a pure note. In reality, that isn’t what happens, so immediately after plucking the string, there is a lot of vibrations in there that “don’t belong” due to the imperfect pluck. Since the string is tuned, it wants to be vibrating a specific way, so over time the vibrations evolve from the imperfect pluck vibrations to the tuning of the guitar string. As you average the samples together, you are removing the higher frequency noise/imperfections. Averaging is a crude low pass filter. This makes it converge to the right frequencies over time. It’s also important to note that with a real stringed instrument, when you play a note, the high frequencies disappear before the low frequencies. This averaging / low pass filter makes that happen as well and is part of what helps it sound so realistic. Also while all that is going on, the energy in the string is being diminished as it becomes heat and sound waves and such, so the noise gets quieter over time. When you multiply the values by a feedback value which is less than 1, you are simulating this loss of energy by making the values get smaller over time. Tuning The Note This wasn’t intuitive for me at first, but the frequency that the note plays at is determined ENTIRELY by the size of the circular buffer. If your audio has a sample rate of 44100hz (44100 samples played a second), and you use this algorithm with a buffer size of 200 samples, that means that the note synthesized will be 220.5hz. This is because 44100/200 = 220.5. Thinking about the math from another direction, we can figure out what our buffer size needs to be for a specific frequency. If our sample rate is 44100hz and we want to play a note at 440hz, that means we need a buffer size of 100.23 samples. This is because 44100/440 = 100.23. Since we can’t have a fractional number of samples, we can just round to 100. You can actually deal with the fractional buffer size by stepping through the ring buffer in non integer steps and using the fraction to interpolate audio samples, but I’ll leave that as an exercise for you if you want that perfectly tuned note. IMO leaving it slightly off could actually be a good thing. What guitar is ever perfectly in tune, right?! With it being slightly out of tune, it’s more likely to make more realistic sounds and sound interactions when paired with other instruments. You are probably wondering like I was, why the buffer size affects the frequency of the note. The reason for this is actually pretty simple and intuitive after all. The reason is because the definition of frequency is just how many times a wave form repeats per second. The wave form could be a sine wave, a square wave, a triangle wave, or it could be something more complex, but frequency is always the number of repetitions per second. If you think about our ring buffer as being a wave form, you can now see that if we have a buffer size of 200 samples, and a sample rate of 44100hz, when we play that buffer continually, it’s going to play back 220.5 times every second, which means it will play with a frequency of 220.5! Sure, we modify the buffer (and waveform) as we play it, but the modifications are small, so the waveform is similar from play to play. Some More Details I’ve found that this algorithm doesn’t work as well with low frequency notes as it does with high frequency notes. They say you can prime the buffer with a saw tooth wave (or other wave forms) instead of static (noise). While it still “kind of works”, in my experimentation, it didn’t work out that well. You could try using other low pass filters to see if that affects the quality of the note generated. The simple averaging method works so well, I didn’t explore alternative options very much. Kmm on hacker news commented that averaging the current sample with the last and next, instead of just the next had the benefit that the wave form didn’t move forward half a step each play through and that there is an audible difference between the techniques. I gave it a try and sure enough, there is an audible difference, the sound is less harsh on the ears. I believe this is so because averaging 3 samples instead of 2 is a stronger low pass filter, so gets rid of higher frequencies faster. Example Code Here is the C++ code that generated the sample at the top of the post. Now that you can generate plucked string sounds, you can add some distortion, flange, reverb, etc and make some sweet (synthesized) metal without having to learn to play guitar and build up finger calluses 😛 #include <stdio.h> #include <memory.h> #include <inttypes.h> #include <vector> // constants const float c_pi = 3.14159265359f; const float c_twoPi = 2.0f * c_pi; // typedefs typedef uint16_t uint16; typedef uint32_t uint32; typedef int16_t int16; typedef int32_t int32; //this struct is the minimal required header data for a wav file struct SMinimalWaveFileHeader { //the main chunk unsigned char m_chunkID[4]; uint32 m_chunkSize; unsigned char m_format[4]; //sub chunk 1 "fmt " unsigned char m_subChunk1ID[4]; uint32 m_subChunk1Size; uint16 m_audioFormat; uint16 m_numChannels; uint32 m_sampleRate; uint32 m_byteRate; uint16 m_blockAlign; uint16 m_bitsPerSample; //sub chunk 2 "data" unsigned char m_subChunk2ID[4]; uint32 m_subChunk2Size; //then comes the data! }; //this writes template <typename T> bool WriteWaveFile(const char *fileName, std::vector<T> data, int16 numChannels, int32 sampleRate) { int32 dataSize = data.size() * sizeof(T); int32 bitsPerSample = sizeof(T) * 8; //open the file if we can FILE *File = nullptr; fopen_s(&File, fileName, "w+b"); if (!File) return false; SMinimalWaveFileHeader waveHeader; //fill out the main chunk memcpy(waveHeader.m_chunkID, "RIFF", 4); waveHeader.m_chunkSize = dataSize + 36; memcpy(waveHeader.m_format, "WAVE", 4); //fill out sub chunk 1 "fmt " memcpy(waveHeader.m_subChunk1ID, "fmt ", 4); waveHeader.m_subChunk1Size = 16; waveHeader.m_audioFormat = 1; waveHeader.m_numChannels = numChannels; waveHeader.m_sampleRate = sampleRate; waveHeader.m_byteRate = sampleRate * numChannels * bitsPerSample / 8; waveHeader.m_blockAlign = numChannels * bitsPerSample / 8; waveHeader.m_bitsPerSample = bitsPerSample; //fill out sub chunk 2 "data" memcpy(waveHeader.m_subChunk2ID, "data", 4); waveHeader.m_subChunk2Size = dataSize; //write the header fwrite(&waveHeader, sizeof(SMinimalWaveFileHeader), 1, File); //write the wave data itself fwrite(&data[0], dataSize, 1, File); //close the file and return success fclose(File); return true; } template <typename T> void ConvertFloatSamples (const std::vector<float>& in, std::vector<T>& out) { // make our out samples the right size out.resize(in.size()); // convert in format to out format ! for (size_t i = 0, c = in.size(); i < c; ++i) { float v = in[i]; if (v < 0.0f) v *= -float(std::numeric_limits<T>::lowest()); else v *= float(std::numeric_limits<T>::max()); out[i] = T(v); } } //calculate the frequency of the specified note. //fractional notes allowed! float CalcFrequency(float octave, float note) /* Calculate the frequency of any note! frequency = 440×(2^(n/12)) N=0 is A4 N=1 is A#4 etc... notes go like so... 0 = A 1 = A# 2 = B 3 = C 4 = C# 5 = D 6 = D# 7 = E 8 = F 9 = F# 10 = G 11 = G# */ { return (float)(440 * pow(2.0, ((double)((octave - 4) * 12 + note)) / 12.0)); } class CKarplusStrongStringPluck { public: CKarplusStrongStringPluck (float frequency, float sampleRate, float feedback) { m_buffer.resize(uint32(float(sampleRate) / frequency)); for (size_t i = 0, c = m_buffer.size(); i < c; ++i) { m_buffer[i] = ((float)rand()) / ((float)RAND_MAX) * 2.0f - 1.0f; // noise //m_buffer[i] = float(i) / float(c); // saw wave } m_index = 0; m_feedback = feedback; } float GenerateSample () { // get our sample to return float ret = m_buffer[m_index]; // low pass filter (average) some samples float value = (m_buffer[m_index] + m_buffer[(m_index + 1) % m_buffer.size()]) * 0.5f * m_feedback; m_buffer[m_index] = value; // move to the next sample m_index = (m_index + 1) % m_buffer.size(); // return the sample from the buffer return ret; } private: std::vector<float> m_buffer; size_t m_index; float m_feedback; }; void GenerateSamples (std::vector<float>& samples, int sampleRate) { std::vector<CKarplusStrongStringPluck> notes; enum ESongMode { e_twinkleTwinkle, e_strum }; int timeBegin = 0; ESongMode mode = e_twinkleTwinkle; for (int index = 0, numSamples = samples.size(); index < numSamples; ++index) { switch (mode) { case e_twinkleTwinkle: { const int c_noteTime = sampleRate / 2; int time = index - timeBegin; // if we should start a new note if (time % c_noteTime == 0) { int note = time / c_noteTime; switch (note) { case 0: case 1: { notes.push_back(CKarplusStrongStringPluck(CalcFrequency(3, 0), float(sampleRate), 0.996f)); break; } case 2: case 3: { notes.push_back(CKarplusStrongStringPluck(CalcFrequency(3, 7), float(sampleRate), 0.996f)); break; } case 4: case 5: { notes.push_back(CKarplusStrongStringPluck(CalcFrequency(3, 9), float(sampleRate), 0.996f)); break; } case 6: { notes.push_back(CKarplusStrongStringPluck(CalcFrequency(3, 7), float(sampleRate), 0.996f)); break; } case 7: { mode = e_strum; timeBegin = index+1; break; } } } break; } case e_strum: { const int c_noteTime = sampleRate / 32; int time = index - timeBegin - sampleRate; // if we should start a new note if (time % c_noteTime == 0) { int note = time / c_noteTime; switch (note) { case 0: notes.push_back(CKarplusStrongStringPluck(55.0f, float(sampleRate), 0.996f)); break; case 1: notes.push_back(CKarplusStrongStringPluck(55.0f + 110.0f, float(sampleRate), 0.996f)); break; case 2: notes.push_back(CKarplusStrongStringPluck(55.0f + 220.0f, float(sampleRate), 0.996f)); break; case 3: notes.push_back(CKarplusStrongStringPluck(55.0f + 330.0f, float(sampleRate), 0.996f)); break; case 4: mode = e_strum; timeBegin = index + 1; break; } } break; } } // generate and mix our samples from our notes samples[index] = 0; for (CKarplusStrongStringPluck& note : notes) samples[index] += note.GenerateSample(); // to keep from clipping samples[index] *= 0.5f; } } //the entry point of our application int main(int argc, char **argv) { // sound format parameters const int c_sampleRate = 44100; const int c_numSeconds = 9; const int c_numChannels = 1; const int c_numSamples = c_sampleRate * c_numChannels * c_numSeconds; // make space for our samples std::vector<float> samples; samples.resize(c_numSamples); // generate samples GenerateSamples(samples, c_sampleRate); // convert from float to the final format std::vector<int32> samplesInt; ConvertFloatSamples(samples, samplesInt); // write our samples to a wave file WriteWaveFile("out.wav", samplesInt, c_numChannels, c_sampleRate); } Links Hacker News Discussion (This got up to topic #7, woo!) Wikipedia: Karplus-Strong String Synthesis Princeton COS 126: Plucking a Guitar String Shadertoy: Karplus-Strong Variation (Audio) – I tried to make a bufferless Karplus-Strong implementation on shadertoy. It didn’t quite work out but is still a bit interesting.
http://blog.demofox.org/2016/06/16/synthesizing-a-pluked-string-sound-with-the-karplus-strong-algorithm/
CC-MAIN-2017-22
refinedweb
1,891
55.44
If a user experiences a crash they will be prompted to submit a raw crash report, which is generated by Breakpad. The raw crash report is received by Socorro which creates a processed crash report. The processed crash report is based on the raw crash report but also has a signature, classifications, and a number of improved fields (e.g. OS, product, version). Many of the fields in both the raw crash report and the processed crash report are viewable and searchable on crash-stats. Although there are two distinct crash reports, the raw and the processed, people typically talk about a single "crash report" because crash-stats mostly presents them in a combined way. Each crash report contains a wealth of data about the crash circumstances. Despite this, many crash reports lack sufficient data for a developer to understand why the crash occurred. As well as providing a general overview, this page aims to highlight parts of a crash report that may provide non-obvious insights. Note that most crash report fields are visible, but a few privacy-sensitive parts of it are only available to users who are logged in and have "minidump access". A relatively small number of users have minidump access, and they are required to follow certain rules. If you need access, file a bug like this one. Each crash report has the following tabs: Details, Metadata, Modules, Raw Dump, Extensions, and (optional) Correlations. Details tab The Details tab is the first place to look because it contains the most important pieces of information. Primary fields The first part of the Details tab shows a table containing the most important crash report fields. It includes such things as when the crash occurred, in which product and version, the crash kind, and various details about the OS and configuration of the machine on which the crash occurred. The following screenshot shows some of these fields. All fields have a tool-tip. For many fields, the tool-tip describes its meaning. For all fields, the tool-tip indicates the key to use when you want to do searches involving this field. (The field name is usually but not always similar to the search key. E.g. the field "Adapter Device ID" has the search key "adapter_device_id".) These descriptions are shown in the SuperSearchFields API and can be modified by crash-stats superusers. The fields present in this tab vary depending on the crash kind. Not all fields are always present. The start of the "Signature" field tells you what kind of crash it is. Some special-purpose annotations are used to indicate particular kinds of crashes. Abort: A controlled abort, e.g. via NS_RUNTIMEABORT. (Controlled aborts that occur via MOZ_CRASHor MOZ_RELEASE_ASSERTcurrently don't get an Abortannotation, but they do get a "MOZ_CRASH Reason" field.) OOM | <size>, where <size>is one of large, small, unknown: an out-of-memory (OOM) abort. The <size>annotation is determined by the "OOM Allocation Size" field; if that field is missing <size>will be unknown. hang: a hang prior to shutdown. shutdownhang: a hang during shutdown. IPCError-browser: a problem involving IPC. If the parent Firefox process detects that the child process has sent broken or unprocessable IPDL data, or is not shutting down in a timely manner, it kills the child process with a crash report. These crashes will now have a signature that indicates why the process was killed, rather than the child stack at the moment. When no special-purpose annotation is present and the signature begins with a stack frame, it's usually a vanilla uncontrolled crash. The crash cause can be determined from the "Crash Reason" field. Most commonly it's a bad memory access. In that case, on Windows you can tell from the reason field if the crash occurred while reading, writing or executing memory (e.g. EXCEPTION_VIOLATION_ACCESS_READ indicates a bad memory read). On Mac and Linux the reason will be SIGSEGV or SIGBUS and you cannot tell from this field what kind of memory access it was. See this file for a detailed explanation of the crash report signature generation procedure, and for information on how modify this procedure. There are no fields that uniquely identify the user that a crash report came from, but if you want to know if multiple crashes come from a single user the "Install Time" field is a good choice. Use it in conjunction with other fields that don't change, such as those describing the OS or graphics card, for additional confidence. For bad memory accesses, the "Crash Address" field can give additional indications what went wrong. - 0x0 is probably a null pointer deference[*]. - Small addresses like 0x8 can indicate an object access (e.g. this->mFoo) via a null thispointer. - Addresses like 0xfffffffffd8 might be stack accesses, depending on the platform[*]. - Addresses like 0x80cdefd3 might be heap accesses, depending on the platform. - Addresses may be poisoned: 0xe4 indicates the address comes from memory that has been allocated by jemalloc but not yet initialized; 0xe5 indicates the address comes from memory freed by jemalloc. The JS engine also has multiple poison values defined in js/src/jsutil.h. [*] Note that due to the way addressing works on x86-64, if the crash address is 0x0 for a Linux/OS X crash report, or 0xffffffffffffffff for a Windows crash report, it's highly likely that the value is incorrect. (There is a bug report open for this problem.) You can sanity-check these crashes by looking at the raw dump or minidump in the Raw Dump tab (see below). Some fields, such as "URL" and "Email Address", are privacy-sensitive and are only visible to users with minidump access. The Windows-only "Total Virtual Memory" field indicates if the Firefox build and OS are 32-bit or 64-bit. - A value of 2 GiB indicates 32-bit Firefox on 32-bit Windows. - A value of 3 or 4 GiB indicates 32-bit Firefox on 64-bit Windows (a.k.a. "WoW64"). Such a user could switch to 64-bit Firefox. - A value much larger than 4 GiB (e.g. 128 TiB) indicates 64-bit Firefox. (The "Build Architecture" field should be "amd64" in this case.) Some crash reports have a field "ContainsMemoryReport", which indicates that the crash report contains a memory report. This memory report will have been made some time before the crash, at a time when available memory was low. The memory report can be obtained in the Raw Dump tab (see below). Bug-related information The second part of the Details tab shows bug-related information, as the following screenshot shows. The "Report this bug in" links can be used to easily file bug reports. Each one links to a Bugzilla bug report creation page that has various fields pre-filled, such as the crash signature. The "Related Bugs" section shows related bug reports, as determined by the crash signature. Stack traces The third part of the Details tab shows the stack trace and thread number of the crashing thread, as the following screenshot shows. Each stack frame has a link to the source code, when possible. If a crash is new, the regressing changeset can often be identified by looking for recent changes in the blame annotations for one or more of the top stack frames. Blame annotations are also good for identifying who might know about the code in question. Sometimes the highlighted source code is puzzling, e.g. the identified line may not touch memory even though the crash is memory-related. This can be caused by compiler optimizations. It's often better to look at the disassembly (e.g. in a minidump) to understand exactly what code is being executed. Stack frame entries take on a variety of forms. - The simplest are functions names, such as NS_InitXPCOM2. - Name/address pairs such as nss3.dll@0x1eb720are within system libraries. - Names such as F1398665248_____________________________('F' followed by many numbers then many underscores) are in Flash. - Addresses such as @0xe1a850acmay indicate an address that wasn't part of any legitimate code. If an address such as this occurs in the first stack frame, the crash may be exploitable. Stack traces for other threads can be viewed by clicking on the small "Show other threads" link. If the crash report is for a hang, the crashing thread will be the "watchdog" thread, which exists purely to detect hangs; its top stack frame will be something like mozilla::`anonymous namespace'::RunWatchdog. In that case you should look at the other threads' stack traces to determine the problem; many of them will be waiting on some kind of response, as shown by a top stack frame containing a function like NtWaitForSingleObject or ZwWaitForMultipleObjects. Metadata tab The Metadata tab is similar to the first part of the Details tab, containing a table with various fields. These are the fields from the raw crash report, ordered alphabetically by field name, but with privacy-sensitive fields shown only to users with minidump access. There is some overlap with the fields shown in the Details tab. Modules tab The modules tab shows all the system libraries loaded at the time of the crash, as the following screenshot shows. On Windows these are mostly DLLs, on Mac they are mostly .dylib files, and on Linux they are mostly .so files. This information is most useful for Windows crashes, because DLLs loaded by antivirus software or malware often cause Firefox to crash. Correlations between loaded modules and crash signatures can be seen in the "Correlations" tab (see below). This page says that files lacking version/debug identifier/debug filename are likely to be malware. Raw Dump tab The first part of the Raw Dump tab shows the raw crash report, in JSON format. Once again, privacy-sensitive fields are shown only to users with minidump access. For users with minidump access, the second part of the Raw Dump tab has some links, as the following screenshot shows. These links are to the following items. - A minidump. Minidumps can be extremely useful in understanding a crash report; see this page for an explanation how to use them. - The aforementioned JSON raw crash report. - The memory report contained within the crash report. Only crash reports with the ContainsMemoryReportfield set will have this link. - The unredacted crash report, which has additional information. Extensions tab The Extensions tab shows which extensions are installed and enabled. Usually it just shows an ID rather than the proper extension name. Note that several extensions ship by default with Firefox and so will be present in almost all crash reports. (The exact set of default extensions depends on the release channel.) The least obvious of these has an Id of {972ce4c6-7e08-4474-a285-3208198ce6fd}, which is the default Firefox theme. Some (but not all) of the other extensions shipped by default have the following Ids: webcompat@mozilla.org, e10srollout@mozilla.org, firefox@getpocket.com, flyweb@mozilla.org, loop@mozilla.org. If an extension only has a hexadecimal identifier, a Google search of that identifier is usually enough to identify the extension's name. This information is useful because some crashes are caused by extensions. Correlations between extensions and crash signatures can be seen in the "Correlations" tab (see below). Correlations tab This tab is only shown when crash-stats identifies correlations between a crash and modules or extensions that are present, which happens occasionally. See also - A talk about understanding crash reports, by David Baron, from March 2016. - A guide to searching crash reports
https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Crash_reporting/Understanding_crash_reports
CC-MAIN-2016-50
refinedweb
1,924
64.3
Traveled to Brunswick for July 4th weekend. Upon arrival at The Jameson Inn we were told we could not check in due to the hotel not having any clean linens (mind you 3 housekeepers were in the parking lot smoking for a good 25 minutes) and to come back in an hour. Upon our return (same housekeepers still in the lot) we stood at the front desk while 4 staff members were dealing with over bookings for 15 minutes before we were assisted. They then had to send someone to locate a member of the housekeeping staff to come down to see if they had rooms available yet. Another 15 minutes and we were checked in. Entering the room there was still trash in the can from the previous guest and yellow stains clearly visible on the white bedspread. Being exhausted from my 17 hour trip I went out into the hall and asked housekeeping for a trash bag and a new blanket. The blanket she brought in was an old brown, stale smoky smelling one, needless to say we did not use it. While we did get a good deal on the room, what all the websites fail to tell you is that people also reside at this motel, the pool is over ran by unsupervised children, the "residents" sit outside of their rooms in their lawn chairs and watch everything. There also seems to be a lot of sketchy activity in the parking lot. We awoke Saturday Morning to find someone getting a haircut next to the stairs. The staff doesn't seem much to care about what is going on, and they are very unprofessional, If they weren't behind the desk I would've assumed them for one of the "residents" by the way they were dressed. While it is located right off of the interstate and next to a lot of restaurants (which you will need for breakfast since the unsupervised kids & residents load up 6 plates and leave nothing) The location was the only thing that was fairly decent about this place. -, Hotels.com, Travelocity, Expedia, Orbitz, Booking.com, Tingo, Despegar.com, BookingOdigeoWL and Venere so you can book your Jameson Inn reservations with confidence. We help millions of travelers each month to find the perfect hotel for both vacation and business trips, always with the best discounts and special offers.
http://www.tripadvisor.com/ShowUserReviews-g34802-d5556172-r214307965-Jameson_Inn-Brunswick_Golden_Isles_of_Georgia_Georgia.html
CC-MAIN-2014-23
refinedweb
397
65.05
In this article, we introduce a set of CSS naming conventions that we have applied in several big projects and achieved success. The goal of these naming conventions is to eliminate the possibility of naming conflicts, facilitate debugging and maintenance, and to simplify the naming process. Info: The naming conventions we introduce here may not be optimal to browsers. However, we believe that compared with the huge advantage it brings, its performance impact is negligible. Use lower-case letters to name all CSS classes and files. And use dash characters to separate words in the name. For example, we may use names like widget-latest-comments, post.css. Divide CSS styles into separate files to facilitate team work and future maintenance. The CSS files may be named according to the following rules: global.css: this file contains global CSS styles that may be reused in different places. layout.css: this file contains CSS styles used by layout views. ControllerID.css: here ControllerID refers to any controller ID in the application. This means each controller may have its own CSS file named after its ID. For example, PostController may have a CSS file named post.css. widget-WidgetClass.css: here WidgetClass refers to the class name of a widget that requires CSS styles. For example, LatestComments may use the name widget-latest-comments.css. FeatureName.css: big features may have their own CSS files named after the feature names. For example, the Markdown content format may use the CSS file markdown.css. Other needed CSS files, such as CSS frameworks. In general, we should use CSS classes instead of IDs to style HTML elements. This is because the same ID cannot appear twice in the same XHTML page. The naming conventions for CSS classes are as follows: g-. For example, we can have names like g-submit-button, g-link-button. The declaration of the corresponding styles should be put in the aforementioned global.cssfile, and can use the simple syntax like the following: .g-link-button { ... } post/index.phpview file should content like the following: <div class="post-index"> ...view content here... </div> post/indexview, we should put the following CSS styles in the post.cssfile: /* in post.css file */ .post-index .item { ... } LatestCommentswidget should use root CSS class name as widget-latest-comments, and declare its comment styles in the widget-latest-comments.cssfile like the following: /* in widget-latest-comment.css file */ .widget-latest-comments .comment { ... } layout-. For example, the mainlayout should use CSS class named as layout-mainfor its root container. To avoid naming conflict with the inserted view content, the CSS class of container elements in the layout may be prefixed with the root container class name. For example, the header section may use the name layout-main-header; the content section may use layout-main-content. In development mode (when YII_DEBUG is true), every CSS file should be included in the main layout file. In production mode, all CSS files should be merged and compressed into a single file. The file name should contain a timestamp (e.g. styles-201010221550.css). By doing so, we can let the browser to cache the merged CSS file and thus eliminate the necessity of downloading CSS file each time. Here we introduce a strategy on how to achieve the above goal. First, we declare all CSS file names as an array in the application parameters in the application configuration. Second, write a console command to combine and compress the CSS files. The YUI coompressor may be used for this purpose. The command will read the CSS file names from the application parameters, concatenate all file contents into a single file, and call YUI compressor to minify the CSS styles. The generated file should be named with a timestamp on it. Third, modify the application main layout view by inserting the following code in the HTML head section: <head> ...... <?php if(Yii::app()->params['css.files.compressed']): ?> <link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->baseUrl.'/css/' . Yii::app()->params['css.files.compressed']; ?>" /> <?php else: ?> <?php foreach(Yii::app()->params['css.files'] as $css): ?> <link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->baseUrl.'/css/'.$css); ?>" /> <?php endforeach ?> <?php endif ?> </head> Note that in the above, we assume the CSS files are listed in the css.files application parameter. And if the files are combined and compressed, the resulting file name should be put in the css.files.compressed application parameter. The console command should modify the application configuration file to update the css.files.compressed parameter after it generates the combined and compressed CSS file. We can use the above CSS naming conventions in jQuery selectors in the application's javascript code. In particular, when selecting one or several elements using jQuery selectors, we should follow the similar rule for declaring CSS styles. For example, if we want to attach click handlers to all hyperlinks within news item blocks, we should use the following jQuery selectors: $('.news-index .item a').click(function(){ ... }); That is, a selector should be prefixed with the root container CSS class name ( news-index in the above). Total 4 comments Sounds like you can put that in an extension with a widget ;) When you use following code in the head section of the main layout file (instead of the code in the article) you can configure the inclusion of the css file regarding media and condition: The following params configuration example results in the default css files included by a clean Yii installation: Just a little note on jQuery selector using chained CSS classes. Remove spaces around class name: .news-index.item a The "Naming CSS Classes"-part talks about "widget-latest-comment". However, it is then used as both widget-latest-comment and widget-latest-comments. It should be edited to whatever is intended. Please login to leave your comment.
http://www.yiiframework.com/wiki/88/css-naming-conventions/
CC-MAIN-2015-35
refinedweb
982
57.87
Carl Banks wrote: > Travis Oliphant wrote: >> Travis Oliphant wrote: >>> Hi Carl and Greg, >>> >>> Here is my updated PEP which incorporates several parts of the >>> discussions we have been having. >> And here is the actual link: >> >> > > > What's the purpose of void** segments in PyObject_GetBuffer? It seems > like it's leftover from an older incarnation? > Yeah, I forgot to change that location. > I'd hope after more recent discussion, we'll end up simplifying > releasebuffer. It seems like it'd be a nightmare to keep track of what > you've released. Yeah, I agree. I think I'm leaning toward the bufferinfo structure which allows the exporter to copy memory for things that it wants to be free to change while the buffer is exported. > > > Finally, the isptr thing. It's just not sufficient. Frankly, I'm > having doubts whether it's a good idea to support multibuffer at all. > Sure, it brings generality, but I'm thinking its too hard to explain and > too hard to get one's head around, and will lead to lots of > misunderstanding and bugginess. OTOH, it really doen't burden anyone > except those who want to export multi-buffered arrays, and we only have > one shot to do it. I just hope it doesn't confuse everyone so much that > no one bothers. People used to have doubts about explaining strides in NumPy as well. I sure would have hated to see them eliminate the possiblity because of those doubts. I think the addition you discuss is not difficult once you get a hold of it. I also understand now why subbufferoffsets is needed. I was thinking that for slices you would just re-create a whole other array of pointers to contain that addition. But, that is really not advisable. It makes sense when you are talking about a single pointer variable (like in NumPy) but it doesn't when you have an array of pointers. Providing the example about how to extract the pointer from the returned information goes a long way towards clearing up any remaining confusion. Your ImageObject example is also helpful. I really like the addition and think it is clear enough and supports a lot of use cases with very little effort. > > Here's how I would update the isptr thing. I've changed "derefoff" to > "subbufferoffsets" to describe it better. > > > typedef PyObject *(*getbufferproc)(PyObject *obj, void **buf, > Py_ssize_t *len, int *writeable, > char **format, int *ndims, > Py_ssize_t **shape, > Py_ssize_t **strides, > Py_ssize_t **subbufferoffsets); > > > subbufferoffsets > > Used to export information about multibuffer arrays. It is an > address of a ``Py_ssize_t *`` variable that will be set to point at > an array of ``Py_ssize_t`` of length ``*ndims``. > > [I don't even want to try a verbal description.] > > To demonstrate how subbufferoffsets works, here is am example of a > function that returns a pointer to an element of ANY N-dimensional > array, single- or multi-buffered. > > void* get_item_pointer(int ndim, void* buf, Py_ssize_t* strides, > Py_ssize_t* subarrayoffs, Py_ssize_t *indices) { > char* pointer = (char*)buf; > int i; > for (i = 0; i < ndim; i++) { > pointer += strides[i]*indices[i]; > if (subarraysoffs[i] >= 0) { > pointer = *(char**)pointer + subarraysoffs[i]; > } > } > return (void*)pointer; > } > > For single buffers, subbufferoffsets is negative in every dimension > and it reduces to normal single-buffer indexing. What about just having subbufferoffsets be NULL in this case? i.e. you don't need it. If some of the dimensions did not need dereferencing then they would be negative (how about we just say -1 to be explicit)? > For multi-buffers, > subbufferoffsets indicates when to dereference the pointer and switch > to the new buffer, and gives the offset into the buffer to start at. > In most cases, the subbufferoffset would be zero (indicating it should > start at the beginning of the new buffer), but can be a positive > number if the following dimension has been sliced, and thus the 0th > entry in that dimension would not be at the beginning of the new > buffer. > > > > Other than that, looks good. :) > I think we are getting closer. What do you think about Greg's idea of basically making the provider the bufferinfo structure and having the exporter handle copying memory over for shape and strides if it wants to be able to change those before the lock is released. -Travis
https://mail.python.org/pipermail/python-dev/2007-March/072363.html
CC-MAIN-2017-17
refinedweb
710
62.38
lektor.types. Type( env, options) The fields in Records use types to specify the behavior of the values. Lektor comes with a wide range of built-in field types but it is possible to build your own by subclassing types class. A type is instantiated with two parameters: a reference to the Environment that it belongs to and a dictionary with configuration options from the ini file. A field type has to implement the value_from_raw method and set the widget property as a very basic requirement. To create a type you need to create a subclass. The name of the class needs to match the type name. If you want to name your type mything then it needs to be called MyThingType. Afterwards you can register it with the environment in setup_env: from lektor.types import Type class MyThingType(Type): widget = 'singleline-text' def value_from_raw(self, raw): return raw.value def setup_env(self, **extra): self.env.add_type(MyThingType) For more information see value_from_raw. There is a more complete example in the Plugin How To. Main method to override to implement the value conversion.
https://www.getlektor.com/docs/api/db/type/
CC-MAIN-2018-43
refinedweb
183
66.54
In this tutorial, we’ll be looking in Kotlin Generics and Variances. Table of Contents Generics Generics are a powerful feature that allows us to define a common class/method/property that can be operated using different types while keeping a check of the compile-time type safety. They are commonly used in Collections. A generic type is a class or interface that is parameterized over types. We use angle brackets (<>) to specify the type parameter. To understand Generics, we need to understand types. Every class has a type which is generally the same as the class. Though, in Kotlin a nullable type such as String? won’t be considered a class type. Same goes for a List<String> etc. An example of Kotlin Generic classes is given below: fun main(args: Array<String>) { var a = A("") var b: A<Int> = A(1) //explicit } class A<T>(argument: T) { var result = argument } We’ve instantiated the class using explicit types as well as allowing the compiler to infer them. Variance Variance is all about substituting a type with subtypes or supertypes. The following thing works in Java: Number[] n = newNumber[2]; n[0] = newInteger(1); n[1] = newDouble(47.24); This means Arrays in Java are covariant. Subtypes are acceptable. Supertypes are not. So using the covariant principle the following Java code works as well: Integer[] integerArray = {1,2,3}; Number[] numberArray = integerArray; The Number class is the parent of Integer class hence the inheritance and subtyping principle works above. But the above assignment is risky if we do something like this: numberArray[1] = 4.56 //compiles successfully This would lead to a runtime exception in Java since we cannot store a Double as an Int. Kotlin Arrays stays away from this principle by making arrays invariant by default. Subtypes are not allowed. Supertypes are not allowed. So the above runtime error won’t occur with Kotlin Arrays. val i = arrayOf(1, 2, 3) val j: Array<Any> = i //this won't compile. Hence, one of the major differences in variances between Kotlin and Java is: Applying the above concepts DON’T COMPILE when used with Generics and Collections for both Java and Kotlin. import java.util.ArrayList; import java.util.List; public class Hi { public static void main(String[] args) { List<String> stringList= new ArrayList<>(); List<Object> myObjects = stringList; //compiler error } } By default, the Generic types are invariant. In Java, we use wildcard characters to use the different type of variances. There are two major types of variances besides invariant. - Covariant - Contravariant Covariant A ? extends Object is a wildcard argument which makes the type as covariant. Our previous java code now works fine. public class Hi<T> { public static void main(String[] args) { Hi<Integer> j = new Hi(); Hi<Object> n = j; //compiler error Hi<? extends Object> k = j; //this works fine } } The third statement is an example of Covariance using wild card arguments. The modifier out is used for applying covariance in Kotlin. fun main(args: Array<String>) { val x: A<Any> = A<Int>() // Error: Type mismatch val y: A<out Any> = A<String>() // Works val z: A<out String> = A<Any>() // Error } class A<T> In Kotlin, we can directly annotate the wildcard argument on the parameter type of the class. This is known as declaration-site variance. fun main(args: Array<String>) { val x: A<Any> = A<Int>() } class A<out T> The above Kotlin code looks more readable than the Java one. fun main(args: Array<String>) { var correct: Container<Vehicle> = Container<Car>() var wrong: Container<Car> = Container<Vehicle>() } open class Vehicle class Car : Vehicle() class Container<out T> Use out Used to set substitute subtypes. Not the other way round Contraconvariant This is just the opposite of Covariance. It’s used to substitute a supertype value in the subtypes. It cannot work the other way round. It uses the in modifier fun main(args: Array<String>) { var correct: Container<Car> = Container<Vehicle>() var wrong: Container<Vehicle> = Container<Car>() } open class Vehicle class Car : Vehicle() class Container<in T> inis equivalent to <? super T> of Java. Kotlin outis equivalent to <? extends T> of Java. This brings an end to this tutorial on Kotlin Generics and Variance. This is one of the best Explanations I’ve seen about Kotlin Generics in a While 👍. It’s easier to understand. Thank You!! Glad you liked it!
https://www.journaldev.com/20454/kotlin-generics
CC-MAIN-2021-10
refinedweb
728
58.18
Consistently, one of the more popular stocks people enter into their stock options watchlist at Stock Options Channel is Starbucks Corp. (Symbol: SBUX). So this week we highlight one interesting put contract, and one interesting call contract, from the February 2017 expiration for SBUX. The put contract our YieldBoost algorithm identified as particularly interesting, is at the $52.50 strike, which has a bid at the time of this writing of 69 cents. Collecting that bid as the premium represents a 1.3% return against the $52.50 commitment, or a 6.5% annualized rate of return (at Stock Options Channel we call this the YieldBoost ). Selling a put does not give an investor access to SBUX's upside potential the way owning shares would, because the put seller only ends up owning shares in the scenario where the contract is exercised. So unless Starbucks Corp. sees its shares fall 9% and the contract is exercised (resulting in a cost basis of $51.81 per share before broker commissions, subtracting the 69 cents from $52.50), the only upside to the put seller is from collecting that premium for the 6.5% annualized rate of return. Interestingly, that annualized 6.5% figure actually exceeds the 1.7% annualized dividend paid by Starbucks Corp. by 4.8%, based on the current share price of $57.72. And yet, if an investor was to buy the stock at the going market price in order to collect the dividend, there is greater downside because the stock would have to lose 9.01% to reach the $52.7% annualized dividend yield. Turning to the other side of the option chain, we highlight one call contract of particular interest for the February 2017 expiration, for shareholders of Starbucks Corp. (Symbol: SBUX) looking to boost their income beyond the stock's 1.7% annualized dividend yield. Selling the covered call at the $60 strike and collecting the premium based on the $1.17 bid, annualizes to an additional 10% rate of return against the current stock price (this is what we at Stock Options Channel refer to as the YieldBoost ), for a total of 11.7% annualized rate in the scenario where the stock is not called away. Any upside above $60 would be lost if the stock rises there and is called away, but SBUX shares would have to climb 4% from current levels for that to occur, meaning that in the scenario where the stock is called, the shareholder has earned a 6% return from this trading level, in addition to any dividends collected before the stock was called. The chart below shows the trailing twelve month trading history for Starbucks Corp., highlighting in green where the $52.50 strike is located relative to that history, and highlighting the $60 strike in red: The chart above, and the stock's historical volatility, can be a helpful guide in combination with fundamental analysis to judge whether selling the February 2017 $57.72) to be 21%. In mid-afternoon trading on Monday, the put volume among S&P 500 components was 748,736 contracts, with call volume at 1.26 SBUX.
https://www.nasdaq.com/articles/one-put-one-call-option-know-about-starbucks-2016-12-05
CC-MAIN-2019-47
refinedweb
525
64.51
UPDATE:. For the longest time I’ve been a big fan of Rhino Mocks and have often written about it glowingly. When Moq came on the scene, I remained blissfully ignorant of it because I thought the lambda syntax to be a bit gimmicky. I figured if using lambdas was all it had to offer, I wasn’t interested. Fortunately for me, several people in my twitter-circle recently heaped praise on Moq. Always willing to be proven wrong, I decided to check out what all the fuss was about. It turns out, the use of lambdas is not the best part of Moq. No, it’s the clean discoverable API design and lack of the record/playback model that really sets it apart. To show you what I mean, here are two unit tests for a really simple example, one using Rhino Mocks and one using Moq. The tests use the mock frameworks to fake out an interface with a single method. [Test] public void RhinoMocksDemoTest() { MockRepository mocks = new MockRepository(); var mock = mocks.DynamicMock<ISomethingUseful>(); SetupResult.For(mock.CalculateSomething(0)).IgnoreArguments().Return(1); mocks.ReplayAll(); var myClass = new MyClass(mock); Assert.AreEqual(2, myClass.MethodUnderTest(123)); } [Test] public void MoqDemoTest() { var mock = new Mock<ISomethingUseful>(); mock.Expect(u => u.CalculateSomething(123)).Returns(1); var myClass = new MyClass(mock.Object); Assert.AreEqual(2, myClass.MethodUnderTest(123)); } Notice that the test using Moq only requires four lines of code whereas the test using Rhino Mocks requires six. Lines of code is not the measure of an API of course, but it is telling in this case. The extra code in Rhino Mocks is due to creating a MockRepository class and for calling ReplayAll. MockRepository ReplayAll The other aspect of Moq I like is that the expectations are set on the mock itself. Even after all this time, I still get confused when setting up results/expecations using Rhino Mocks. First of all, you have to remember to use the correct static method, either SetupResult or Expect. Secondly, I always get confused between SetupResult.On and SetupResult.For. I feel like the MoQ approach is a bit more intuitive and discoverable. SetupResult Expect SetupResult.On SetupResult.For The one minor thing I needed to get used to with Moq is that I kept trying to pass the mock itself rather than mock.Object to the method/ctor that needed it. With Rhino Mocks, when you create the mock, you get a class of the actual type back, not a wrapper. However, I see the benefits with having the wrapper in Moq’s approach and now like it very much. My only other complaint with Moq is the name. It's hard to talk about Moq without always saying, “Moq with a Q”. I’d prefer MonQ to MoQ. Anyways, if that’s my only complaint, then I'm a happy camper! You can learn more about MoQ and download it from its Google Code Page. Nice work Kzu! Addendum The source code for MyClass and the interface for ISomethingUseful are below in case you want to recreate my tests. MyClass ISomethingUseful public interface ISomethingUseful { int CalculateSomething(int x); } public class MyClass { public MyClass(ISomethingUseful useful) { this.useful = useful; } ISomethingUseful useful; public int MethodUnderTest(int x) { //Yah, it's dumb. return 1 + useful.CalculateSomething(x); } } Give it a whirl. 524:public void BackToRecord(object obj, BackToRecordOptions options)525:{526: IsMockObjectFromThisRepository(obj);527: foreach (IExpectation expectation in rootRecorder.GetAllExpectationsForProxy(obj))528: {529: rootRecorder.RemoveExpectation(expectation);530: }... internal static IMatchSyntax On<T>(this IReceiverSyntax syntax, object x, Expression<Action<T>> func, params object[] args){ string name = ((MethodCallExpression)func.Body).Method.Name; return syntax.On(x).Method(name).With(args);} Expect.Once. On<IHand>(hand, h => h.TouchIron(null), Is.Anything). Will(Throw.Exception(new BurnException()));...
http://haacked.com/archive/2008/03/23/comparing-moq-to-rhino-mocks.aspx
crawl-003
refinedweb
630
50.23
This chapter is intended for systems programmers and assumes an understanding of either the CMS or TSO command language as well as the concepts of EXEC processing. All SUBCOM interfaces are portable between CMS, TSO, and OpenEdition, so a program written for one environment can be ported to another. Although the exact internal processing (or effect of SUBCOM functions) is system-dependent, these differences are transparent to the user, so a program's operation on different systems is still predictable. Even SUBCOM programs with substantial differences in required CMS and TSO behavior can usually be written with the system dependencies isolated to smaller parts of the program. execget, which obtains a subcommand from an appropriate source execid, which extracts the subcommand name and may perform additional system-dependent processing, for example, recognizing system-defined use of special characters in the subcommand execmsg, which sends diagnostic messages, the exact form of which can be controlled by the user execrc, which sets the return code from the completed subcommand and may perform additional system-dependent processing. execinitfunction is used to initialize the subcommand environment (and assign a name to it), and execendis used to terminate the environment. The set of library functions that implement the SUBCOM interface can be summarized as follows: execinit establishes and assigns a name to a SUBCOM environment. execcall execend execget execid execinit execmsg execmsi execrc execshv execinit(...); /* Set up environment. */ for(;;) { execget(...); /* Get a subcommand. */ cmd = execid(...); /* Identify subcommand. */ if (strcmp(cmd,"END")==0) break; if (strcmp(cmd,"EXEC")==0) execcall(...); /* Implement exec. */ else process(...); /* Process the subcommand. */ execrc(...); /* Set the return code. */ } execend(); /* Terminate the environment.*/ To use the SUBCOM facility under CMS, a program must tell CMS its name and the address to which CMS should pass the commands. The next step is to give the program the commands. Under CMS the user typically uses an EXEC to pass the commands. Because commands in an EXEC are sent by default to CMS, however, an alternate destination can be specified via the address statement (in REXX) or the &SUBCOMMAND statement (in EXEC2). After the program has handled the command, it returns to CMS so that CMS can get another command for the program to handle. Therefore, subcommand processors are being invoked continually and returning to CMS until they are told to stop or are interrupted. CMS also has a facility for letting the user program call the EXEC processor directly. In this case, the EXEC processor sends commands by default to the program instead of CMS. To invoke an EXEC for itself, the program again must first declare itself via SUBCOM so that it can get commands. In this case, it then calls CMS to tell it the name of a file that the EXEC processor will execute. The EXEC processor executes the file and sends the commands to the program. To facilitate this processing, the SUBCOM interface uses the CMS SUBCOM facility that enables a subcommand entry point. To invoke an EXEC, the interface calls the EXEC processor with the filename and filetype of the EXEC to be executed. The SUBCOM implementation for TSO is closely tied to traditional CLIST processing. The execget function reads the CLIST input by calling the PUTGET routine. The execcall function, which invokes a new CLIST, does so by calling the EXEC command. When using the SUBCOM interface to communicate with a REXX EXEC in TSO, the EXEC must specifically address (via the ADDRESS command) the SAS/C application's environment to send it subcommands. The default environment for EXECs invoked from SAS/C is still TSO. The name to be addressed is the value of the first argument to execinit. Note that a REXX EXEC that addresses a SUBCOM application cannot be called using the system function. If this is attempted, any subcommand addressed to the SUBCOM application will fail with a return code of -10. The TSO SUBCOM implementation for calling a REXX EXEC is somewhat different from the CLIST implementation. In this case, execinit defines a host-command environment routine to process subcommands addressed to the application. When execget is called, control is transferred from the SUBCOM application to REXX. When the REXX EXEC generates a subcommand for the application, REXX calls the Host Command Environment routine, which passes the subcommand back to execget. execfamily of functions. However, when a REXX EXEC is invoked in this fashion, it runs in a separate address space from its caller, and only the standard REXX environments (such as the MVS and SYSCALL environments) are available. The SAS/C SUBCOM implementation for OpenEdition uses the oeattach function to invoke REXX in the same address space as its caller. This allows the library to establish the additional SUBCOM environment used for communication with the calling program. The IBM support routine BPXWRBLD is used to establish a REXX environment that is OpenEdition aware, so that REXX input and output will be directed to the hierarchical file system rather than to DDnames. The SAS/C REXX interface under the shell runs as a separate process from the calling program to prevent interference between the program and EXEC processing. When the REXX interface is created by a call to execinit, the program's environment variables and file descriptors are copied to the REXX interface process. This copy of the environment is not affected by any changes requested by the program, including the use of setenv or close. REXX input and output are always directed to the REXX process' file descriptors 0 and 1, even if these descriptors have been reopened by the program after the call to execinit. Note that a REXX script invoked by the system function under OpenEdition cannot address the invoker's SUBCOM environment. Any attempt to do so will fail with return code -3 (command not found). A program with interactive style gets subcommands from the terminal. This style program, even if it is invoked from an EXEC or CLIST, begins by reading from the terminal and accepts EXEC or CLIST input only as the result of terminal input (such as an EXEC command from the user). Commands in an EXEC or CLIST following a call to an interactive program can be executed only after that program terminates. A program with noninteractive style receives subcommands from an EXEC or CLIST. If this style program is invoked from an EXEC or CLIST, it gets its input from that EXEC or CLIST and takes input from the terminal only as a result of commands from the EXEC or CLIST or after that EXEC or CLIST has terminated. For example, an EXEC or CLIST could contain the following commands: CPGM1 (options) SUBCMD2 ( options)If the program CPGM1 is interactive, the SUBCMD2 input line is not read by CPGM1 or processed at all until CPGM1 terminates. If CPGM1 is noninteractive, however, the SUBCMD2 line is read by CPGM1 the first time it calls execgetto get a line of input. Under CMS, most processors are defined as interactive. In versions of CMS after VM/SP 5, we do not recommend noninteractive programs. Under TSO, most processors are defined as noninteractive. An interactive program must create a new version of the TSO stack to avoid reading input from the CLIST that invoked it. Under the OpenEdition shell, only the interactive mode of SUBCOM is supported. #include <exec.h> int execcall(const char *cmd); execcallfunction invokes an EXEC or CLIST. The character string pointed to by cmdis an EXEC command. The exact format of the command is system-dependent. cmdcan include a specification of the file to execute and also operands or options. The library assumes that both "EXEC cmdname operands" and "cmdname operands" are valid arguments to execcall, but the exact details are system-dependent. (Under OpenEdition, the command string should not begin with "EXEC" unless the intent is to invoke a REXX script named EXEC.) execcallfunction returns 0if the call is successful or nonzero if the call is not successful. A nonzero return code indicates that the EXEC or CLIST could not be executed. Under TSO, the return code is that of the EXEC command or a negative return code whose meaning is the same as that from the system function. However, if execcall is used to call a TSO REXX EXEC that terminates without passing any subcommands to the C program, the return code is that set by the EXEC's RETURN or EXIT statement. This cannot always be distinguished from an EXEC command failure. Under the OpenEdition shell, as under TSO, the return code from execcall may reflect either a failure of the REXX interface (IRXJCL) or a return code set by the called EXEC. execcallfunction is valid only for programs that have defined an environment name through execinit. Once execcall is used successfully, future execget calls are expected to read from the EXEC or CLIST. execget returns "*ENDEXEC rc " the first time it is called after a CLIST or EXEC invoked by execcall has completed, where rc is the return code from the CLIST or EXEC. Subsequent calls to execget result in terminal reads. execcalldoes not cause any of the statements of the EXEC or CLIST to be executed. execcallfinds the file to be executed and completes the parameter list to be processed. Under CMS, the macro to be invoked has a filename of execname and a filetype of envname, where envname was specified by the call to execinit. If the macro cannot be found, an error code is returned. Otherwise, execcall saves the fileid but does not invoke the macro. The next call to execget invokes the EXEC processor with the EXEC parameter list and a FILEBLOK indicating the filename (from execcall) and filetype (from execinit) of the macro. Under TSO, execcall uses the ATTACH macro to call the EXEC command. Any CLIST arguments are processed at this time, and prompts are generated for any omitted arguments. No other CLIST processing occurs until execget is called. For a TSO REXX EXEC, execcall executes the statements of the EXEC up to the first subcommand addressed to the program's environment before control is returned to the program. Note that if errors are detected by the EXEC command, the TSO stack is flushed, and a diagnostic message is printed by EXEC. Under the OpenEdition Shell, the requested REXX EXEC is invoked using the IRXJCL service routine. Due to limitations of this service, the name of the EXEC is limited to eight characters. The EXEC must be an executable file, and must reside in one of the directories defined by the PATH environment variable. The statements of the EXEC up to the first subcommand addressed to the program's environment will be processed before control is returned to the program. execgetfunction and the comprehensive SUBCOM example. #include <exec.h> int execend(void); execendfunction is called to terminate subcommand processing. execendfunction returns 0if the call is successful or nonzero if the call is not successful. A nonzero value is returned when there is no previous successful call to execinitor if execendencounters other errors during its processing. Further use of a SUBCOM environment created by execinitis not possible after a call to execend, if execenddoes not complete successfully. execcallare active when execendis called, the effect is system-dependent and also can depend on whether the previous call to execinitwas interactive. Under CMS, if the program invokes an EXEC via execcall and then calls execend (see the IMPLEMENTATION section) before processing the entire EXEC, execend allows the EXEC processing to complete. All remaining subcommands are accepted but ignored, and the return code for each subcommand is set to - 10 . Under TSO, if the original execinit call is interactive, any active CLISTs started by execcall are terminated when execend is called. If the execinit call is noninteractive, however, any such CLISTs continue to execute and may generate input for the processor that called the C program. If the execend function is called with one or more TSO REXX EXECs still active, the EXECs continue to execute, but any attempt to send a subcommand to the application that called execend results in a REXX RC of - 10 and a message. The call to execend is not considered to be complete until all active REXX EXECs have terminated. If execinit is called in noninteractive mode, any CLISTs on the TSO stack beneath the first REXX EXEC at the time of a call to execend remain active. Under the OpenEdition shell, the behavior is the same as under CMS. execinit, execendcauses all CLISTs invoked by execcallto be forcibly terminated. If execinitcreates a new stack allocation, the previous allocation is restored. Similarly, if SUBCOM is initialized as interactive, execend deletes the current REXX data stack, restoring the stack defined when execinit was called. If SUBCOM is initialized as noninteractive, the REXX data stack is not modified. execgetfunction and the comprehensive SUBCOM example. #include <exec.h> char *execget(void); execgetfunction obtains a subcommand from a CLIST or EXEC or from the terminal if no CLIST or EXEC input is available. It returns the address of a null-terminated string containing the subcommand. The area addressed by the pointer returned from execgetremains valid until the next call to execget. If an EXEC or CLIST is active and accessible, input is obtained from that EXEC or CLIST; otherwise, the user is prompted with the name of the environment and a colon, and the next line of terminal input is returned to the program. (Before the prompt is issued, input is taken from the REXX data stack, if the stack is not empty.) If the SUBCOM interface is initialized with an interactive call to execinit, any EXECs or CLISTs active at the time are inaccessible. Additionally, under TSO, any input on the REXX data stack is inaccessible. Therefore, for such programs, a call to execget reads from the terminal unless execid or execcall has invoked a new CLIST or EXEC. If all active EXECs or CLISTs terminate and the data stack becomes empty, execget returns a pointer to the string "*ENDEXEC rc ". The component "*ENDEXEC" is a literal character string provided as a dummy subcommand. The component "rc" is an appropriate return code. The "rc" can be omitted if no return code is defined. Subsequent calls to execget issue terminal reads, using a prompt formed from the original envname suffixed with a colon. The "*ENDEXEC" convention was designed for the convenience of programs that want to use execget to read only from CLISTs or EXECs, while using another form of normal input (for instance, a full-screen interface). Such programs use execget only after execcall (or at start-up, if noninteractive) and switch to their alternate form of input after execget returns "*ENDEXEC". execgetfunction returns a pointer to a buffer containing the subcommand string. If no subcommand can be returned due to an unexpected system condition, execgetreturns NULL. execgetfunction is rejected when there is no environment name defined via execinit. Under TSO, a CLIST can use the TERMIN statement to switch control from the CLIST to the terminal. Use of TERMIN when the SUBCOM interface is initiated with a noninteractive call causes "*ENDEXEC" to be returned, even when the CLIST has not ended. The CMS SUBCOM interface acknowledges two logical cases of SUBCOM processing. The first case is when the program is accepting subcommands from an EXEC that is invoked external to the program. The second case occurs when the program is accepting subcommands from an EXEC invoked by execcall (see the execcall description). If the program is accepting subcommands from an EXEC invoked externally and the EXEC terminates without sending a subcommand to execget, the string "*ENDEXEC" is placed in the subcommand buffer without a return code value because the return code belongs to the environment that invoked the EXEC (usually CMS). Subsequent calls to execget read from the terminal. If the program terminates before all the subcommands in the EXEC are processed, the remaining subcommands are issued to CMS. Under most circumstances, CMS responds with an error message and a return code of - 3. (Refer also to the note on *ENDEXEC in the section CAUTIONS under execcall.) Note that under the OpenEdition shell, input is read from the REXX process' file descriptor 0 if no EXEC is active and there is no data present on the data stack. File descriptor 0 is normally allocated to the terminal, but could be directed elsewhere if the program's standard input had been redirected when execinit was called. Premature termination of programs that have invoked an EXEC via execcall are handled by execend. See the section CAUTIONS following the execend description. execcalldescription. Under TSO, execget issues the PUTGET MODE macro to get a line of input if the current input source is a CLIST or the terminal. If the current input source is a REXX EXEC, the next input line is obtained from the host-command environment routine. In interactive mode, "*EXECEND" is returned when the current allocation of the TSO stack becomes empty. In noninteractive mode, "*EXECEND" is returned when control passes from a CLIST to the terminal, or on the first call if no CLIST is active when program execution begins. Under OpenEdition, if no EXEC is active when execget is called, execget reads a line from the REXX process' file descriptor 0 using the IRXSTK service routine's PULLEXTR function. execcall. #include <exec.h> #include <string.h> int rc; char *cmd; cmd = execget(); if (cmd != 0 && memcmp(cmd,"*ENDEXEC",8)) execend(); else { rc = execcall(cmd); execrc(rc); } Note: Also see the comprehensive SUBCOM example. #include <exec.h> char *execid(char **cmdbuf); execidfunction parses a line of input as a subcommand, according to system-specific conventions. cmdbufis a pointer to the address of the line of input. When execidreturns, *cmdbufis altered to address the first operand of the subcommand or the null character ending the string. The return value from execidis a pointer to the subcommand name. The execid function can enforce syntax conventions of the host system. This is useful particularly in TSO applications. For example, under TSO, execid checks to see if the subcommand begins with the '%' character, and then treats it as an implicit EXEC command if it does. In such cases, execid can preempt processing of the subcommand. If it does, it returns a command name of "*EXEC" to indicate that processing of the subcommand has been preempted, that a new EXEC may have been invoked, and that the program should get another line of input. If the PCF-II product is installed on TSO, execid also processes the PCF-II X command and returns "*EXEC" on completion of PCF-II processing. Under MVS and CMS, execid uppercases the input command name in accordance with TSO and CMS conventions. Under the OpenEdition shell, the command name is not uppercased, in accordance with UNIX conventions. execidfunction returns a pointer to the subcommand name if the call is successful or 0if it failed. A 0 return code from execid always means that the program should expect subsequent input to come from a CLIST or an EXEC. (The next execget that reads from the terminal always returns "*ENDEXEC".) execidis valid for a program without an environment name defined is system-dependent. The execid function does no validation of the subcommand name. It is the responsibility of the program to decide whether to accept the subcommand. Under TSO, if execid is not called for a subcommand, the CLIST variable &SYSSCMD does not contain the current subcommand name. execidis optional. However, the environmental integration it provides may be helpful in TSO applications. Under TSO, execid calls the IKJSCAN service routine to extract the subcommand name. If IKJSCAN indicates that the % prefix was used, execid calls the EXEC command to process an implicit CLIST request and returns "*EXEC" to indicate this. #include <exec.h> char *cmdname, *operands; cmdname = execid(&operands); Note: Also see the comprehensive SUBCOM example. #include <exec.h> int execinit(const char *envname, int interactive); execinitfunction establishes a SUBCOM environment with the name specified by envname. The characteristics of envnameare system-dependent. Under TSO, the value of envnameis available through the standard CLIST variable &SYSPCMD or the REXX call SYSVAR(SYSPCMD). Under CMS, the value of envnameis the environment addressed by an EXEC to send subcommands. Also under CMS, for EXECs invoked via execcall, the environment is used as the filetype of the EXEC. The interactive argument is a true-or-false value (where 0 is false and nonzero is true) indicating whether the program should run as an interactive or noninteractive SUBCOM processor. Because the interactive argument to execinit can be a variable, it is possible for a program to choose its mode according to a command-line option, allowing complete flexibility. An interactive processor is one that normally accepts input from the terminal, even if the program is invoked from an EXEC or CLIST. A noninteractive processor is one that is normally called from an EXEC or CLIST and that takes input from the EXEC or CLIST that calls it. Using this terminology, most CMS processors, such as XEDIT, are interactive, while most TSO processors, such as TEST, are noninteractive. Note that TSO REXX does not allow a program invoked from an EXEC to read input from the same EXEC. For TSO REXX applications, the only distinction between interactive and noninteractive mode is that, in interactive mode a new REXX data stack is created, while in noninteractive mode the previous data stack is shared with the application. Similarly, noninteractive mode is not supported under the OpenEdition shell. execinitfunction returns 0if the call is successful or nonzero if the call is not successful. Reasons for failure are system-dependent. Possible errors include a missing or invalid envnameor, under CMS, a nonzero return code from the CMS SUBCOM service. execinitmore than once without an intervening call to execend. Under CMS, a program that calls execinitmust have been called directly from CMS. Calls from other languages, including assembler front ends, are not supported. Noninteractive SUBCOM processing is not supported under bimodal CMS or OpenEdition. Under TSO, when a program calls execinit with interactive set to true (nonzero), it is not possible for CLISTs invoked by that program to share GLOBAL variables with the CLIST that called the program. If the value of interactive is true (nonzero) and the SAS/C program is invoked from an EXEC or CLIST, the remaining statements of the EXEC or CLIST are inaccessible via execget. If execget is called before the use of execcall, or after any EXECs or CLISTs called by execcall have terminated, the program gets input from the terminal. If the value of interactive is false ( 0) and the SAS/C program is invoked from a CMS EXEC or TSO CLIST, then calls to execget without the use of execcall read from that EXEC or CLIST. Under TSO, if the value of interactive is true, a new allocation of the REXX data stack is created, and the previous data stack contents are inaccessible until execend is called. execinitinvokes the CMS SUBCOM service. The name of the environment is envname, truncated to eight characters if necessary and translated to uppercase. Under CMS, the execinit function creates a nucleus extension called L$CEXEC with the ENDCMD attribute. This is done so that premature EXEC termination can be detected (see the execget function description). If the CMS command NUCXDROP L$CEXEC is issued to delete this nucleus extension, the program continues to execute, but premature termination is not detected. If this happens, the program remains active, but control cannot be transferred from CMS back to the program. Therefore, it is not recommended that you use NUCXDROP L$CEXEC. For more information, see "Guidelines for Subcommand Processing" at the end of this chapter. Under TSO, the value of envname is stored in the ECTPCMD field of the Environment Control Table (ECT). When the value of interactive is true, a new allocation of the TSO stack is created, if necessary, to preserve the status of a previously executing CLIST. Under the OpenEdition shell, execinit creates a new process using the oeattach function. This process invokes the BPXWRBLD service to create an OpenEdition REXX language environment. #include <exec.h> #include <stdio.h> int rc; . . . if (rc = execinit("EXENV",0)) printf("Failed to establish SUBCOM envr\n"); Note: See also the comprehensive SUBCOM example. #include <exec.h> int execmsg(const char *id, char *msg); execmsgfunction sends a message to the terminal, editing it in a system-dependent way. The character string pointed to by idis a message identifier that either can be sent or suppressed. idcan be 0to indicate the absence of the message identifier. The character string pointed to by msgis the actual message text. execmsgfunction returns 0if the call is successful or nonzero if the call fails. Reasons for failure are system-dependent. For example, under TSO a message cannot be sent if it is longer than 256 characters, including the identifier. execmsgcannot fail under CMS, although depending on the current EMSG setting, the message may not be sent. idis NULL, although the TSO effects are the same. Under CMS, the maximum message length, for the ID and text, is 130 characters. If it is longer, the message text is truncated. The execmsg function edits the message according to the user's EMSG setting. No message is sent in the following situations: idis NULL msgis NULL. execmsgcan be trapped by the CLIST command output trapping facility (the symbolic variables &SYSOUTTRAP and &SYSOUTLINEnnnn). Terminal output sent in other ways (such as using the standard SAS/C I/O facilities) is not trapped. Under OpenEdition, messages sent using execmsg are sent to file descriptor 1 of the REXX interface process, which is normally the terminal. OpenEdition does not support suppression of message IDs. idis 0). Under CMS, the message is edited via DIAG X'5C' and sent to the terminal by TYPLIN or LINEWRT. Under OpenEdition, the message is sent to the REXX process' file descriptor 1 using the IRXSAY service routine. The execmsg function can be used by programs that have not defined an environment name with execinit under CMS or TSO; however, prior use of execinit is required under OpenEdition. #include <exec.h> static char *id="EXEC-MSG"; execmsg(id,"File not found"); Note: See also the comprehensive SUBCOM example. #include <exec.h> int execmsi(void); execmsifunction tests the user's preferences for printing system messages, specifically, whether message IDs should be printed or suppressed. Under TSO, execmsiindicates whether PROFILE MSGID or PROFILE NOMSGID is in effect. Under CMS, execmsitests whether the CP EMSG setting is EMSG ON, EMSG TEXT, EMSG CODE, or EMSG OFF. Under OpenEdition, execmsi always returns MSI_MSGON, indicating that message IDs should be printed. execmsifunction returns an integer value indicating the user's message processing preference. Symbolic names for these return values are defined in the header file <exec.h>, as follows: MSI_MSGON specifies to print message and message id (TSO PROFILE MSGID or CMS SET EMSG ON or OpenEdition). MSI_MSGTEXT specifies to print message text only (TSO PROFILE NOMSGID or CMS SET EMSG TEXT). MSI_MSGCODE specifies to print message ID only (CMS SET EMSG OFF). MSI_MSGOFF specifies not to print messages (CMS SET EMSG OFF). MSI_NOINFO specifies that the information is unavailable (MVS batch). stderrbased on the return code from execmsi: #include <stdio.h> #include <string.h> #include <exec.h> void msgfmt(int msgid, char *msgtext) { int rc; rc = execmsi(); switch (rc) { case MSI_MSGON: /* id + text */ default: fprintf(stderr, "%d -- %s\n", msgid, msgtext); break; case MSI_MSGTEXT: /* text only */ fprintf(stderr, "%s\n", msgtext); break; case MSI_MSGCODE: /* id only */ fprintf(stderr, "%d\n", msgid); break; case MSI_MSGOFF; /* no message */ break; } return; } #include <exec.h> int execrc(int rc); execrcfunction is used to set the return code of the most recently executed subcommand. The return code is passed back to any executing EXEC or CLIST and is accessible via the REXX RC variable, the EXEC2 &RC variable, or the CLIST &LASTCC variable. In all environments, a negative return code is treated as a more serious error than a positive code. execrcfunction returns the maximum return code value that is specified so far. That is, the return value is the maximum of the current execrcargument and any previous argument to execrc. Under TSO and OpenEdition, the return code is replaced by its absolute value before the maximum is computed. execrc returns a negative value if it is unable to successfully store the requested return code. execrcis called more than once for the same subcommand, the last value set is used, but the execrcreturn value may reflect the previous value. If execrc is not called for each subcommand, the old value of rc is retained. If execrc is not called at all for a subcommand, the return code for the previous subcommand is set, or 0 is used if there is no previous value. rcis negative, the IKJSTCK service routine is called to flush the stack. Then, the absolute value of rcis stored in the ECTRCDF field, which the CLIST processor uses as the value of the &LASTCC variable. However, a call to execrc with a negative argument does not flush a REXX EXEC because this functionality is not present in TSO REXX. In this case, the EXEC receives rc unchanged, not its absolute value, as for a CLIST. If execrc is called with a negative argument and one or more CLISTs are active, the CLISTs are still flushed until a REXX EXEC or the terminal is at the top of the stack, at which point flushing stops. Under CMS, the rc value is the R15 value returned when control is returned to CMS, presumably in search of a new subcommand. execgetfunction and the comprehensive SUBCOM example. #include <exec.h> int execshv(int code, char *vn, int vnl, char *vb, int vbl, int *vl); execshvfunction can be called in any situation where an EXEC or CLIST is active. Under OpenEdition, execshvcan be used only when an EXEC invoked by execcallis active. execshv performs the following tasks: char codedetermines what action execshvperforms and how the remaining parameters are used. <exec.h>defines the following values that can be used as the value of code: SHV_DROP SHV_FETCH vb. The variable name is translated to uppercase before being used. SHV_FIRST SHV_NEXTfetch next sequence and retrieves the first in the list of all names and values of all REXX or CLIST variables as known to the REXX or CLIST interpreter. The particular variable fetched is unpredictable. SHV_NEXT execshvwith SHV_FIRSTor any other value for code. SHV_SET vn, is ignored (no distinction is made between uppercase and lowercase characters). vn, vnl, vb, vbl, and vlare controlled by code.The values of these arguments are summarized in Table 7.1. Table 7.1 execshv Argument Values +-------------+-------------+------------+------------+------------+-------------+ | SHV_SET | addresses | length of | addresses | length of | ignored | | | the name | the | a buffer | the value. | | | | of the | variable | containing | If 0, then | | | | variable | name. If | the value | the vlaue | | | | | 0, then | to be | is assumed | | | | | the name | assigned | to be num- | | | | | is assumed | | terminated | | | | | to be | | | | | | | null-ter | | | | | | | minated. | | | | | | | | | | | | | | | | | | | | | | | | | |-------------|-------------|------------|------------|------------|-------------| | SHV_FETCH | addresses | length of | addresses | length of | addresses | | | the name of | of the | a buffer | the buffer | an int | | | the variable| variable | to which | | where the | | | | name. If | the vlaue | | actual | | | | 0, then | of the | | length of | | | | the name | variable | | the value | | | | is assumed | is copied | | will be | | | | to be null-| | | stored. If | | | | terminated | | | null, then | | | | | | | the value | | | | | | | will be | | | | | | | null-ter | | | | | | | minated. | | | | | | | | | | | | | | | | | | | | | | |-------------|-------------|------------|------------|------------|-------------| | SHV_FIRST | addresses | length of | addressed | length of | addresses | | | a buffer | the | a buffer | the buffer | an int | | SHV_NEXT | where the | variable | to which | buffer | where the | | | name is | name | the value | | actual | | | copied. The | buffer | of the | | length of | | | name | | variable | | the value | | | returned | | is copied | | will be | | | is null- | | | | stored. | | | terminated. | | | | If null, | | | | | | | then the | | | | | | | value will | | | | | | | null-ter | | | | | | | minated | | | | | | | | | | | | | | | | | | | | | | |-------------|-------------|------------|------------|------------|-------------| | SHV_DROP | addressee | length of | ignored | ignored | ignored | | | the name | the name. | | | | | | of the | If 0, the | | | | | | variable | name is | | | | | | | assumed | | | | | | | to be null-| | | | | | | terminated.| | | | | | | | | | | | | | | | | | +-------------+-------------+------------+------------+------------+-------------+ execshvfunction returns a negative value if the operation cannot be performed and a nonnegative value if it is performed. <exec.h>defines the negative values from execshvas follows: SHV_NO_SUBCOM SHV_NO_MEM SHV_LIBERR execshvinternal library error. SHV_INVALID_VAR SHV_INVALID_FUNC SHV_SET, SHV_FETCH, SHV_DROP, SHV_FIRST, or SHV_NEXT. SHV_NOT_SUPPORTED SHV_SIGNAL execshvare any one or more of the following. When one or more of these conditions are true, a logical OR is performed to indicate that the condition occurred. SHV_SUCCESS SHV_NOT_FOUND SHV_LAST_VAR SHV_NEXTloop have been fetched, as in an end-of-file return. The returned variable name and value are unpredictable. SHV_TRUNC_VAL SHV_FETCH, SHV_FIRST, or SHV_NEXT, the buffer addressed by vbis too short to contain the entire value of the variable. If vladdresses an int, the actual length of the value is stored in *vl. SHV_TRUNC_VAR SHV_FIRSTor SHV_NEXT, this value may be returned if the buffer addressed by vnis too short to contain the entire variable name. execshvuses the direct interface to REXX and EXEC2 variables provided by EXECCOMM. Under TSO, execshvuses the IKJCT441 interface to CLIST and REXX variables. Under OpenEdition, execshvuses the IRXEXCOM service. <exec.h>function also defines five macros for use with execshv: shvset, shvfetch, shvdrop, shvfirst, and shvnext. These macros SET, FETCH, DROP, FETCH FIRST in SEQUENCE, and FETCH NEXT in SEQUENCE, respectively, by expanding to the full form of the execshvfunction call to process REXX/EXEC2 or CLIST variables. Using these macros can, in some situations, simplify the use of execshvconsiderably. The definition of each macro is shown here, followed by an example of its use: /* shvset macro */ #define shvset(vn, vb) execshv(SHV_SET, vn, 0, vb, 0, 0) rc = shvset("XXXVAR","THIS_VALUE"); /* shvfetch macro */ #define shvfetch(vn, vb, vbl) execshv(SHV_FETCH, vn, 0, vb, vbl, 0) char valbuf[50]; rc=shvfetch("RVAR",valbuf,sizeof(valbuf)); /* shvdrop macro */ #define shvdrop(vn) execshv(SHV_DROP, vn, 0, NULL, 0, 0) rc = shvdrop("XXXVAR"); /* shvfirst macro */ #define shvfirst(vn, vnl, vb, vbl) execshv(SHV_FIRST, vn, vnl, vb, vbl, 0) /*shvnest macro */ #define shvnext(vn, vnl, vb, vbl) execshv(SHV_NEXT, vn, vnl, vb, vbl, 0) char vname[50], valbuf[255]; rc = shvfirst(vname,vnl,valbuf,sizeof(valbuf)); rc = shvnext (vname,vnl,valbuf,sizeof(valbuf)); shutstc.c, demonstrates how to list all current REXX, EXEC2 or CLIST variables accessible to a program. #include <exec.h> #include <lcio.h> #include <stdio.h> main() { int rc; int len; char namebuf[20]; char valbuf[200]; rc = execshv(SHV_FIRST,namebuf,20,valbuf,200,&len); while (rc >= 0 && !(rc & SHV_LAST_VAR)) { if (rc & SHV_TRUNC_VAR) { puts("Variable name truncated."); } if (rc & SHV_TRUNC_VAL) { puts("Variable value truncated."); printf("Actual value length is %d\n",len); } printf("The variable name is: %s\n",namebuf); printf("The variable value is: %.*s\n",len,valbuf); rc = execshv(SHV_NEXT,namebuf,20,valbuf,200,&len); } }The following EXEC, which should be named shutst.exec, will declare several variables. The shutstc.ccan be called to print these variables to the terminal. Arnie = "cute" Becca = "beautiful" . . . 'shutstc' exit(0) interactoption in execinit. A copy of this example is provided with the compiler and library. See your SAS Software Representative for SAS/C compiler products for more information. #include <exec.h> #include <ctype.h> #include <lcstring.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> main(int argc, char **argv) { /* If 0, next input expected from EXEC. If nonzero, next input */ /* expected from terminal. */ int interact; char *input, *cmdname, *operands; int maxrc = 0; int thisrc; char msgbuff[120]; int result; interact = (argc > 1 && tolower(*argv[1]) == 'i'); /* If first argument starts with 'i', use interactive mode. */ result = execinit("EXAMPLE", interact); if (result != 0) exit(EXIT_FAILURE); /* Check for failure of execinit */ for(;;) { operands = input = execget(); /* Obtain next input line. */ if (!input) break; cmdname = execid(&operands); /* Obtain command name. If error in execid, expect */ /* CLIST/EXEC input next. */ if (!cmdname) { interact = 1; continue; } strupr(cmdname); /* Upper case command name */ if (!*cmdname) /* Check for null input. */ continue; /* If execid did an EXEC for us, note and continue. */ else if (strcmp(cmdname, "*EXEC") == 0) { interact = 0; continue; } /* If we just switched from EXEC to the terminal, note this. */ else if (strcmp(cmdname, "*ENDEXEC") == 0) { interact = 1; thisrc = atoi(operands); /* Extract EXEC return code. Remember it might be missing.*/ if (operands) sprintf(msgbuff, "EXEC return code %d", thisrc); else strcpy(msgbuff, "EXEC return code unavailable"); /* Inform user of return code. */ result = execmsg("EXAM001I", msgbuff); if (result != 0 && errno == EINTR) break; /* Check for unexpected signal */ } /* Terminate if END received. */ else if (strcmp(cmdname, "END") == 0) break; else if (strcmp(cmdname, "EXEC") == 0) { /* Call EXEC for EXEC subcommand and expect input from it.*/ thisrc = execcall(input); interact = 0; if (thisrc != 0) { sprintf(msgbuff,"EXEC failed with return code %d",thisrc); result = execmsg("EXAM005E",msgbuff); if (result != 0 && errno == EINTR) break; /* just quit after OpenEdition signal */ } } /* If command is ECHO, repeat its operands. */ else if (strcmp(cmdname, "ECHO") == 0) { result = execmsg(0, operands); if (result != 0 && errno == EINTR) break; thisrc = 0; } /* If command is SETRC, set return code as requested. */ else if (strcmp(cmdname, "SETRC") == 0) { char *number_end; thisrc = strtol(operands, &number_end, 10); if (!number_end) { sprintf(msgbuff, "Invalid return code: %s",operands); result = execmsg("EXAM002E", msgbuff); if (result != 0 && errno == EINTR) break; thisrc = 12; } else { sprintf(msgbuff, "Return code set to %d", thisrc); execmsg("EXAM003I", msgbuff); if (result != 0 && errno == EINTR) break; } } /* If unknown command name, try to EXEC it. */ else { errno = 0; /* Make sure errno is clear */ thisrc = execcall(input); if (thisrc != 0 && errno == EINTR) break; interact = 0; } maxrc = execrc(thisrc); /* Inform EXEC of return code.*/ if (maxrc < 0 && errno == EINTR) break; } sprintf(msgbuff, "Maximum return code was %d", maxrc); execmsg("EXAM004I", msgbuff); /* Announce max return code. */ execend(); /* Cancel SUBCOM connection. */ return maxrc; /* Return max return code. */ } CONTROL NOCAPS WRITE SUBCOM EXAMPLE: starting. /* Issue the echo subcommand a few times. */ ECHO This is the first subcommand. ECHO Your userid is &SYSUID.. SETRC 0 /* Try the SETRC subcommand. */ WRITE SUBCOM EXAMPLE: return code is now &LASTCC SETRC 8 /* Set the return code to 8 */ WRITE SUBCOM EXAMPLE: return code is now &LASTCC SETRC 0 /* and back to 0 */ WRITE /* Experiment with 'execmsg' by changing current */ /* message handling. The PCF-II X facility is used to */ /* direct PROFILE requests to TSO. */ X PROFILE MSGID /* Request message ID display. */ WRITE PROFILE MSGID (complete message) SETRC 0 WRITE X PROFILE NOMSGID /* Request message ID suppression. */ WRITE PROFILE NOMSGID (just the text) SETRC 0 WRITE CONTROL NOMSG WRITE CONTROL NOMSG (no message) SETRC 0 WRITE CONTROL MSG WRITE SET SYSOUTTRAP = 5 (trap messages within CLIST) SET SYSOUTTRAP = 5 SETRC 0 SET I = 1 WRITE Output produced by SETRC subcommand: DO WHILE &I <= &SYSOUTLINE /* Write output of SETRC subcommand. */ SET MSG = &STR(&&SYSOUTLINE&I) WRITE &MSG SET I = &I + 1 END SET SYSOUTTRAP = 0 WRITE /* Tell the example program to invoke another CLIST, */ /* this one called SUBSUB. When it finishes, display */ /* its return code. SUBSUB returns the sum of its */ /* arguments as its return code. */ %SUBSUB 12 2 WRITE SUBCOM EXAMPLE: subsub returned &LASTCC. END /* Invoked by SUBCOM CLIST */ PROC 2 VAL1 VAL2 CONTROL NOCAPS WRITE SUBSUB EXAMPLE: Received arguments &VAL1 and &VAL2 EXIT CODE(&VAL1+&VAL2) address example /* REXX SUBCOM example */ /* Issue the echo subcommand a few times. */ "echo This is the first subcommand." "echo Your userid is " sysvar("SYSUID") "setrc 0" /* try the SETRC subcommand */ say "SUBCOMR EXAMPLE: return code is now " RC "setrc 8" /* Set the return code to 8 */ say "SUBCOMR EXAMPLE: return code is now " RC "setrc 0" /* and back to 0 */ say " " /* Put an echo subcommand on the stack for execution after the EXEC */ /* completes. */ queue 'echo This line is written after the EXEC is completed.' /* Experiment with "execmsg" by changing current message handling. */ address tso "profile msgid" say "PROFILE MSGID (complete message)" "setrc 0" say " " address tso "profile nomsgid" say "PROFILE NOMSGID (just the text)" "setrc 0" say " " save = msg("OFF") say "MSG(OFF) (no message)" "setrc 0" say " " save = msg(save) /* Tell the example program to invoke a CLIST named SUBSUB. When */ /* it finishes, display its return code. SUBSUB returns the sum */ /* of its arguments as its return code. */ "%subsub 12 2" say "SUBCOMR EXAMPLE: subsub returned " RC /* Now invoke a REXX EXEC named SUBSUBR, which performs the same */ /* function as the SUBSUB CLIST. Note that the negative return */ /* code produced by this call to subsubr will be flagged as an */ /* error by REXX. */ "%subsubr 5 -23" say "SUBCOMR EXAMPLE: subsubr returned " RCThe following is the SUBSUBR EXEC invoked by the previous example. /* REXX EXEC invoked by SUBCOMR EXEC */ parse arg val1 val2 . say "SUBSUBR EXAMPLE: Received arguments " VAL1 " and " VAL2 exit val1+val2 /* REXX */ say 'SUBCOM EXAMPLE: starting.' /* Issue the echo subcommand a few times. */ 'echo This is the first subcommand.' 'echo Your userid is' userid()'.' 'setrc 0' /* Try the setrc subcommand. */ say 'SUBCOM EXAMPLE: return code is now' rc /* REXX variable 'rc' */ 'setrc 8' /* Set the return code to 8. */ say 'SUBCOM EXAMPLE: return code is now' rc /* REXX variable 'rc' */ 'setrc 0' /* And back to 0. */ say '' /* Experiment with 'execmsg' by changing the current EMSG setting. */ /* The subcommand 'setrc 0' will cause a message (or part of a */ /* message or nothing) to be sent. Note that the REXX 'address' */ /* statement is used to change the subcommand environment to CMS. */ address COMMAND 'CP SET EMSG ON' /* Display both ID and text. */ say 'SET EMSG ON (complete message)' 'setrc 0' say '' address COMMAND 'CP SET EMSG CODE' /* Display just the ID. */ say 'SET EMSG CODE (just the id)' 'setrc 0' say '' address COMMAND 'CP SET EMSG TEXT' /* Display just the text. */ say 'SET EMSG TEXT (just the text)' 'setrc 0' say '' address COMMAND 'CP SET EMSG OFF' /* Don't display anything. */ say 'SET EMSG OFF (no message)' 'setrc 0' say '' address COMMAND 'CP SET EMSG ON' /* Back to normal. */ /* Finally, tell SUBCOM C to invoke another macro, this one called */ /* 'SUBSUB'. When it finishes, display the return code. SUBSUB */ /* returns the number of arguments it got as the return code. */ 'exec subsub arg1 arg2' say 'SUBCOM EXAMPLE: subsub was passed' rc 'arguments.' trace ?r 'end' exit 0 /* invoked by SUBCOM EXAMPLE */ arg args say 'SUBSUB EXAMPLE: Got' words(args) 'arguments.' return words(args) "*ENDEXEC"string indicating that an EXEC invoked externally has completed, and the program has been reentered during CMS end-of-command processing via the L$CEXEC nucleus extension (see the execinitdescription earlier in this chapter). Noninteractive execution of SUBCOM applications cannot be supported in bimodal CMS because, by the time the the library's end-of-command nucleus extension is entered, CMS has already purged program modules from memory. Under the OpenEdition shell, the SAS/C REXX interface runs as a separate process from the calling program to prevent interference between the program and EXEC processing. Since the REXX interface is in a separate process, it is possible that the interface could be terminated by a signal at any time. When this occurs, on the next call to a SUBCOM function, errno is set to EINTR. Because the REXX interface has been terminated, the program cannot thereafter use any SUBCOM functions other than execend. Once execend has been called, it is possible to call execinit to create a new SUBCOM environment. Copyright (c) 1998 SAS Institute Inc. Cary, NC, USA. All rights reserved.
http://support.sas.com/documentation/onlinedoc/sasc/doc/lr2/lrv2ch7.htm
CC-MAIN-2019-22
refinedweb
7,175
54.42
Hello, I use Vue CLI 3 plugin and platform.is in state.js file, but it response is undefined. export default { preferences: { platform: Platform.is, // this.$q.platform.is.desktop fullScreen: AppFullscreen.isActive // this.$q.fullscreen.isActive } } It will not fail when I use it in .vue file (this.$q.platform.is.desktop) export default { name: 'Home', data() { return { leftDrawerOpen: this.$q.platform.is.desktop } }, methods: { openURL } } I’m using: –Vue version 3.0.5 –Quasar-framework version 0.17.17 Similarly create a template with Quasar CLI everything is normal no errors. Please give me information to solve this problem. Thanks - s.molinari last edited by s.molinari I don’t think Quasar globals will be available anywhere else other than in components within a Vue project. I don’t even understand why this version of Quasar is offered. It is a patch for a problem that I don’t know of and only causes confusion, when it is used. At least I don’t understand what problem the Quasar plugin is solving. Quasar IS Vue, so there is no reason to patch it/ plug it into Vue. Scott Hi Scott, I would like to mention a problem, when using Vue CLI 3 to build project with quasar framework. Can not retrieve this $ q.platform.is in .js files. Is there a difference between Quasar CLI and Vue CLI. Thanks - s.molinari last edited by Yes. Quasar CLI is built for Quasar. The Vue CLI is built for Vue. If you want all the features of Quasar, it’s best to use the Quasar CLI. Scott - metalsadman last edited by $q only work inside .vue files, if you like to use it then you’ll need to do an import in your .js file. ie: //somefile.js import { Platform } from ‘quasar’ isMobile() { return Platform.is.mobile }
https://forum.quasar-framework.org/topic/2808/platform-is-response-is-undefined-with-vue-cli-3
CC-MAIN-2022-33
refinedweb
307
78.65
Consistently, one of the more popular stocks people enter into their stock options watchlist at Stock Options Channel is JPMorgan Chase & Co (Symbol: JPM). So this week we highlight one interesting put contract, and one interesting call contract, from the January 2018 expiration for JPM. The put contract our YieldBoost algorithm identified as particularly interesting, is at the $67.50 strike, which has a bid at the time of this writing of $2.93. Collecting that bid as the premium represents a 4.3% return against the $67.50 commitment, or a 4.4% annualized rate of return (at Stock Options Channel we call this the YieldBoost ). Selling a put does not give an investor access to JPM's upside potential the way owning shares would, because the put seller only ends up owning shares in the scenario where the contract is exercised. So unless JPMorgan Chase & Co sees its shares fall 19.3% and the contract is exercised (resulting in a cost basis of $64.57 per share before broker commissions, subtracting the $2.93 from $67.50), the only upside to the put seller is from collecting that premium for the 4.4% annualized rate of return. Interestingly, that annualized 4.4% figure actually exceeds the 2.3% annualized dividend paid by JPMorgan Chase & Co by 2.1%, based on the current share price of $83.68. And yet, if an investor was to buy the stock at the going market price in order to collect the dividend, there is greater downside because the stock would have to lose 19.3% to reach the $67.3% annualized dividend yield. Turning to the other side of the option chain, we highlight one call contract of particular interest for the January 2018 expiration, for shareholders of JPMorgan Chase & Co (Symbol: JPM) looking to boost their income beyond the stock's 2.3% annualized dividend yield. Selling the covered call at the $95 strike and collecting the premium based on the $2.89 bid, annualizes to an additional 3.5% rate of return against the current stock price (this is what we at Stock Options Channel refer to as the YieldBoost ), for a total of 5.8% annualized rate in the scenario where the stock is not called away. Any upside above $95 would be lost if the stock rises there and is called away, but JPM shares would have to advance 13.6% from current levels for that to happen, meaning that in the scenario where the stock is called, the shareholder has earned a 17% return from this trading level, in addition to any dividends collected before the stock was called. The chart below shows the trailing twelve month trading history for JPMorgan Chase & Co, highlighting in green where the $67.50 strike is located relative to that history, and highlighting the $95 JPMorgan Chase & Co (considering the last 251 trading day JPM historical stock prices using closing values, as well as today's price of $83.68) to be 23%. In mid-afternoon trading on Monday, the put volume among S&P 500 components was 1.12M contracts, with call volume at 1.12 JPM.
https://www.nasdaq.com/articles/interesting-january-2018-stock-options-jpm-2017-01-23
CC-MAIN-2020-50
refinedweb
527
65.52
Wiki psi / Documentation Documentation PSI is split up in several modules, currently they are: - arch: System and architecture details. - process: Processes and process table. - mount: Filesystems. And some functions exist in the psi namespace directly (uptime, loadavg, ...). The entire API should be documented extensively with docstrings, so that pydoc should be the primary documentation. If something is missing from the docstrings it is a bug! However some general concepts and topics are explained a bit more on this page. Design All objects are snapshots at instantiation time, that means that if you create a psi.process.Process object and look at the .cputime attribute you will see the used CPU time when you created the object, if you later look at that attribute again it will not have changed. In contrast to this methods on objects are executed at the time you invoke them, e.g. Process.children() will only return the current children. Since it is possible that what the objects represent have changed since you created it most objects have a .refresh() method which will update all the attributes. Note that some methods might alter the state of an object too, like Process.kill(), in those cases you will have to call .refresh() to see the updated state. Even tough PSI provides a uniform API accross different platforms sometimes certain platforms simply don't have the information available. When reasonable PSI will construct this, c.f. Process.command, but sometimes this is simply not possible. Other times an API will be specific to just a few platforms, e.g. psi.getzoneid(). In those cases the classes, functions, methods or attributes are simply not present on platforms where they are not applicable, so you can always check with hasattr(). Exceptions Class hierarch of exceptions: Exception (Python) +-- StandardError (Python) | +-- AttributeError (Python) | | +-- AttrNotAvailableError (PSI) | | +-- AttrInsufficientPrivsError (PSI) | | +-- AttrNotImplementedError (PSI) | ... +-- InsufficientPrivsError (PSI) +-- MissingResourceError (PSI) | +-- NoSuchProcessError (PSI) | ... ... The general rule is that when accessing an attribute (most of which are implemented using the descriptor protocol internally) you will always get a subclass of AttributeError if you get an exception. When you get a [Attr]NotImplementedError it means development of the feature for the platform is lagging. Any part of the API which is experimental or which might still change will issue a FurureWarning. This helps reduce the number of required major version number changes (and hence module-import-name changes). Detailed Topics - Process names, arguments and executables: many attributes are involved with these with lots of platform-dependent quirks. This explains how it all works and how to easily work with them. Updated
https://bitbucket.org/chrismiles/psi/wiki/Documentation
CC-MAIN-2019-18
refinedweb
429
56.96
Hi I've been taking a python course and now that were done the professor wants us to write a program to list all the prime numbers from 2 - 10000. Oh yea and it has to be in C. So I am very stuck and really need help. Heres the assignment: Write a C program to compute and display all of the prime numbers which are less than 10000 using the technique known as the "Sieve of Eratosthenes". It works as follows: Start with a list of all candidate numbers up some number N (in this case, integers from 2 to 9999). Set a variable "p" to the first prime number, 2. While p^2 (p squared) is less than N, repeat the following: (1) starting from p^2, calculate all of the multiples of p less than or equal to N and eliminate them from the list; and (2) set p to the next number still on the list. This is the next prime number. When you are done, the only numbers remaining on the list will be prime. Heres what I've done so far, Thanks in advanced for the help! #include <stdio.h> char numlist[10000]; int main(void){ int i,p,n; for (i=2; i<10000; i++) { numlist[i]=1; } p=2; n=10000 while (p*p<n) { for (p*p<=n; n<10000; p++) { numlist[p]=0; } }
https://www.daniweb.com/programming/software-development/threads/283716/prime-number-compiler-help
CC-MAIN-2019-04
refinedweb
233
85.83
Here is my code! - Code: Select all def juice(x): d=2.0 y=1.0 x = float(x) k = (-1.0)*x**2/d np = input("Nivel of precision: ") np = float(np) while d < (np): if d % 2 == 0: d = d*(d-1) y = k*y + y # I'm just feeling that my error is here!; I want to take the last sum to multiply it by the constant k... d = d + 1 return y Could you give me some advice about this code? Please, don't post your code here, if you do this the fun is over..., I'm just seaching the way of think to solve this code.
http://www.python-forum.org/viewtopic.php?f=10&t=3507
CC-MAIN-2016-26
refinedweb
112
93.34
Introduction: In this tutorial article you will learn How to create Asp.net MVC 4 web application having CRUD (Create, Read, Update, and Delete), View details and Search functionality using Razor view engine, Entity Framework(EF) and SQL SERVER Database. Basically we will create an application to save, edit, update, list and search Book records. In previous articles i explained What is Asp.Net MVC? Its work flow, goals and advantages and The difference between Asp.Net Webforms and Asp.Net MVC. and Dynamically bind asp.net mvc dropdownlist from sql serverdatabase using entity framework and Pass data from controller to view in asp.net mvc and What is the use of viewbag, viewdata and tempdata in asp.net mvc and Create,Read,Update,Delete operation using Asp.Net MVC and Entity Framework Below is the demo preview of the web application that we are going to build. Requirements: I am using Visual Studio 2010 for accomplishing this application. You need to install the following components before completing this application: Implementation: Let's create our first Asp.Net MVC web application. - Open Visual Studio -> File -> New -> Project - Select you preferred language either Visual C# or Visual Basic. For this tutorial we will use Visual C#. - Name the project "MvcBookApp". Specify the location where you want to save this project as shown in image below. Click on Ok button. - A "New ASP.NET MVC 4" project dialog box having various Project Templates will open. Select Internet template from available templates. Select Razor as view engine as shown in image below. Click on Ok button. It will add the required files and folder automatically as shown in image below. Can you believe you have created your first MVC project without doing anything? But yes working MVC project is created having default template. You can run the application using F5 or from the Debug menu of Visual Studio select Start Debugging. You will see the page as shown below: As we are using default template, you can see the links to the Home, About and Contact pages that are all functional. But our aim is to create a web application to manage Book records. So we need to create the Model class that will automatically create the table in the database having the columns as mentioned in the form of properties in the class. Creating Model So let's create the model - Right Click on the Models folder of the project -> Add -> Class as shown in image below - Name the class "BookDetail.cs" using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; using System.Data.Entity; namespace MvcBooksApp.Models { public class BookDetail { [Key] public int BookId { get; set; } public string BookName { get; set; } public string Author { get; set; } public string Publisher { get; set; } public decimal Price { get; set; } } public class BookDetailContext : DbContext { public DbSet<BookDetail> BookDetails { get; set; } } } Note: If you get the error "The type or namespace name 'DbContext' could not be found (are you missing a using directive or an assembly reference?) " then read the article "Error Solution:The type or namespace name 'DbContext' could not be found (are you missing a using directive or an assembly reference?)" - Now it's time to create the database. So launch SQL SERVER and create a database and name it "Books_DB" - In the web.config file of the root directory of our project, create the connection string in the <configuration> tag as: <add name="BookDetailContext" connectionString="Data Source=lalit;Initial Catalog=Book_DB;Integrated Security=True"/> </connectionStrings> Note: Replace the Data Source and Initial Catalog as per your application. - Build the project first before going further. Go to Build menu -> Build MvcBooksApp. Next step is to create the controller - Right click on the Controller folder -> Add -> Controller as shown below. - Name the controller "BookDetailsController" and Select the following options as shown in image below. · Controller name: BookDetailsController. · Template: MVC Controller with read/write actions and views, using Entity Framework. · Model class: BookDetail (MvcBooksApp.Models) · Data context class: BookDetailContext (MvcBooksApp.Models) · Views: Razor (CSHTML). Note: Model class and Data Context class will not appear until you build the project. On clicking Add Button, Visual studio will create the following files and folder under your project. - A BookDetailsController.cs file in the Controllers folder of the project. - A BookDetails folder in the Views folder of the project. - And also the Create.cshtml, Delete.cshtml, Details.cshtml, Edit.cshtml, and Index.cshtml in the Views\ BookDetails folder. Congrats you have created the MVC application having Create, Read, Update and Delete (CRUD) functionality that the Asp.Net MVC automatically created so the phenomenon of creating CRUD action methods and views automatically is called Scaffolding. Run the application using F5 and navigate to BookDetails controller by appending BookDetails to the URL in the browser:. You will see the page as shown in image below: Clicking on "Create New" Button will open the screen as shown in image below. Add the details and save some records e.g. as shown in image below: Clicking on "Details" button you can view the details of any particular record as shown in image below: You can also edit any particular record by clicking on the "Edit" button at the bottom of the record details or come back to the main page by clicking on "Back to List" button. From the main BookDetails page clicking on the Edit button enables you to edit the record as shown in image below Make the changes and update the record. Similarly clicking on the "Delete" button allows you to delete the record. Implementing Searching functionality - Now going further we will also implement the Searching functionality in this application so that we can search the book records by Publisher or Book Name. Add the following lines @using (Html.BeginForm("Index","BookDetails",FormMethod.Get)) { <p>Publisher: @Html.DropDownList("Publishers", "All") Book Name: @Html.TextBox("strSearch") <input type="submit" value="Search" /></p> } below the line @Html.ActionLink("Create New", "Create") So it should look like: @Html.ActionLink("Create New", "Create") @using (Html.BeginForm("Index","BookDetails",FormMethod.Get)) { <p>Publisher: @Html.DropDownList("Publishers", "All") Book Name: @Html.TextBox("strSearch") <input type="submit" value="Search" /></p> } - In the Controller folder -> BookDetailsController.cs , comment or remove the code { return View(db.BookDetails.ToList()); } and add the method as: public ViewResult Index(string Publishers, string strSearch) { //Select all Book records var books = from b in db.BookDetails select b; //Get list of Book publisher var publisherList = from c in books orderby c.Publisher select c.Publisher; //Set distinct list of publishers in ViewBag property ViewBag.Publishers = new SelectList(publisherList.Distinct()); //Search records by Book Name if (!string.IsNullOrEmpty(strSearch)) books = books.Where(m => m.BookName.Contains(strSearch)); //Search records by Publisher if (!string.IsNullOrEmpty(Publishers)) books = books.Where(m => m.Publisher == Publishers); return View(books); } - Now time to run the application. Go to Controller folder -> HomeController replace the below index method { ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application."; return View(); } With the method public ActionResult Index() { return RedirectToAction("Index", "BookDetails"); } Now run the application and you will see the results as shown in the image below: Now over to you: " I hope you have created your Asp.Net MVC application successfully." 36 commentsClick here for comments great sir, thanksReply hello Lalit..Reply thanks for uploading MVC article..I am waiting for some more of it.. Cheers bro Thanks Ajay..i hope you enjoyed the article and learned the basic of MVC from it..keep reading..:)Reply Hi Asif Khan..i will create and publish more useful articles on MVC very soon..so stay connected and keep reading..:)Reply Hello sir. I read your blog and like it. but in this tutorial i did not understand properly can you please upload some other article related to mvc without any Crude Operation from basic level. in this article you did not mention how will i create entity framework.Reply Hello Faisal..i will upload more articles on MVC soon..keep reading..:)Reply u created only index wat abt edit n delete ,,,,,,,,Reply hi ,u didnt create tat edit ,,,,and delete ,,,Reply do any ,,,binding data to dropdown from database ,,,selected item ,,,,,when i insert ,,,,,tried of this ,,,,am binding data,,,but value or item not selecting in droplist ,,,,plz solve this hiReply Hello Santhosh Patil..have you followed the article fully? Scaffolding automatically creates the index,edit,delete and details functionality. When you will follow the article, they will be automatically created..Reply Hollo sir, I want to learn MVC in details so please upload more articles in MVC. I read your articles it's very usefull so sir help me.Reply Hi Anil..i am working on MVC articles so that the reader like you can learn the MVC..I will soon publish some more articles..so keep readingReply Hello sir, I also work with MVC and i'm using ajax to post the data to controller. but image ulpoaded is not posting to controller . Please help me.Reply hello sir, this article is really helpful to me.Reply i would like to read MVC with Linq, MVC without Linq also. Hello Neeraj, i am glad you liked this article..keep reading and stay connected for more articles on MVC covering all aspects..:)Reply Hello Sir,Reply Can U Plz tell me how to Create CRUD operations in GridView using MVC 4 ASP.NET but without using Entity FrameWork. thank u sir.this article is very usefulfor me because i m learning mvc.thanks again sir please give and moreReply Thanks Hemu for your feedback..i am glad you found this article helpful..stay connected and keep reading for more useful updates like this..:)Reply Hi Lalit..Thank you for your articles...Try to update your Posts on MVC..we are waiting for those...at least give me one mvc article for a day.:)Reply Hi rahul..thanks for appreciating my work...it is always nice to hear that someone liked my work..I will try to publish more articles on MVC...:)Reply Thanks for uploading this tutorial can you please help us in GridviewReply Please Mr. Lalit Raghuvanshi ... Greatly appreciated the way you learnt, but this is not at all much ... lets dig more .. so now i would be your sincere reader of your blogs .. thanks again, having pleasures for such true and honest articles. :-)Reply thanks sandeep for your feedback..i am glad you liked my articles..stay connected and keep reading..:)Reply One thing to ask that is not searching the record from the model, but that is filtering the record, where on the you have all the list of records...Reply But I need the Search function Can you please tell how can I do that It is very good starting for initial level understanding of MVC.Reply Thanks for that :) thanks ketan..i am glad you found this article useful..stay connected and keep reading for more useful updates...:)Reply Great article..Reply Thanks..stay connected and keep reading:)Reply Thanks a lot Lalit.Reply It was very helpul for me. your welcome..Reply hi lalith ,Reply I am a beginners of MVC. After a lot of google search i found this website . it helps a lot for me and all the beginners of MVC . Thank you very much once again and waiting for new updates on MVC. Keep share the treasure of knowledge I am glad you found my articles on MVC useful..Stay connected for more useful updates like this..Reply reallly its very helpful for meReply Thanks for your feedback..:)Reply thank you so much this artical help me lots !..
https://www.webcodeexpert.com/2013/11/aspnet-mvc-application-to.html
CC-MAIN-2021-43
refinedweb
1,945
60.41
Download: AutoSave Me (12.8 KB) Download Description: AutoSave Me is a scripted solution that saves your Maya scene after a specified amount of time has elapsed. Built before Maya integrated their own auto save feature but still relevant. Time tested on a large development team over multiple years. - Elapsed time is checked after selection changes via scriptJob. - Incremental saves are stored in the same directory as your Maya scene. - Utilizes Maya’s built-in incremental save and limits which you can enable/disable within Maya or ASM Options. - Settings are saved between sessions via OptionVars. Installation: Copy autoSaveMe.py to your Maya scripts directory, usually – documents\maya\version\scripts\ Add the following lines of code into your userSetup.py file: (included in download) import autoSaveMe as asm asm.autoSaveMe() To access the Options window run: (auto opens on first run) asm.asmOptions()
http://eeltechart.com/downloads/autosave-me/
CC-MAIN-2018-51
refinedweb
143
51.85
#include <consensus/validation.h> #include <policy/policy.h> #include <primitives/transaction.h> #include <vector> Go to the source code of this file. A package is an ordered list of transactions. The transactions cannot conflict with (spend the same inputs as) one another. Definition at line 32 of file packages.h. A "reason" why a package was invalid. It may be that one or more of the included transactions is invalid or the package itself violates our rules. We don't distinguish between consensus and policy violations right now. Definition at line 24 of file packages.h. Context-free package policy checks: Definition at line 14 of file packages.cpp. Context-free check that a package is exactly one child and its parents; not all parents need to be present, but the package must not contain any transactions that are not the child's parents. It is expected to be sorted, which means the last transaction must be the child. Definition at line 64 of file packages.cpp. Default maximum number of transactions in a package. Definition at line 15 of file packages.h. Default maximum total virtual size of transactions in a package in KvB. Definition at line 17 of file packages.h.
https://bitcoindoxygen.art/Core-master/packages_8h.html
CC-MAIN-2022-05
refinedweb
203
60.92
/> The Euclidean Algorithm is a simple method for finding the highest common factor or HCF (also known as greatest common divisor or GCD) of two positive integers. This is an implementation of the algorithm in Python. Wikipedia has a comprehensive article on the topic here so let's get straight to the coding by creating a new folder, and within it creating an empty file called euclideanalgorithm.py. Open it and enter the following, or you can download the source code as a zip or clone/download the Github repo if you prefer. euclideanalgorithm.py Source Code Links def main(): """ The Euclidean Algorithm finds the highest common factor of two numbers. Here we create lists of number pairs and run the algorithm on it, printing out the result and the numbers divided by the HCF. """ print("----------------------") print("| codedrome.com |") print("| Euclid's Algorithm |") print("----------------------\n") avalues = (55, 27, 3, 14, 500, 30) bvalues = (5, 45, 15, 49, 12, 18) for i in range(0, 6): hcf = EuclideanHCF(avalues[i], bvalues[i]) print("HCF of {} and {} = {}".format(avalues[i], bvalues[i], hcf)) print("{} / {} = {:.0f}".format(avalues[i], hcf, avalues[i] / hcf)) print("{} / {} = {:.0f}\n".format(bvalues[i], hcf, bvalues[i] / hcf)) def EuclideanHCF(a, b): """ A simple implementation of a simple algorithm. """ while(b != 0): temp = b b = a % b a = temp return a main() The main function creates two lists containing pairs of numbers to apply the algorithm to. It then iterates the lists,. Run the program with this command in the terminal: Running the Program python3.7 euclideanalgorithm.py The program output is Program Output ---------------------- | codedrome.com | | Euclid
https://www.codedrome.com/euclidean-algorithm-python/
CC-MAIN-2021-31
refinedweb
269
55.24
In PyQt5, Qt alignment is used to set the alignment of the widgets. In order to use the Qt alignment methods we have to import Qt from the QtCore class. from PyQt5.QtCore import Qt There are many methods in Qt alignment : 1. Qt.AlignLeft 2. Qt.AlignRight 3. Qt.AlignBottom 4. Qt.AlignTop 5. Qt.AlignCenter 6. Qt.AlignHCentre 7. Qt.AlignVCentre Note : There are also some alignment methods like Qt.AlignJustify but they works in PyQt4 not in PyQt5. Code : The code will show all these methods and helps in better understanding the differences. Output : Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics. To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. Recommended Posts: - PyQt5 - alignment() method for Label - PyQt5 – Check if alignment of radio button is left to right - PyQt5 QSpinBox - Setting alignment - PyQt5 QSpinBox - Getting alignment - PyQt5 QDateEdit - Setting Date Alignment - PyQt5 QDateEdit - Getting Date Alignment - PyQt5 QListWidget – Setting Item Alignment - PyQt5 QListWidget – Getting Item Alignment - PyQt5 QListWidget – Getting all Scroll Bar at given alignment - String Alignment in Python f-string - Biopython - Sequence Alignment - Biopython - Pairwise Alignment -.
https://www.geeksforgeeks.org/qt-alignment-in-pyqt5/?ref=lbp
CC-MAIN-2020-50
refinedweb
195
52.7
How Wikipedia Works/Chapter 7 Contents - 1 Chapter 7: Cleanup, Projects, Policy, and Processes - 1.1 Cleanup - 1.2 Cleanup Tasks - 1.3 The "Fix Crappy Prose" Challenge - 1.4 Projects: Working to Improve Content - 1.5 Processes - 1.6 Summary Chapter 7: Cleanup, Projects, Policy, and Processes[edit] Please don't say you're at a loss for something to do on Wikipedia today. There is far too much that needs to be fixed for that! Wikipedia's broad concept of cleanup includes most tasks to improve articles once they have been created. Any time you need a break from writing new articles, you'll find plenty of work waiting for you on existing ones. Work on Wikipedia is self-directed. You can create your own tasks or look into the wide variety of projects and processes for improving and maintaining Wikipedia content in particular areas. You can almost always find someone else who is interested in working in the same areas as you are. In this chapter, we'll talk about some of the available cleanup tasks and the collaborative projects that have been set up for maintaining articles. We'll also introduce processes, the review structures that have been set up to allow interested editors to discuss articles and perform certain formal tasks. Processes are the practical implementation of policies and provide a structure for day-to-day work. We'll discuss two of the biggest processes: deleting articles and promoting good content. The activities described in this chapter are at the heart of the collaborative editing and article improvement that make Wikipedia work. Cleanup[edit] If you see a message with a yellow bar at the beginning of an article, along with the icon of a broom chasing out the dust, that's a tag indicating the article needs to be cleaned up. Although the majority of articles could be improved—after all, Wikipedia is never finished—some are clearly in more desperate need of help than others. These neglected articles require cleanup. Cleanup is simply the general term for improving articles. The vast majority of tasks on Wikipedia fall under this broad heading: Sourcing, formatting, rewriting, and linking are all cleanup tasks. Although anyone is free to work on any task at any time, Wikipedia has developed a variety of mechanisms to sort out articles in need of help, so editors can find them and address cleanup issues more easily. In this section, we'll describe the basic mechanism for identifying and flagging articles as needing help, and then we'll discuss the broad categories of issues and how to find articles with these issues. Spending at least some time on cleanup tasks is helpful for any Wikipedian. Working on articles that need to be cleaned up reveals the kinds of problems that Wikipedia faces, and dealing with similar issues and problems in a number of articles is an excellent way to learn Wikipedia style and develop proficiency at encyclopedic writing (and by extension, any type of writing). Cleanup is also one of the best ways to contribute; Wikipedia always has a tremendous backlog of cleanup needing to be done. Thoroughly improving a poorly written article can also be immensely satisfying: You can always compare the before and after versions of the article from the page history to see just how much you accomplished. Most people start volunteering by exploring and trying out small cleanup jobs. Try different kinds of editing tasks to see what suits you. The authors of this book have different tasks they like to do on Wikipedia: Phoebe likes merging and fact-checking, whereas Charles prefers creating redirects. Many people end up focusing on one or two tasks—copyediting or referencing, for instance. As described in "Projects: Working to Improve Content" on Section 3, “Projects: Working to Improve Content”, many of these tasks have dedicated WikiProjects where groups of interested editors work on them: WikiProject League of Copyeditors (shortcut WP:LoCE) caters to those interested in stylistic editing, whereas WikiProject Fact and Reference Check (shortcut WP:FACT) is for fact-checkers. 1.1. Flagging Articles When editors encounter articles that need to be cleaned up, they have two options: They can immediately fix the problems, or they can flag the article with a message describing the problem for another editor to clean up later. Once articles have been flagged, other editors can then systematically work their way through all the ones tagged as having a particular issue. These flags or tags are the cleanup messages you'll see at the top of many articles. They are produced by templates, small pieces of code that can be included on pages to produce standardized messages. As noted in Chapter 5, Basic Editing, to add a template to a page, you simply enclose the name of the template in double curly brackets and place it on the page where you want it to appear. For instance, you can find the generic cleanup template at Template:Cleanup. To flag an article as needing cleanup using this template, insert this code at the very top of the article: This will create the message shown in Figure 7.1, “The cleanup template message”. Figure 7.1. The cleanup template message The cleanup template message If an article has several issues, multiple cleanup templates may be stacked on top of each other. An editor may also replace a general cleanup message with a more specific message as the particular issue becomes clear: For instance, if the article needs to be rewritten for clarity, you would flag it with the {{confusing}} template instead of the more general {{cleanup}} template. Template messages now exist for most conceivable problems. The long list of cleanup messages is available here (shortcut WP:TC); we also list some of these templates in the sections that follow. If an editor fixes an article so the cleanup message is no longer needed, he or she can remove the template message by simply editing the page and removing the template tag. If the editor only partially addresses the problem, he or she may remove only the appropriate template message if more than one has been added to the article or add a note on the talk page detailing what's been done and what's left to do. Although an editor sometimes forgets to remove a template when cleaning up an article, be careful about removing templates if you aren't sure all the issues have been addressed because content-related templates also serve as warnings to readers. Most cleanup templates can also be dated, so you can see how long an article has been in need of cleanup. For the general cleanup tag, adding a date looks like this: {{cleanup|date=November 2007}} This tag adds the date to the template message and sorts the article into a cleanup-by-month category. Although the cleanup process is thus somewhat subjective—no hard and fast rules on when to add any particular template exist, and anyone can add or remove templates—using the template message system allows several different editors (who may otherwise never be in touch) to clean up an article using a loose process and helps readers know when an article has problems. 1.2. Cleanup Categories Adding a cleanup message to an article will automatically place the article in an associated cleanup category. This way editors can easily find all the articles tagged as needing a certain kind of cleanup; they can simply go to the category and get to work. For instance, articles tagged with {{cleanup}} are placed in the category "All pages needing cleanup". Articles tagged with a dated cleanup tag are automatically sorted into a cleanup-by-month category as well so those with older tags can be worked on first. This also makes the large cleanup category more manageable. If you edit out the template to remove it, the article will automatically be removed from the cleanup category. Of course, flagging articles is easier than actually cleaning them up. This is reflected in some of the large cleanup categories. These categories have backlogs—large numbers of articles awaiting attention. Wikipedia's rapid growth has perhaps made this inevitable. Because there is so much to do, adding a template for every issue isn't really helpful, as this may, in fact, mask an article's worst issues; if a quick edit can resolve the problem, instead of adding a template, go ahead and fix it (the sofixit principle described in Chapter 13, Policy and Your Input). Make sure, however, that you flag the biggest issues if you can't fix them right away. As of early 2008, roughly 31,000 articles are in the category "All pages needing cleanup". Working in this category can be overwhelming; on the other hand, 31,000 represents less than 2 percent of the total number of articles on Wikipedia at this time. Cleanup Tasks[edit] The most comprehensive place to look for a list of collaborative cleanup projects is Wikipedia:Maintenance (shortcut WP:MAINT). This page gives an overview of all sorts of cleanup tasks, from the simple to the complex. So many tasks are listed that you might not know where to start. What is WikiProject Red Link Recovery? Well, this project aims to turn redlinks to bluelinks by automating the process of finding close title matches and suggesting redirects. If you would rather edit by topic, joining a WikiProject may be the best route (see "WikiProjects" on Section 3.1, “WikiProjects”). Alternatively, you can simply scan a list of articles in any topic area to find one that looks interesting and is in need of help. Try Category "To do", which shows articles with to-do lists on their talk pages or "Wikipedia:Cleanup" for a selected list of articles that need to be cleaned up, along with brief explanations of what needs to be done. If you can clean up one of these articles completely, simply edit the page to remove it from the list. Cleanup may be basic Wikipedia work, but it still offers challenges and interesting insights. Sometimes articles will require complete restructuring. Some will need to be rewritten: Refer to "Handling Major Editing Tasks" on Section 1.3, “Handling Major Editing Tasks” for a general approach to handling major edits, and heed the advice in Chapter 6, Good Writing and Research about keeping the material that can be saved and working so cleanup doesn't leave big breaks and surprise diffs in the page history. 2.1. Rewriting Every article in Wikipedia should aspire to elegant and clear prose that explains a topic gracefully and logically. Unfortunately, this aspiration is far from always being realized. Poor writing creeps into Wikipedia in different ways: An article may start with a poorly written draft. The original author may not be a proficient writer or English may be his or her second language. An article may have gradually become unclear. Articles that have been copyedited in pieces over time, improving the wording but neglecting the logical flow, may still need to be thoroughly rewritten. Perhaps small pieces of information have been added over time, but the article now lacks structure. Finally, an article may be clearly written but have an inappropriate tone or style for an encyclopedia. An article may lack a neutral point of view, demonstrating an editorial bias toward an event, a product, or a person. An article may also read like a press release, a product announcement, or even an advertisement. Articles that need language help can be flagged in a variety of ways. Additionally, many of the articles flagged with the generic cleanup tag actually need to be rewritten. Numerous explicit cleanup tags address the question of poor writing. To see articles flagged with any of these templates, you can go to the template page (such as Template:Copyedit); generally, the categories articles are placed into will be noted here, or you can click What Links Here from the template page. For instance: {{copyedit}} Addresses any problem with grammar, style, cohesion, tone or spelling {{advert}}, {{fansite}}, {{gameguide}}, {{likeresume}}, {{newsrelease}}, {{obit}}, {{review}}, {{story}} Address problems with inappropriate tone and style The "Fix Crappy Prose" Challenge[edit] Everyone reading this who thinks they're a pretty good writer should click the Random Article link in the left-hand sidebar 20 times and rewrite any crappy prose in the articles you find, without sacrificing facts. Do this at least once a week. Detail and accuracy beat eloquence when the choice arises, but that does not justify bad prose. (Adapted from User:David Gerard) {{abbreviations}}, {{buzzword}}, {{cleanup-jargon}}, {{inappropriate person}}, {{quotefarm}}, {{toospecialized}} Address composition problems {{contradict}}, {{misleading}}, {{unbalanced}}, {{limitedgeographicscope}}, {{weasel}} Address problems with content and presentation Depending on the level of problems, many approaches to rewriting articles exist. Guidelines for good articles are given in the Manual of Style and a variety of essays on the subject (see Chapter 6, Good Writing and Research), but the most important goal is that information be clearly conveyed to the reader, in line with the content policies. For unclear wording, consider clearer ways to provide explanations without sacrificing facts or ideas. Readers will benefit when you're done. To find other editors interested in writing and copyediting, consider joining the League of Copyeditors WikiProject. Expanding Stubs[edit] Stub articles are beginning articles that need to be expanded with more information on the topic. Hundreds of thousands of articles have been marked as stubs in all topic areas—so many that stub-sorting by topic is itself a key maintenance task. If you don't want to write an entire article from scratch but enjoy the research and writing process, try expanding one of these articles. Don't forget, however, that new information should be well referenced. A list of all stub types (which, in turn, links to specific categories for each type) is maintained at Wikipedia:WikiProject Stub sorting. When working on these articles, review more mature articles in the same topic area. What information is missing? Does an article about an author, for instance, contain a bibliography of the author's work? Wikipedia has no hard-and-fast rules about how long a stub can get before it is no longer a stub. If an article seems reasonably complete or it seems like a long article, you can probably remove the stub message. If an article seems longer than a stub but still needs to be expanded, flag it with the {{expand}} template. Wikification[edit] Wikification is the changing of any text into wikitext, including marking it with wikisyntax, structuring the article into logical sections, and adding internal links. Wikification can easily turn into rewriting and fact-checking because, fundamentally, you are converting ordinary prose into Wikipedia hypertext. Wikification, in this broader sense, means "formatting according to Wikipedia style." Experienced Wikipedia editors probably wikify before serious rewriting for prose style because wikification brings articles closer to encyclopedic considerations and helps flag related material in other articles. When you wikify, be alert to other issues: If the article is a dead-end article with no wikilinks leading from it, check What Links Here to make sure the article isn't also an orphan article without incoming links. These two problems often occur in the same article. Part of wikifying may be adding appropriate links to the article from other pages. You may need to add sections to the text or rewrite the lead topic sentence to be more encyclopedic. If the whole logical flow of an article is wrong, give that the highest priority of all. Poorly formatted content should usually also be examined for compliance with notability standards and factual accuracy as well; poor formatting is often a sign that the content was added by someone unfamiliar with Wikipedia. Wrong tone can be a clue to copyright issues; see "Copyright Violations" on Section 2.4.2, “Copyright Violations”. Formatting Articles[edit] Sometimes articles in need of stylistic help turn out to not be suitable for the encyclopedia: They may duplicate other older articles, be about non-notable topics, or even be hoaxes. If you see an article with a questionable topic, don't be afraid to ask for a second opinion before spending a great deal of time formatting it. You may also need to add other tags to the article as you edit, such as Citation Needed for questionable statements. Flag articles that need to be wikified by using the {{wikify}} template (Figure 7.2, “Wikify template message”). The article will then be added to Category:Articles that need to be wikified. The Wikification effort is supported by Wikipedia:WikiProject Wikify (shortcut WP:WWF). A related cleanup tag is {{sections}}, which places articles in Category:Articles needing sections. Fact-Checking and Referencing[edit] Good sources boost the quality of articles. Sources give the reader a place to find more information when they have finished reading the Wikipedia article, as well helping to ensure stated facts are accurate. Verifiability and Reliable Sources (shortcuts WP:V and WP:RS) are key content policies, as discussed in Chapter 1, What's in Wikipedia?. However, verifiability, which means the ability to verify something in principle, differs from actually providing verifiable sources. Many Wikipedia articles fall a little short here. Older articles from the more free-wheeling days on Wikipedia may not cite sources at all, whereas other articles may cite sources for only a few of the ideas in the text or not contain footnotes in the text itself. Sourcing is an ongoing process: Compiling a good bibliography for any topic, even a small one, is a big task. For some topics, you may have trouble finding any reliable sources, and accurate referencing work in these instances is particularly valuable. When original authors do not source their facts, various fact-checking projects perform this work. Wikipedia has several templates that alert both editors and readers that citations are needed in an article: {{unreferenced}} This template places articles in Category:Articles lacking sources. Use when an article doesn't cite any sources at all. {{refimprove}} This template places articles in Category:Articles lacking reliable references. Use when some sources exist but more are needed. {{citeneeded}} The more usual {{citeneeded}} or {{fact}} both place an article in Category:All articles with unsourced statements. Unlike the first two templates, add these templates inline in the article text wherever the problem occurs. For instance, if an article contains a questionable or controversial statement that needs a reference, you can insert the {{fact}} template at the end of the sentence in question. Sourcing can be time-consuming, but you can add sources to articles gradually. If you can find an outside, reliable source for just one fact mentioned in an article, adding a footnote with this source is quite helpful. If you have a more general source for the article's subject but haven't used it as a source for specific facts in the article, consider starting a Further reading or External links section and listing the source as a place for readers to get more information. For instance, you may want to list definitive biographies for articles on noteworthy people in Further reading or add links to online primary source documents for historical articles in External links. Every article should be as well sourced as possible. If you are knowledgeable about a particular topic area and want to concentrate on finding sources for that area, joining a WikiProject (as described in "Projects: Working to Improve Content" on Section 3, “Projects: Working to Improve Content”) is the easiest way to find articles on that topic that need to be improved. Help, an Article About Me Is Incorrect![edit] Wikipedia does not want articles to include mistaken statements, particularly those damaging to people or commercial ventures. On the other hand, Wikipedia content is not determined by outside pressures; neutrality is a key principle, and Wikipedia is not a mechanism for promotion. Therefore, inaccurate information and unfair criticism without a factual basis should not appear in Wikipedia articles; but fair criticism, properly sourced and presented in a balanced way, is not going to be removed from Wikipedia just because the subject or anyone else wants it removed. If an article about you or your company is factually incorrect, you have several options, but you should first assess the best way to get corrections made. Discussion[edit] First, remember to take into account the guidelines and policies presented in Chapter 1, What's in Wikipedia?. All articles must be neutrally presented, factually accurate and verifiable, and about notable, encyclopedic topics. Issues regarding factual inaccuracies can be discussed on the talk page for any article. This is the best first step toward getting a problem resolved. Give a calm account of where the article is factually wrong, and back up your argument with outside references. This should prompt those editing the article to correct it. Editing[edit] You can also, of course, simply edit the article; but before doing so, please consult Wikipedia:Conflict of interest (shortcut WP:COI). This guideline distinguishes defamatory comments (which anyone, including you, may remove) from other inaccuracies. Two further relevant pages are Wikipedia:Biographies of Living persons (shortcut WP:BLP) and Wikipedia:Autobiography (shortcut WP:AUTO). Wikipedia has strict guidelines on what can be written about living people, and WP:BLP will help you argue for deletion if someone has posted a hostile piece about you. On the other hand, WP:AUTO (subordinate to the conflict of interest guideline) explains why autobiographical writing is strongly discouraged—under most circumstances, you should not edit an article about yourself. If discussing the issue on the talk page does not resolve it, even after you have drawn an administrator's attention to it, do not be tempted to force the issue, make threats, or abuse the editors who are working on the article. Those approaches are likely to be counterproductive. Your best recourse is to send an email, as explained at Wikipedia:OTRS (shortcut WP:OTRS), detailing the problem. This channel is the official complaint mechanism. If your complaint has any substance, an experienced volunteer will review the article and work to resolve problems. 2.4.2. Copyright Violations You can often spot copyright violations on Wikipedia simply by their tone. Material from another source usually doesn't read like an encyclopedia article. Most copyright violations are caused by people cutting and pasting material from other sites into an article, which you can detect by searching the Web for the passage. Be sure to search for selected phrases from middle or particular unlikely sounding sentences; editors tend to change introductory and concluding sentences. If you locate a probable source for some article text, the next question is how much text was copied. If only a sentence or two was copied and the source is simply unattributed, then rewriting and citing the source may solve the problem. If, however, an entire article or most of it has been copied from a single source (as is more common with cut-and-paste violations), then a copyright violation has occurred. Be aware, though, that Wikipedia does include, legitimately, much public domain text and that other sites mirror Wikipedia content—double-check that the other website is not copying Wikipedia, rather than the other way around! You have a few options for removing copyright violations: First, the text can be reverted to a good version. Check the page history to see if a clean version exists; if so, simply revert to this good version, adding an appropriate edit summary. If you're having trouble figuring out if a good version exists, you can always rewrite the text yourself. Be careful that you aren't simply paraphrasing. Strip out most of the detail and start over, citing each fact to a source as you reinsert it. Be sure to add a note to the talk page explaining why you cut article text. If you are unable to revert or rewrite, flag confirmed copyright violations using the {{copyvio}} tag, which will place the article in a category of possible copyright violations for experienced editors to check. If you aren't certain that a copyright violation has occurred, use {{copyvio|url=}}, which will trigger a more measured deletion process. After the equal sign, paste in the URL from which you think the material may have been copied. Detailed instructions can be found at Wikipedia:Copyright problems (shortcut WP:CP). If you are sure the article violates copyright and that the text or topic doesn't seem to have any redeeming value, you may want to use the speedy delete tag {{db-copyvio}}, which will ensure rapid administrator attention (see "Deletion Processes" on Section 4.2.1, “Deletion Processes”). See Wikipedia:Spotting possible copyright violations (shortcut WP:SPCP) for more information. If your copyright is being infringed in an article, see Wikipedia:Contact us/Article problem/Copyright; several experienced editors work on resolving copyright issues Vandalism Patrolling[edit] Vandalism patrolling, though formally neither a project nor a process, is some of the most important ongoing work on Wikipedia. Vandalism is, by definition, a change made to Wikipedia with the malicious intention of having a negative effect on the content. Disputes over content may lead to accusations of vandalism, but no editor should ever use the word lightly—always assume good faith unless you have very good reason not to. Any good-faith effort to improve the encyclopedia, even if misguided or ill-considered, is not vandalism. See Wikipedia:Vandalism (shortcut WP:VAN) for a general perspective on the topic and Wikipedia:Administrator intervention against vandalism (shortcut WP:AIV) for a place to file reports against the most problematic editors. Anyone can just revert obvious vandalism that they see, of course; check the history page and then edit or use the undo version if you're logged in to revert an article to a version before the vandalism occurred, as explained in Chapter 5, Basic Editing. (With either method, check the diff of the current version with the version you are reverting to make sure you're only undoing vandalism, and then add an edit summary: rvv vandalism is common.) Many editors use their watchlists for just this purpose, scanning the list of changes on a regular basis to check for suspect edits that might be vandalism. Others devote substantial time to watching Recent Changes and other logs. Most vandalism is obvious: cutting content for no reason or inserting obscenities, crude humor, or nonsense. If you find a vandalized page, you should spend a couple of minutes reviewing the page history; vandal edits tend to be clustered, and you may have to revert several edits to find the "latest good version" or a version of the page that hasn't been vandalized at all (see "Fixing Mistakes and Other Reasons to Revert" on Section 1.4, “Fixing Mistakes and Other Reasons to Revert”). If you can't tell whether an edit is vandalism, check the diff of the edit along with the editing history of the user who made the edit to make a final determination. If an edit seems potentially realistic but is unsourced and uncommented, you can always tag it appropriately (with the Citation Needed template, for instance), leave a comment on the talk page, or revert it but copy the text of the edit to the talk page for others to verify one way or the other. Most vandalism follows a pattern. The soft security concept, which will be discussed again in Chapter 12, Community and Communication, is worth mentioning here. Wikipedia is open to everyone, so bad edits will happen. As noted in Chapter 4, Understanding and Evaluating an Article, however, most of these edits are caught quickly. The offenders are often young, and most vandalism is juvenile. Some persistent or more subtle vandals can succeed for a while. But Wikipedia defends in depth, not just with one front line. Wikipedia works by self-healing. Many tools and systems have been developed to detect (and sometimes automatically correct) vandal edits; the Counter-Vandalism Unit, found at Wikipedia:Counter-Vandalism Unit (shortcut WP:CVU), is a collection of editors interested in this work (Figure 7.4, “Counter-Vandalism Unit logo” shows its logo). Cleanup Editing Tools[edit] Besides vandalism repair, many cleanup editing tasks (such as correcting spelling or fixing typos) are repetitive, and for these you can use editing tools. These tools help power editors get dull tasks done quickly (though editors are always responsible for the edits they make, regardless of whether they used an automated tool or not). One popular application is the AutoWiki Browser. Here is a description from its page at Wikipedia:AutoWikiBrowser (shortcut WP:AWB): The AutoWikiBrowser is. This tool and other automated tools are meant for experienced editors only; learn the ropes by editing by hand. You can find many other tools, including tools for editing quickly, at Wikipedia:Tools. - Further Reading General Cleanup Tasks - A list of many different maintenance tasks - A reference to the template messages used on Wikipedia, including all the cleanup templates - All pages that are tagged as needing "cleanup," arranged by month - A list of various cleanup tasks that have large backlogs of articles needing work - A category containing all cleanup categories Rewriting - A copyediting and rewriting project - The category of articles that need copyediting - The category of articles that need to be edited for style - Articles that may need to be rewritten completely Expansion and Stubs - The WikiProject that organizes stub classification - All stub articles, sorted by topic - Articles that need expansion (may not be stubs) Wikification - The WikiProject covering wiki formatting tasks - Articles that need to be formatted to conform to Wikipedia's style guidelines - Pages that contain no internal links to other pages (and thus need to be wikified) - The page for listing and reviewing possible copyright violations and a good place to ask for a second opinion on an article's copyright status Fact-Checking - The fact- and reference-check WikiProject - Articles with no sources, sorted by month - Articles with some unsourced statements, sorted by month - The biographies of living persons policy - An article by a Wikipedia administrator about the correct way to go about fixing your own or your client's inaccurate Wikipedia article Vandalism - About different kinds of vandalism - An introduction to cleaning up vandalism Cleanup Editing Tools - The AutoWikiBrowser tool - Other editing tools Projects: Working to Improve Content[edit] The fundamental problem of the Wikipedia method is that massive collaboration is *hard*. David Gerard, WikiEN-l mailing list, 9 October 2007 After being created by individuals, articles are often brought up to a much higher standard within the broader community of Wikipedia editors. Two types of systems, projects and processes, have developed to work on Wikipedia content from different directions. Projects are loose social groups on the site. In contrast, processes, discussed later in the chapter, focus on making editorial and other decisions following specific guidelines. In other words, projects use the more casual idea of workflow, but processes move articles or decisions from one stage to another, more like a factory. WikiProjects[edit] A WikiProject is a loose grouping of editors who have banded together. There isn't actually a WikiProject Frogs—but there is a WikiProject Amphibians and Reptiles. WikiProject Philately and WikiProject Skateboarding both exist as well. Some projects are quite specific, whereas others focus on a broad area, such as WikiProject Chemistry, which works on articles related to all areas of chemistry (Figure 7.5, “The WikiProject Chemistry page”). WikiProject Novels "aims to define a standard of consistency for articles about Novels." This aim is typical for a WikiProject: to prescribe certain aspects of structure or format for articles. Such a project takes an interest in developing helpful templates and guidelines for writing about a particular subject area. Projects may also work on rating articles in their area, developing portals and other navigational structures, and determining what articles are missing. A Note on Naming[edit] WikiProjects are pages that exist within the Wikipedia namespace. The convention for naming them is to use WikiProject (with the P capitalized) and then the name of the project. Thus the full internal page name to link to, for instance, WikiProject Chemistry, is Wikipedia:WikiProject Chemistry. Wikipedia has hundreds of different projects, each addressing a topic area or specific maintenance or cleanup task. The best reason to participate in projects is that they operate on a smaller scale, whereas Wikipedia is enormous. Within the big city of Wikipedia, projects operate more like a small village, where it's easier to to get to know and work with other editors who are interested in the same topics. There are two types of WikiProjects: Topical WikiProjects[edit] These projects focus on improving and managing articles in a single topic area. They usually serve as a place for documenting and discussing changes and provide a natural forum (on the talk page for the project's main page) for discussing a topic area. They may provide centralized "to-do" lists for coordinating articles among interested editors. Maintenance WikiProjects[edit] These projects focus on Wikipedia maintenance and general cleanup tasks by coordinating efforts to clean up needy articles, perhaps using several template types. These projects simply help aggregate the work with formal project pages that describe the tasks needing to be done and techniques for doing them. A list of both types of projects can be found at Wikipedia:WikiProject_Council/Directory. To join a WikiProject, simply add your username to the list of interested editors and take on one of the jobs that might be listed. Of course, you don't have to join a project before working on articles in that area! People generally take on tasks on their own initiative. Formal assignments and other kinds of top-down management are pretty much nonexistent. Projects vary in their level of formality and activity; some have editors who provide regular updates about a topic area and active groups who work on tasks or rate articles, whereas other projects simply provide an occasionally updated list of articles that need work. Any editor who thinks they have a good idea for a project can create a project page, and then other interested editors are free to join the project and get to work. If you see a need for a new WikiProject, you can start one easily. You'll find more information at Wikipedia:WikiProject (shortcut WP:PROJ) and Wikipedia:WikiProject Council/Guide (shortcut WP:PROJGUIDE). You don't need special permission before starting a new project, but you might want to ask around—the success of any new project depends on attracting others to help out. Wikiportals[edit] Portals, those inviting pages with a collection of related articles and projects described in Chapter 3, Finding Wikipedia's Content, are not generally under the direct control of WikiProjects. On the other hand, a natural relationship exists between a portal on a topic and a WikiProject on the same topic. WikiProject Poetry announces, "Help is needed in maintaining the Portal:Poetry, including adding quotes, poems, articles, and other material for future weeks." A portal is a natural entry point on the site for a browsing reader, so a WikiProject often aims to sustain and improve a matching portal or to set one up if needed. Portals also often provide a list of articles that need work in their particular subject area, so look here if you're searching for articles to work on. Portal:Contents/Portals provides a list of portals, organized by topic. Most portals use a standardized layout that relies heavily on templates and subpages. Setting up a new portal does not require any special permissions, but you'll find that understanding templates before you begin is helpful. Try working on other portals first to get a sense of how they function. See Wikipedia:Portal/Instructions for a detailed guide on how to create a new portal. Writing Collaborations[edit] A writing or article collaboration is simply a drive to improve a particular article. Some people prefer to work on their own, but others enjoy the more focused push that a writing collaboration offers. When several people work on a particular article, it can improve very quickly. Most of the WikiProjects use collaborations. Some are based on periods of time, such as an article of the week, where the group selects one article for dedicated improvement efforts that week. One long-standing project that is not topic-specific is the Article Collaboration and Improvement Drive, which picks articles to collaborate on that need work. Often the articles, selected by popular vote, are on core topics or important articles that have been neglected in favor of more specialized subjects. Broad topics can be surprisingly difficult to write about well! See Wikipedia:Article Collaboration and Improvement Drive (shortcut WP:ACID). Another good place to find collaborations is Wikipedia:Community Portal, also accessible from the Community Portal link in the left-hand sidebar. Here, people are free to post collaborations, projects, and cleanup tasks that they want other editors to help with. On the Community Portal page, you can find an entire section devoted to collaborations; many are article collaborations in need of good editors. A further list of writing collaborations can be found at Wikipedia:Collaborations (shortcut WP:CO). Further Reading[edit] - WikiProjects - A group of Wikipedians who coordinate WikiProjects - The chemistry WikiProject - All about portals and how to find them - About article collaborations - The weekly article collaboration and improvement drive Processes[edit] Editorial and management decisions have to be made all the time on Wikipedia, yet the site is far too large for a single decision-making center to be an effective solution. Decisions, small and large, are thus made in different forums, where discussions about specific topics are clearly structured. Processes are not formally directed, but they generally follow specific, agreed-on rules for making decisions. Processes are clearly structured, while projects rarely are, and are more like a conveyor belt for processing decisions. Several processes are based on official policy, such as the deletion policy. Anyone can participate in a process; interested editors simply go to the process page to add their views. Technically, a Wikipedia process is a page, or a suite of pages, normally found in the Wikipedia namespace where editors discuss proposed decisions. Processes are public, open, and transparent. They are also confidence-building mechanisms, as they help ensure that the rules are the same for all editors and topics, and everyone can see (and double-check) that others are playing fair and that the rules do not suddenly change. As the essay Wikipedia:Practical process says: We're here to write an encyclopedia. Process is the temporary scaffolding we put up to help us write an encyclopedia. Having no process or not working to established process leads to chaos. We use process: 1. To give some consistency in similar situations. This helps process feel fair, even though precedent is not binding on Wikipedia. 2. To reduce the redundant effort of making each and every decision from first principles. 3. To encourage institutional learning and lead to a higher overall quality of decision making. Most processes rely on community consensus as well as policy for making decisions. Consensus, as used on Wikipedia, is an unusual and specific term. Within the context of processes, consensus means general agreement among participants within a specified time period (almost all processes put time limits on discussion). Sometimes a specific type of voting is used, as in article deletion discussions where editors include their name and whether or not they think the article should be deleted; but even in these situations, everyone understands this is not really a vote—compelling arguments that follow policy are treated with more weight than a simple yes or no. Wikipedia's processes are, therefore, systems for getting certain things done. Process, community, and policy: These are key concepts for how Wikipedia works—the real Wikipedia, not a utopian clone. Although Wikipedia has very few committees, it has many processes, each open to anyone who is willing to do the work to understand the issues involved in that particular decision. Processes should generally be followed, unless very good reasons are given for not doing so; for example, administrators can delete pages out of process, but they risk inciting controversy if they do. On the other hand, processes have a tendency to get out of control, and rule-bound processes should not exist for their own sake. The process is important—red tape is not. The anti-bureaucratic nature of Wikipedia is set in context on the official policy page, Wikipedia:What Wikipedia is not. Searching on WP:BURO takes you directly to the section Wikipedia is not a bureaucracy. This section is worth quoting in full (from July 11, 2007): Wikipedia is not a moot court, and rules are not the purpose of the community. Instruction creep should be avoided.. In other words, process should not become legalistic. Processes can get out of control and having processes that insist on following their own rules no matter what should be avoided. We'll return to this idea in Chapter 13, Policy and Your Input (see "Ignore All Rules and Be Bold" on Section 1, “The Spirit of Wikipedia”). 4.1. What Processes Cover Wikipedia has numerous processes, dealing with both content and community. These processes include some that implement Wikipedia's official policies, such as the deletion processes, the Featured Article candidate process, the various dispute resolution processes, and the Request for Adminship process for administrator promotion. Other processes focus on making specific maintenance tasks routine, such as renaming categories or approving bots. One notable exception is resolving disputes over article content. You might believe that an encyclopedic wiki should start with a clear idea of this process. No such process exists and will not likely ever exist. This design decision is one of the keys to Wikipedia's model. Deletion processes deal with the question of whether a topic should be covered at all, and dispute resolution processes help editors who are arguing come to agreement. But Wikipedia has no formal form of adjudication for rival views of suitable article content. Editors are supposed to engage with others about their differing conceptions and deal with disagreements through discussion and common sense and with the assumption that everyone is on the encyclopedia's side. A content decision process would turn into an editorial board for the site, which is against the fundamental ideas of openness and community that are key to Wikipedia. Status on Wikipedia does not allow anyone to dictate content. In this section, we'll cover the two major content processes that do exist: deleting articles and featuring articles. In later chapters, we'll look at community processes, including dispute resolution. 4.2. Deleting Articles Wikipedia is growing at a tremendous rate, but a great deal of content is also deleted—hundreds or thousands of articles are deleted from Wikipedia every day. Clearly, not all articles that are created belong in the encyclopedia, but what should stay and what should go is not always obvious. The article deletion process is used to decide what should be deleted. Primarily used as a housekeeping measure, this process is mainly applied to poorly chosen topics—ones that don't, and can't, lead to proper encyclopedia articles. Deleting an article is the only way to remove content from the encyclopedia entirely, so readers cannot see the page or the page's history. Deleting is not the same thing as blanking a page by saving an empty revision; in deletion, the history of a deleted article, with access to all revisions, is also deleted. All traces of contributions to that article also disappear from the site—changes to a deleted article won't appear in user contributions, watchlists, Recent Changes, or Related Changes. The articles do not vanish entirely, however; deleted articles are still visible to administrators, which allows them to review deletions and restore content (undeleting) in case a mistake was made. Each deleted article is also logged in a special list, the deletion log, at Special:Logs. Only Wikipedia's administrators may delete articles, but the deletion process is open for anyone to discuss the fate of articles proposed for deletion. Wikipedia has very specific—and complicated—rules for how pages should be deleted and a large body of past discussion on the subject. Because Wikipedia leans toward including as much as possible, deletion is generally seen as a bad solution if the article can be salvaged. Articles are not deleted when the only issue is that they need to be cleaned up or are stubs. Articles are also not deleted based on anyone's personal dislike of the subject matter—Wikipedia has no censorship. How much emphasis to put on deleting content is a long-running philosophical debate on the site; see Chapter 12, Community and Communication for a broad discussion of the "inclusionism versus deletionism" debate. What does get deleted then? Usually, deletion is for Wikipedia's worst content. Some articles can't possibly be cleaned up. Submitted pages may be nonsense, graffiti, not in English, life stories, advertisements, blatant copyright violations, and spam articles containing nothing but the URL of a website. These examples are not particularly contentious, and many of these types of articles are deleted almost as soon as they are submitted, as part of routine vandalism control (this falls under the speedy deletion process described in the next section). Deleting articles that were submitted in good faith but that probably violate Wikipedia's content policies is more controversial. Sometimes the violation is clear; plain dictionary definitions or pieces of original research just don't fit within the scope of the encyclopedia. Many articles are deleted because they violate the principle of notability, and this violation is harder to determine. It can also lead to contention—no one likes being told that their company is "not notable." In these deletion discussions, editors discussing the deletion may need to do outside research to find out more about the topic and thoroughly assess the article and whether it belongs in the encyclopedia. Occasionally, editors decide that although the topic doesn't merit its own article, the content should be merged or otherwise incorporated into another article. Notability can be a problematic notion. If an article's topic violates the principle of notability, then the article will likely be deleted. But turning that around, the best working definition of notability comes from which topics are and are not deleted. Applying notability is not an exact science. As discussed in Chapter 1, What's in Wikipedia?, notability guidelines have been set up for various topics to help guide decisions, but these don't provide exact criteria. Saying that a TV actor is notable because he or she has 421 minutes on screen but not with 419 minutes on screen would be ridiculous, as would be declaring someone notable who has received 76 column inches of industry press but not with 74 inches. On the other hand, precedent is not binding on Wikipedia—and particularly not in deletion discussions. Many Wikipedians argue that one article's existence does not mean another article on the same topic should be automatically included. For instance, just because an article about one actor is on the site does not mean an article about another actor should also be included by default. Each article should be assessed on its own merits and measured against the basic content policies. Thus deletion discussions are about individual articles, not whole classes of articles. These complicated issues do help explain why deleting articles is a process—the process helps ensure a timely decision is made one way or another that settles the issue for the time being, if not forever. 4.2.1. Deletion Processes Anyone can nominate articles for deletion, review the articles that have been nominated, and offer opinions on whether they should be deleted. Nearly every deletion requires some interpretation of Wikipedia policy (which is certainly not always clear-cut). Deletion processes are, however, fairly stable, well regulated, and reasonably consistent. Of the three main ways to delete an article, Articles for Deletion (AfD) requires community discussion and a dedicated debate, whereas proposed deletions (PRODs; see WP:PROD) and speedy deletions (speedies, or sometimes CSD, which is short for Criteria for Speedy Deletion, the policy page) do not. Speedy deletions are the most common, due to the sheer volume of nonsense articles submitted. Articles that don't meet speedy deletion guidelines may get deleted though the Articles for Deletion process or the proposed deletion process instead, and contested speedy and proposed deletions are often referred to the AfD process. In other words, when the quicker deletion processes prove contentious, Wikipedia has the more serious AfD as a fallback. Each deletion process is initiated by an editor tagging the article with a red-bar deletion template. This template adds the page to several lists for review, and in the case of AfD, the editor creates a page explaining why the article should be deleted. Each specific deletion process covers a different type of problem article: Speedy deletion This process is for articles that definitely violate Wikipedia policies. Wikipedia maintains an extensive list of around 20 particular criteria for speedy deletion at Wikipedia:Criteria for speedy deletion (shortcut WP:CSD), along with the particular deletion templates that can be used. If none of these criteria are met, one of the other deletion processes should be used. Speedy does mean quickly, however. Speedy can also occasionally mean hasty, and it should never be applied to controversial or unclear cases. The usual process for speedy deletions is that a new-page or other vandalism patroller will discover a clearly bad article. He or she will tag the page with a speedy deletion template (Figure 7.6, “Speedy deletion message”) to add it to a list that administrators check routinely. If an administrator agrees that the page should be deleted, he or she will delete the page, citing the appropriate criteria. Speedy deletion can also be requested for non-article working pages that are no longer needed, such as user space subpages; this kind of housekeeping work is rarely contentious. Figure 7.6. Speedy deletion message Speedy deletion message Proposed deletion Proposed deletions (PRODs) are gentler than speedy deletions and give the community time to review the proposal. PRODs, like speedy deletion, are also designed for deletions that are not likely to be contested, but PRODs can be used for any type of article, not just those falling under the CSD criteria. When an editor discovers an article that he or she thinks should clearly be deleted, the editor can begin the proposed deletion process by tagging the article with the PROD template (Figure 7.7, “PROD deletion message”) and explaining why the article should be deleted. You can find the template at Template:Prod. The editor should insert the template on the page to be deleted along with this code, , replacing reason with the specific reason for deletion. This template remains on the article for five days, during which time the article's talk page is open for discussion. If, at any point during this time, any involved party—the original tagger, the author of the article, or another editor—thinks the article should not in fact be deleted, he or she can simply remove the template and the case is closed. This is called contesting the PROD, and at this point, if the nominator wants to pursue it, he or she must submit the article to AfD for discussion in order to delete it. If, at the end of the five days, no one contests the deletion, an administrator will review the article, the reason for deletion, and make a decision. The process is explained at Wikipedia:Proposed deletion. Figure 7.7. PROD deletion message PROD deletion message Articles for Deletion This thorough discussion process is for articles flagged for potential deletion; these articles are added to a list, and other editors review them on a dedicated page. Articles for Deletion (AfD) deals with the 5 to 10 percent of seriously contested cases, as well as any deletion case where the nominator wants input from other editors. If, during the course of about a week, consensus emerges, the discussion is closed, and the decision implemented. When no consensus emerges, general practice is to keep the article. Other outcomes are possible (for example, merges or redirections). A small proportion of cases become acrimonious. Nominating an article for this deletion process requires a few steps. First, an editor adds the AfD template to the article in question (Figure 7.8, “AfD deletion message”). Then, the editor creates a dedicated subpage from the main AfD page for discussing the article (this page is created by simply clicking a link in the deletion template). After the editor has created the subpage, he or she explains why the page should be deleted and signs his or her username. (Detailed instructions can be found at Wikipedia:Articles for deletion, shortcut WP:AFD.) Once the page has been nominated, other editors discuss the matter, adding comments that indicate whether or not they think the article should be deleted. Figure 7.8. AfD deletion message AfD deletion message Anyone can discuss AfD nominations by simply going to the main AfD page and adding a signed comment with his or her opinion about whether to keep or delete the article being discussed (Section 1.5.3, “On-Wiki Forums” shows a sample comment). Participating in a few debates to see what kinds of discussions crop up can be quite interesting. Some editors routinely review all the current AfD nominations, whereas others just visit the list once in a while to check if any articles they are interested in have shown up there. If you are knowledgeable about a particular subject, giving an opinion on whether a particular article or topic should be kept can be quite valuable to the process, and AfDs are now sorted by topic for those who don't want to search through all of them. Good practice for reviewing AfDs is to read the article in question thoroughly, do any other research necessary (such as looking for information online, checking backlinks, and doing basic fact-checking), and then give a reasoned opinion based on the article's content and Wikipedia's policies. AfD discussions can be lively, but certain ground rules exist: The discussion should always be about the content, not the editor who posted or nominated it, and appeals to personal taste ("I like it; I don't like it") are not helpful. If an article is no longer relevant, having been superseded by another article, or has a bad title, a deletion discussion is not needed. Instead, turn to Chapter 8, Make and Mend Wikipedia's Web to learn how to move, merge, or redirect an article. 4.2.2. Help, My Article's Being Deleted! Step one: Don't panic! You can often rescue an article under threat. Wikipedia has different procedures to follow if you want to contest a deletion; getting angry is not one of them. Sometimes articles will be nominated for deletion immediately after being posted; other times, the article may have been on the site for years before someone decides it doesn't belong. Either way, contesting a deletion varies depending on the deletion process being used, but all require discussing and bringing the article up to Wikipedia's standards. Deleting Other Kinds of Pages AfDs, PRODs, and speedies are only for deleting articles or pages in the main namespace. Images and media are dealt with separately; see Wikipedia:Images and media for deletion (shortcut WP:IFD). Categories and templates also have their own process; see Wikipedia:Categories for discussion (shortcut WP:CFD) and Wikipedia:Templates for deletion (shortcut WP:TFD), respectively. For deleting pages in the Wikipedia or User namespace, see Wikipedia:Miscellany for deletion (shortcut WP:MFD). A handful of debates occur here about unused or inappropriate material that has made its way into the project namespaces. A rare case is administrative blanking, not deleting, of project-space pages. For this, refer to Wikipedia:Deletion policy#Courtesy blanking (shortcut WP:CBLANK). This page provides a solution for old pages from deletion debates or other discussions that contain very pointed comments, for example, about specific people or companies. As a courtesy, administrators may replace the current page content to ensure that, over time, the old content becomes less prominent on search engines. Because the page itself hasn't been deleted, the content remains in the page history. If your article is proposed for speedy deletion, don't remove the template. Instead, insert a Template:Hangon template at the top of the article in question, and then go to its talk page immediately to explain why the article is notable and worth keeping. Citing sources will also help a great deal. You can always remove a proposed deletion tag, but then you ought to work on the article to address the issues raised by the nominator. If the article's notability has been questioned, add reliable sources that demonstrate notability. Notable sources depend on context; for instance, for a person, listing publications, awards, and honors helps to prove notability. Putting in enough effort to show the article meets notability and content standards should help prevent a subsequent nomination to AfD. In an AfD debate, feel free to participate in the discussion. Argue your case clearly, and don't take others' comments personally. During an AfD debate, anyone can clean up the article under discussion, so you can use this opportunity to improve the article according to the critics' points. You can then explain how you've improved the article on the AfD discussion page. Asking people to reconsider based on your own cleanup and extra referencing may have very good results. If you don't realize the article has been nominated for deletion until it's already been deleted, determine why and how it was deleted. Generally, a reason is given in the deletion log along with the deleting administrator's name. You can view this information by going to the article's title, which will now be a redlink page, displaying the Wikipedia does not have an article with this exact name message. Click the Deletion Log link that appears in the middle of the page to see the deletion log entry. Understand the common reasons for articles being deleted. Remember, you don't need to rush to get an article written and posted. Working on Wikipedia is not a race, and Wikipedia gives out no prizes for speed. Adopt a thoughtful approach, and learn the system rather than rage against it. The most common reason articles are deleted is because they are judged to be non-notable or vanity topics. Articles about local musicians, minor executives, or other people who aren't in the news regularly are likely to be rejected. Remember not to write about yourself either; autobiographies belong on user pages or personal websites. Here are some other common reasons for deleting articles: Spam-like postings[edit] Does the article read like an advertisement? Is it all about one project or company? Does it just talk about how great something is, failing to keep to a neutral tone? Content originally written for a company website or a press release is rarely suitable for Wikipedia. Too specialist[edit] If your article was judged as non-notable but is really part of something larger—for instance, if you're writing about a single college within a university—you may be able to include the information under the broader topic rather than write a new article about it. Enthusiast[edit] Specialism is a common problem with characters and elements from fiction, such as comic book and video game characters; TV episodes; individual songs; or batches of articles about minuscule parts of a fictional universe. Fancruft (sometimes shortened to just cruft) is a derogatory term for these types of articles, which are sometimes just barely tolerated. You will win friends by cleaning up the broader articles that already exist on the topic and adding detail to those first, rather than starting new articles. In some cases, the content might really belong on a more specialized wiki (see Chapter 16, Wikimedia Commons and Other Sister Projects). They hate the way you write[edit] Bad writing shouldn't be a valid reason for deletion rather than cleanup, but you can avoid deletion by submitting a well-written article in the first place. Many experienced editors make drafts in userspace, as was discussed in Chapter 6, Good Writing and Research, along with other writing advice. Finally, if you're sure your article was good and was deleted by mistake, you can start a deletion review. For a PROD deletion, getting an administrator to revive the article with no special discussion is usually easy. For a speedy deletion, you'll have to show you can address the reason it was deleted. For AfD deletions, a serious appeal process has been developed (see Wikipedia:Deletion review, shortcut WP:DRV), in which another round of community discussion will take place. This process reviews and checks the procedural side of deletions, and contributors can comment on whether they think deletion was the best option or not. As the Deletion Review page says, however, the first step is to talk to the deleting administrator to see why the page was deleted. If nothing comes from the deletion review, you'll probably have to wait six months before trying to re-create the article. If you do decide to try again, make sure you address all the criticisms brought up by reviewers and you are confident you can produce an article that meets content policies and guidelines, including Notability, Verifiability, and Neutral Point of View. Of course, the six-month rule isn't absolute: The notability of a topic can change overnight due to current events or new reliable sources being published. However, repeatedly re-creating an article that was deleted by community consensus without improving it substantially can be considered a form of vandalism. Occasionally, repeated re-creation can lead to an administrator salting a page, which means protecting the page and adding a special template that conveys the message that Wikipedia sincerely, truly, hand-on-heart does not want an article about this topic (the term comes from the phrase "salting the earth"). A Deletion Case Study[edit] Wikipedia is clearly not a business, but this has not stopped it appearing in a Harvard Business School case study. It was prepared by Andrew P. McAfee of the School, with Karim R. Lakhani.[22] Wikipedia's systems are put under the microscope, as they track a particular deletion debate from August 2006. This was one of the first occasions on which a Wikipedia internal process, AfD in this case, was dignified with such close academic attention. The paper used an analytical and historical approach (all the way back to Ephraim Chambers via Nupedia), amply supported by the case study of the particular deletion debate. The study is interesting for the clear picture drawn of the structures, community, admins, policies, and processes all interacting, focusing on the role of individual editors as a major factor. The study concerns the fate of the article Enterprise 2.0, a neologism coined by McAfee himself. The topic lies on one of the fringes of Wikipedia's natural content. The classic debate on including new terms has two opposing views: - Wikipedia's mission is factual and has nothing to do with spreading neologisms. - Many people would like to refer to a discussion of a new phrase making the rounds, in Wikipedia's slightly distanced and neutral style. These thoughts may be behind deletion debate positions, with "deletionists" (see "Wikiphilosophies" on Section 1.6, “Wikiphilosophies”) aiming to keep Wikipedia out of spreading jargon; but they have to be reconciled with the core content policies of No Original Research and Verifiability. For a neologism, you do have to go by usage in published texts, verifying that new jargon is actually used and used in the way the article claims so that the definition isn't "original research"; sometimes an article on a new phrase really should wait for good sources to appear elsewhere. Wikipedia's content and determinations of notability should never be based solely on a publicity effort. In the end, this rather slight article survived AfD. The deletion process, decisive as it may seem, is in fact provisional. Enterprise 2.0 actually has had a checkered history since it was kept, suffering redirection to another article, then re-creation. A redirect to Enterprise social software is its status at the time of this writing. Clearly, a neologism may flourish or it may not, and Wikipedia can and ought to update to reflect that. From this perspective, Wikipedia's social mechanisms are good, rather than weak, in their flexibility: The conclusions of AfD, or any other process on Wikipedia, are not set in stone. 4.3. Featured Articles Rather than being deleted, some very good articles are promoted in status. Good articles (GA) and featured articles (FA) are two levels of articles that the community has determined to be some of the best content on Wikipedia. Reviewing and working constructively on articles is one of the key skills of an involved Wikipedian. This skill also applies in formal or informal peer review (as noted in Chapter 6, Good Writing and Research) and on WikiProjects. Gauge content with an eye to improving it. (Working on good articles is also recommended as an antidote to the burnout caused by the other extreme—immersion in deletion debates.) Finding and browsing featured articles was described in Chapter 3, Finding Wikipedia's Content. Wikipedia also has featured review processes for media, images, lists, and portals. Relative to the rest of Wikipedia's content, few articles have been designated good or featured, with only about 1 in 660 articles listed as good and 1 in 1,200 listed as featured. However, many good-quality articles aren't on these lists—those that haven't gone through the formal processes. The criteria for good and featured articles are basically those mentioned in Chapter 6, Good Writing and Research, but in the processes, you can experience the criteria in action, as debated through open peer review. For either process, anyone can nominate an article and anyone can review it, though featured articles require a more complex review. If it is difficult for you to receive detailed criticism of your own work, remember the no ownership rule. Most articles under review improve greatly, regardless of the eventual outcome. Candidates for good articles are listed at Wikipedia:Good article candidates (shortcut WP:GAC). To nominate an article, simply follow the instructions on this page and place the corresponding Good Article Candidate template on the article's talk page. In turn, any editor can choose to review the article (typically, only one person will review the article). The criteria for review are listed at Wikipedia:Good article criteria (shortcut WP:GA?). The review process is supposed to be fairly informal. Reviewers read through the article and evaluate it based on the criteria, and then they have three options: They may pass the article as being a good article, fail the article if they feel it doesn't meet the criteria, or make suggestions for improvement by placing the article on hold. Often reviewers make detailed constructive comments. Articles that pass are added to the list of good articles at Wikipedia:Good articles (shortcut WP:GA). Articles that fail need to be improved. An article can be renominated once the criticisms have been addressed. Featured articles go through a more formal community peer review process, typically with several different editors participating as reviewers. This review is based on Wikipedia:Featured article criteria(shortcut WP:FACR). The criteria include, for example, appropriate use of images. Reviews take place at Wikipedia:Featured article candidates (shortcut WP:FAC). Here, you can find between 50 and 100 candidates that are under current scrutiny. Reviewer comments are likely to be detailed and extensive, ranging from minor issues, such as formatting, to major issues, such as unclear writing or missing references. Anyone can nominate an article to be featured, but by convention, the nominator is supposed to stick around for the review and help out with fixing up the article. The process is intended as a dialogue, with the nominator responding to the critique by working on the article's issues. Others are also welcome to help, but an article that doesn't improve at all in response to criticism isn't likely to pass. Directions for nominating a new article are on the Featured Article Candidates page (shortcut WP:FAC), along with directions for commenting on nominations. An article should not be nominated for good article status and featured article status at the same time, but a good article can later be nominated for featured article status. Articles that pass (sometimes only after several rounds of review) are then added to the list at Wikipedia:Featured articles (shortcut WP:FA). Any featured article may then be listed as Today's featured article on the main page of the site; the current month's selections are listed at Wikipedia:Today's featured article. Featured articles that degrade in quality may be reviewed through the featured article review process (Wikipedia:Featured article review), where anyone with concerns can nominate a currently featured article for discussion about whether that status should be removed. - Further Reading Process - (shortcut WP:PI) An essay about the role of process - (shortcut WP:PRO) Another essay about how process works - Addresses the genuine need for discussion, not just "yea" and "nay" responses Deletion Process - The deletion policy - An overview of the deletion process - Where current articles nominated for deletion are discussed Good and Featured Articles - The Featured Articles portal - The Good Articles portal - Nominations for featured articles [22] The case study is online at. Summary[edit] As part of the overall task of upgrading and updating Wikipedia, a vast range of jobs are accomplished by small teams or through local, open discussions. These collaborations and discussions are how the apparently anarchic Wikipedia works. Behind the scenes, a large and diverse population of supporting projects and processes are at work. What they all have in common is that editors operate within loose frameworks, communicating and pooling efforts to improve the encyclopedia.
http://en.wikibooks.org/wiki/How_Wikipedia_Works/Chapter_7
CC-MAIN-2014-52
refinedweb
11,791
50.46
Opened 8 years ago Closed 8 years ago #5699 closed (invalid) Generic views' page_range values incomparable to (current) page integer Description Consider this typical example -- <div class="pagenav"> Page {% for p in page_range %} <a href="{{ url }}{{ p }}/"{% ifequal page p %} class="sel"{% endifequal %}>{{ p }}</a> {% endfor %} {% if next_page %} <a href="{{ url }}{{ next_page }}/">Next</a> {% endif %} </div> Ooops, doesn't work! Ifequal doesn't seem to be able to compare the current page (integer) to variables in the page_range list. Aside, it seems type handling can be unnecessarily tedious at times, particularly when using things like Decimal. Change History (2) comment:1 Changed 8 years ago by Simon Litchfield - Needs documentation unset - Needs tests unset - Patch needs improvement unset comment:2 Changed 8 years ago by mtredinnick - Resolution set to invalid - Status changed from new to closed Seems to work fine here. Using this test case and the template fragment you posted data = { 'queryset': Session.objects.all(), 'template_name': 'foo.html', 'paginate_by': 2, } urlpatterns = patterns('', (r'^example/(?P<page>\d+)/$', object_list, data), ) with more than two items in my sessions table, I get the "page" item having the "sel" class added (and only that item). Please reopen if you have a short, complete example that demonstrates the problem. Let me try that again --
https://code.djangoproject.com/ticket/5699
CC-MAIN-2015-22
refinedweb
211
51.48
This appleve. The list and exact details of the "RPython" restrictions are a somewhat evolving topic. In particular, we have no formal language definition as we find it more practical to discuss and evolve the set of restrictions while working on the whole program analysis. If you have any questions about the restrictions below then please feel free to mail us at pypy-dev at codespeak net. but yield, for loops restricted to builtin types range range and xrange are identical. range does not necessarily create an array, only if the result is modified. It is allowed everywhere and completely implemented. The only visible difference to CPython is the inaccessability of the xrange fields start, stop and step. definitions run-time definition of classes or functions is not allowed. generators generators are not supported. exceptions We are using integer, float, string, boolean a lot of, but not all string methods are supported. When slicing a string it is necessary to prove that the slice start and stop indexes are non-negative.. String keys have been the only allowed key types for a while, but this was generalized. After some re-optimization, the implementation could safely decide that all string dict keys should be interned. list comprehensions may be used to create allocated, initialized arrays. After list over-allocation was introduced, there is no longer any restriction. functions objects in PyPy, wrapped objects are borrowed from the object space. Just like in CPython, code that needs e.g. a dictionary can use a wrapped dict and the object space operations on it. This layout makes the number of types to take care about quite limited. While implementing the integer type, we stumbled over the problem that integers are quite in flux in CPython right now. Starting on Python 2.2, integers mutate into longs on overflow. However, shifting to the left truncates up to 2.3 but extends to longs as well in 2.4.. ovfcheck_lshift() ovfcheck_lshift(x, y) is a workaround for ovfcheck(x<<y), because the latter doesn't quite work in Python prior to 2.4, where the expression x<<y will never return a long if the input arguments are ints. There is a specific function ovfcheck_lshift() to use instead of some convoluted expression like x*2**y so that code generators can still recognize it as a single simple operation. has the advantage that it is runnable on standard CPython. That means, we can run all of PyPy with all exception handling enabled, so we might catch cases where we failed to adhere to our implicit assertions. Pylint is a static code checker for Python. Recent versions (>=0.13.0) can be run with the --rpython-mode command line option. This option enables the RPython checker which will checks for some of the restrictions RPython adds on standard Python code (and uses a more agressive type inference than the one used by default by pylint). The full list of checks is available in the documentation of Pylin. RPylint can be a nice tool to get some information about how much work will be needed to convert a piece of Python code to RPython, or to get started with RPython. While this tool will not guarantee that the code it checks will be translate successfully, it offers a few nice advantages over running a translation: Note: if pylint is not prepackaged for your OS/distribution, or if only an older version is available, you will need to install from source. In that case, there are a couple of dependencies, logilab-common and astng that you will need to install too before you can use the tool.. We are thinking about replacing OperationError with a family of common exception classes (e.g. AppKeyError, AppIndexError...) so that we can more easily catch them. The generic AppError would stand for all other application-level classes. Modules visible from application programs are imported from interpreter or application level files. PyPy reuses almost all python modules of CPython's standard library, currently from version 2.5.2. We sometimes need to modify modules and - more often - regression tests because they rely on implementation details of CPython. If we don't just modify an original CPython module but need to rewrite it from scratch we put it into pypy/lib/ as a pure application level module. When we need access to interpreter-level objects we put the module into pypy/module. Such modules use a mixed module mechanism which makes it convenient to use both interpreter- and applicationlevel parts for the implementation. Note that there is no extra facility for pure-interpreter level modules, you just write a mixed module and leave the application-level part empty. You can interactively find out where a module comes from, when running py.py. here are examples for the possible locations: >>>> import sys >>>> sys.__file__ '/home/hpk/pypy-dist/pypy/module/sys/*.py' >>>> import operator >>>> operator.__file__ '/home/hpk/pypy-dist/pypy/lib/operator.py' >>>> import opcode >>>> opcode.__file__ '/home/hpk/pypy-dist/lib-python/modified-2.5.2/opcode.py' >>>> import os faking <type 'posix.stat_result'> faking <type 'posix.statvfs_result'> >>>> os.__file__ '/home/hpk/pypy-dist/lib-python/2.5.2/os.py' >>>>. pypy/lib/ contains pure Python reimplementation of modules. lib-python/modified-2.5.2/ The files and tests that we have modified from the CPython library. lib-python/2.5.2/ The unmodified CPython library. Never ever check anything in there.... You can go to the pypy/lib/test2 directory and invoke the testing tool ("py.test" or "python ../../test_all.py") to run tests against the pypy/lib hierarchy. Note, that tests in pypy/lib/test2 are allowed and encouraged to let their tests run at interpreter level although pypy/lib/ modules eventually live at PyPy's application level. This allows us to quickly test our python-coded reimplementations against CPython. Simply change to pypy/module or to a subdirectory and run the tests as usual. In order to let CPython's regression tests run against PyPy you can switch to the lib-python/ directory and run the testing tool in order to start compliance tests. (XXX check windows compatibility for producing test reports). write good log messages because several people are reading the diffs.. We have a development tracker, based on Richard Jones' roundup application. You can file bugs, feature requests or see what's going on for the next milestone, both from an E-Mail and from a web interface. If you already committed to the PyPy source code, chances are that you can simply use your codespeak login that you use for subversion or for shell access. If you are not a commiter then you can still register with the tracker easily. Our tests are based on the new py.test tool which lets you write unittests without boilerplate. All tests of modules in a directory usually reside in a subdirectory test. There are basically two types of unit tests:. You can write test functions and methods like this: def test_something(space): # use space ... class TestSomething: def test_some(self): # use 'self.space' here Note that the prefix test for test functions and Test for test classes is mandatory. In both cases you can import Python modules at module global level and use plain 'assert' statements thanks to the usage of the py.test tool.: You can run almost all of PyPy's tests by invoking: python test_all.py file_or_directory which is a synonym for the general py.test utility located in the pypy directory. For switches to modify test execution pass the -h option..
http://codespeak.net/pypy/dist/pypy/doc/coding-guide.html
crawl-002
refinedweb
1,265
57.16
How to Build Rails APIs Following the json:api Spec Stay connected We've talked before about how to build a JSON API with Rails 5. We also discussed using Rails 5 in --api mode, serializing our JSON responses, caching, and also rate limiting/throttling. These are all important topics, but even more important is producing a clear, standards-compliant API. We're going to look at how to build an API that conforms to the json:api spec. The json:api spec isn't just limited to how the server should format JSON responses. It also speaks to how the client should format requests, how to handle sorting, pagination, errors, and how new resources should be created. It even speaks to which media types and HTTP codes should be used. We're going to be implementing many of these things in our Rails app, and we'll also look at how we might test them. Lastly, we'll take a quick look at one possible authentication strategy and some tools we can use to produce beautiful documentation for our API. json:api Is Big The json:api spec is pretty big! It covers many of the possible features you may want to implement in a JSON API. May is the key word... you don't have to implement all of them for your API to be json:api compliant. For example: You don't have to have to implement sorting, but if you do, the json:api spec will tell you how it must be done. Media types One of the first things you'll notice with json:api is that it doesn't actually use the application/json media type. The reason for this is that the group behind json:api actually went through the proper process and channels to register their own media type, which is application/vnd.api+json. Part of the contract of the server is that it will respond with the Content-Type header set properly to this media type. The easiest way I was able to find to get this working without having to set it manually in every action is to create an initializer to set them. I called it register_json_mime_types.rb, and it contains: api_mime_types = %W( application/vnd.api+json text/x-json application/json ) Mime::Type.register 'application/vnd.api+json', :json, api_mime_types Now whenever a request is made it will automatically have Content-Type:application/vnd.api+json; charset=utf-8 set in the response headers. Creating a Resource One of the questions that came up from my last article was how we should go about creating a resource. What format should the data come in? What URL should the data be sent to? How should the server respond on success? On errors? Thankfully all of those answers are available, and my goal is to show how to create a resource while following the json:api spec. For these examples, we'll be working with two models: User RentalUnit Their fields don't matter too much, and they have the relationship of a RentalUnit belonging to a User and a User having many RentalUnits. Routing Routing is probably one of the easiest parts. The specification follows RESTful routing pretty much identically to what Rails gives you by default when you define the route with resources :rental_units. The specific route we are interested in for creating a resource is POST /rental_units HTTP/1.1. Format of data posted If you've done very much Rails development before, you're probably used to data being posted to the server in a fairly simple format, which may look somewhat like this: { rental_unit: { price_cents: 100000, rooms: 2, bathrooms: 1 } } We'll have to change this a little bit to conform to the specification. In the guide we see that it must be formatted like this: data: { type: 'rental_units', attributes: { price_cents: 100000, rooms: 2, bathrooms: 1 } } This matches how json:api is formatted on response, so it is at least familiar/consistent! To ensure that our API responds correctly, let's write a test. The test will post the data to the correct URL, and will then verify that the server responded with a 201 HTTP status code (which means resource created). After that, we'll look for a Location header, which tells us where we can find this new resource that was created. Lastly, we'll look to verify that it responded in the correct json:api response format using a custom matcher which I'll include below. require 'rails_helper' RSpec.describe "Rental Units", :type => :request do let(:user) { create(:user) } describe "POST create" do it "creates a rental unit" do post "/rental_units", { params: { data: { type: 'rental_units', attributes: { price_cents: 100000, rooms: 2, bathrooms: 1 } } }, headers: { 'X-Api-Key' => user.api_key } } expect(response.status).to eq(201) expect(response.headers['Location']).to match(/\/rental_units\/\d$/) expect(response.body).to be_jsonapi_response_for('rental_units') end end end Here is the custom rspec matcher I used. It does a simple check to make sure that the response conforms to the json:api spec when responding with a resource. RSpec::Matchers.define :be_jsonapi_response_for do |model| match do |actual| parsed_actual = JSON.parse(actual) parsed_actual.dig('data', 'type') == model && parsed_actual.dig('data', 'attributes').is_a?(Hash) && parsed_actual.dig('data', 'relationships').is_a?(Hash) end end So if this is what our test looks like, what might the controller look like? It ends up looking fairly similar to how it might have before. The only difference here is that I have to dig a little deeper to get to the attributes coming in through the params object. class RentalUnitsController < ApplicationController def create attributes = rental_unit_attributes.merge({user_id: auth_user.id}) @rental_unit = RentalUnit.new(attributes) if @rental_unit.save render json: @rental_unit, status: :created, location: @rental_unit else respond_with_errors(@rental_unit) end end private def rental_unit_params params.require(:data).permit(:type, { attributes: [:address, :rooms, :bathrooms, :price_cents] }) end def rental_unit_attributes rental_unit_params[:attributes] || {} end end When Errors Occur You might have noticed above that I have a special method called respond_with_errors for when the @rental_unit object is unable to save. But before we get to that, let's take a look at how json:api expects us to format the errors: { errors: [ status: 422, source: {pointer: "/data/attributes/rooms"}, detail: "Must be present." ] } To help with this, I've created a small method that lives in the ApplicationController to help respond with errors: def respond_with_errors(object) render json: {errors: ErrorSerializer.serialize(object)}, status: :unprocessable_entity end The ErrorSerializer class it is referring to is just a simple module which helps format the errors in the correct way. module ErrorSerializer def self.serialize(object) object.errors.messages.map do |field, errors| errors.map do |error_message| { status: 422, source: {pointer: "/data/attributes/#{field}"}, detail: error_message } end end.flatten end end I've written a small test to make sure that the API responds correctly. It again uses a custom rspec matcher which I'll include below. What I am looking for here is that it responds with the 422 HTTP code (unprocessable entity) and that it contains an error for a specific field. it "responds with errors" do post "/rental_units", { params: { data: { type: 'rental_units', attributes: {} } }, headers: { 'X-Api-Key' => user.api_key } } expect(response.status).to eq(422) expect(response.body).to have_jsonapi_errors_for('/data/attributes/rooms') end Here is the custom matcher which looks to see if there is an error for a specific field, in this case the rooms field: RSpec::Matchers.define :have_jsonapi_errors_for do |pointer| match do |actual| parsed_actual = JSON.parse(actual) errors = parsed_actual['errors'] return false if errors.empty? errors.any? do |error| error.dig('source', 'pointer') == pointer end end end Sorting Results and Pagination The next thing we are going to look at is how to sort results within our API. I've grouped this together with pagination because the way I coded it they go hand in hand within the same class. You may be thinking at this point why I mentioned class. Doesn't this normally happen within the index action of the RentalUnitsController? Normally yes, but while doing this, I found that it was a bit more code than I was comfortable with to leave it all inside the controller. It's also a good example of how you might extract some complicated logic out of the controller into its own class or module. The action itself is dead simple: def index rental_units_index = RentalUnitsIndex.new(self) render json: rental_units_index.rental_units, links: rental_units_index.links end The RentalUnitsIndex class has one job, to handle preparing the queries and data necessary to respond to the the GET /rental_units HTTP/1.1 request. It receives self (the controller) so that it can access things such as the params object as well as the URL helpers. class RentalUnitsIndex DEFAULT_SORTING = {created_at: :desc} SORTABLE_FIELDS = [:rooms, :price_cents, :created_at] PER_PAGE = 10 delegate :params, to: :controller delegate :rental_units_url, to: :controller attr_reader :controller def initialize(controller) @controller = controller end def rental_units @rental_units ||= RentalUnit.includes(:user). order(sort_params). paginate(page: current_page, per_page: PER_PAGE) end def links { self: rental_units_url(rebuild_params), first: rental_units_url(rebuild_params.merge(first_page)), prev: rental_units_url(rebuild_params.merge(prev_page)), next: rental_units_url(rebuild_params.merge(next_page)), last: rental_units_url(rebuild_params.merge(last_page)) } end private def current_page (params.to_unsafe_h.dig('page', 'number') || 1).to_i end def first_page {page: {number: 1}} end def next_page {page: {number: [total_pages, current_page + 1].min}} end def prev_page {page: {number: [1, current_page - 1].max}} end def last_page {page: {number: total_pages}} end def total_pages @total_pages ||= rental_units.total_pages end def sort_params SortParams.sorted_fields(params[:sort], SORTABLE_FIELDS, DEFAULT_SORTING) end def rebuild_params @rebuild_params ||= begin rejected = ['action', 'controller'] params.to_unsafe_h.reject { |key, value| rejected.include?(key.to_s) } end end end The nice thing about the way this is written is that it would be quite easy to test what might end up being complicated logic to perform sorting, pagination, and maybe at some point in the future, filtering of the rental units. If this were an API I was developing for real, I would most likely extract a lot of these generic methods into a parent class. Sorting with json:api Sorting in json:api is done through a single query param called sort which comes through the URL. It might look like this ?sort=-rooms,price_cents, which would sort descending by the rooms field, and then ascending by the price_cents field. This functionality is handled by the sort_params method, which farms out the work to a module called SortParams. This module has the job of taking a string such as -rooms,price_cents and converting it into the usual Hash that the order method wants to receive. From -rooms,price_cents to {rooms: :desc, price_cents: :asc}. module SortParams def self.sorted_fields(sort, allowed, default) allowed = allowed.map(&:to_s) fields = sort.to_s.split(',') ordered_fields = convert_to_ordered_hash(fields) filtered_fields = ordered_fields.select { |key, value| allowed.include?(key) } filtered_fields.present? ? filtered_fields : default end def self.convert_to_ordered_hash(fields) fields.each_with_object({}) do |field, hash| if field.start_with?('-') field = field[1..-1] hash[field] = :desc else hash[field] = :asc end end end end We've been trying to test functionality as we build it, so here are the tests to ensure that it is sorting correctly when the sort param is included. We've created some rental units and are requesting that they return in descending order based on the amount of rooms they have. describe "GET index" do it "returns sorted results" do create(:rental_unit, rooms: 4) create(:rental_unit, rooms: 5) create(:rental_unit, rooms: 3) get "/rental_units", { params: { sort: '-rooms' }, headers: { 'X-Api-Key' => user.api_key } } expect(response.status).to eq(200) parsed_body = JSON.parse(response.body) rental_unit_ids = parsed_body['data'].map{ |unit| unit['attributes']['rooms'].to_i } expect(rental_unit_ids).to eq([5,4,3]) end end Pagination with json:api With pagination, most of the details are left up to the programmer to decide. That is because pagination could be done quite differently from app to app, either page by page or by where your cursor is on the screen (say in an infinite scroll view). What is dictated by the spec is that you should pass this information through query params in the page key. It may end up looking like this: ?page[number]=1. You are also required to include a links key in the response which provides links to the current page (self), the first, previous, next, and last links. Most of these details are handled by the RentalUnitsIndex class in combination with the will_paginate gem. These are included in the rendered response from within the controller which calls out to our helper class: render json: rental_units_index.rental_units, links: rental_units_index.links Here we will test to ensure that it is returning paginated results along with the links correctly. it "returns paginated results" do (RentalUnitsIndex::PER_PAGE + 1).times { create(:rental_unit) } get "/rental_units", { params: { sort: '-rooms', page: {number: 2} }, headers: { 'X-Api-Key' => user.api_key } } expect(response.status).to eq(200) parsed_body = JSON.parse(response.body) expect(parsed_body['data'].size).to eq(1) expect(URI.unescape(parsed_body['links']['first'])).to eq('[number]=1&sort=-rooms') expect(URI.unescape(parsed_body['links']['prev'])).to eq('[number]=1&sort=-rooms') expect(URI.unescape(parsed_body['links']['next'])).to eq('[number]=2&sort=-rooms') expect(URI.unescape(parsed_body['links']['last'])).to eq('[number]=2&sort=-rooms') end One interesting but slightly unrelated thing I discovered while working on this article was that params has changed in Rails 5. It is now a different object instead of the old HashWithIndifferentAccess object. Thanks to Eileen Uchitelle for a great article pointing out what has changed. Authentication The type of authentication you need depends on the type of application you are building. If it is a public API, you might not need it at all, but more and more I have seen a simple API key given out, allowing the server to track your usage and giving them more control over its access. Alternatively, it may be an API which powers a single page application or a mobile app. Here you will still go with a token solution, perhaps like the one that devise_token_auth gives you, but it is a little bit more complicated to implement because there is more security involved (the token may change on every single request). The main thing to take away is that there are no cookies involved... there is no magical state that the browser handles for us. In fact, because we've built this app using the --api version of Rails 5, the cookies functionality doesn't even exist. We're going to go with the first solution I mentioned, a simple API key that is attached to the user's account. When they request a page, they'll include that in the request headers under the X-Api-Key value. Here is what our User model looks like. It will assign each new user a key (which could later be regenerated and/or modified if we need to shut this account out because of abuse). class User < ActiveRecord::Base has_many :rental_units before_create :set_initial_api_key private def set_initial_api_key self.api_key ||= generate_api_key end def generate_api_key SecureRandom.uuid end end Inside of the ApplicationController, we'll include a few small methods which will help us validate that the token is in fact correct, who it belongs to, and to respond with a 401 unauthorized response if it is invalid. class ApplicationController < ActionController::API before_action :authenticate private def authenticate authenticate_api_key || render_unauthorized end def authenticate_api_key api_key = request.headers['X-Api-Key'] @auth_user = User.find_by(api_key: api_key) end def auth_user @auth_user end def render_unauthorized render json: 'Bad credentials', status: 401 end end Here we have a test that ensures it is working correctly: it "responds with unauthorized" do post "/rental_units", { params: {}, headers: { 'X-Api-Key' => '12345' } } expect(response.status).to eq(401) end As far as I can tell, json:api doesn't speak much or at all about authentication, and it is left up to the implementor to decide what works best for their specific API and its use case. Documenting Your API Part of what makes APIs great -- such as the ones from Stripe, Twilio, or GitHub -- is how good their documentation is. I won't go into too much detail here other than to recommend two of the best approaches I've seen. The first approach, a gem called apipie-rails, is done by adding extra details to your tests, which automatically generates documentation. This has the benefit of being easy to keep in sync with your code as it is right there alongside it, but I find that it can tend to clutter up the tests a little bit. The second approach is one called slate which allows you to create some really beautiful API documentation, much like the ones I listed above. This is done in markdown, and it ends up generating static HTML/CSS files that you can host. Conclusion In this article, we expanded upon a previous article about creating JSON APIs within Rails. We tackled some common problems that occur when creating APIs, such as wanting pagination, sorting, errors, and authentication. We looked at how we can develop these features in keeping with the json:api spec. By doing so, we avoid needing to have conversations about how to implement each feature, and we can instead focus on the specifics of our application. Stay up to date We'll never share your email address and you can opt out at any time, we promise.
https://www.cloudbees.com/blog/the-json-api-spec
CC-MAIN-2022-40
refinedweb
2,881
55.54
In the first part of this blog post we covered some common scenarios for setup and configuration of your tests to ensure the overall test suite maintainable over the long run. Now, we’ll talk about backing APIs, extended tests, and test oracles. As powerful as Test Studio is, every project will end up needing some form of coded infrastructure at some point. Backing APIs make it much easier to handle the setup and configuration tasks mentioned above. You could work with Test Studio Standalone and use an empty coded step in an empty test as a holding place for custom utility classes and namespaces; however, that approach is only suitable for prototypes and tiny projects. Working with Test Studio inside Visual Studio makes it much easier to split out backing APIs/infrastructure to separate projects where they’re much more easily managed. This ensures teams are able to keep areas of responsibility properly separated out from the tests themselves. You’ll also find yourself wanting to drop to code to extend your tests for various reasons. Testing particular conditions on controls such as Trees or Grids is a fine example of this situation. Let’s use this grid as an example for two situations: verifying the count in the grid, and verifying the count of rows meeting specific criteria. First, we’ll count up the total rows in the grid’s body. There are several ways to do this here’s one example. IList rows = Find.AllByXPath ("//tbody/tr"); Assert.AreEqual(9, rows.Count); Another test might be to validate a table generated by a report or other query. Using the table above, we could say we’re validating two rows with users from the New Earth region will be displayed when we run the query against the baseline dataset. The following example shows a different way of interacting with the Grid on the page. In this case, we’ve stored the grid in the Element Repository and are able to extract it as a strongly typed object. We’re then looking for elements containing the text we’re looking for. This will effectively pull us off two table cell elements—this entire test scenario is predicated on us making these decisions based on our knowledge of the baseline dataset, and the absolute trust that we don’t have to worry about pulling off some other element(s) in the table. RadGrid grid = Pages.HomePage.Content_Grid; IList<Element> newEarthContacts = grid.Find.AllByContent( "New Earth" ); Assert.AreEqual(2, newEarthContacts.Count); In this example we’re using Xpath to grab all table row elements under the table body element. (“//tbody/tr”) That’s stored in the rows collection, and we then simply use the Assert class to validate we’ve got the correct count. Test oracles are another critical area where you’ll find yourself needing to write code. Oracles (sometimes also referred to as “heuristics”) are the final check in your tests. These are the true validations of whether your system’s actually functioning as you expect it to—and it’s generally not just a simple validation on the UI. An oft-used example is that of creating a new item in your system’s UI. Your test may log you on, navigate through a few steps and submit something, then finally give you a visual confirmation your item has been created. If your test finishes off with a validation of the UI, then the test is only partially complete because you can’t be sure the item was truly created in your database or underlying persistence system. An oracle should be used to connect to that persistence layer and validate the data item to ensure there’s not been some issue with unhandled exceptions, caching, or other problem which might have the UI updating while not saving things to the database. Below is a practical example of this concept. Here we’re doing a two-step validation: first in steps 11-16 we’re confirming the UI accurately reflects the edits we’ve made. In step 17 we have a coded step which confirms the user was created in the database—the code for that is shown in the window below and also reflects our use of a backing API to handle easy communication to the database via the ContactFactory helper class. With Test Studio you're able to do a great many things without writing code. That said, these last two posts have shown you where it's easy to drop to code for specific tasks that can really help your automation suites shine! Don't get carried away writing too much code when you don't have to, but don't be afraid to dive into VB.NET or C# and add some great value to your tests.
https://www.telerik.com/blogs/working-with-visual-studio-write-code-where-needed---part-2
CC-MAIN-2017-47
refinedweb
802
60.45
Did you see a lot of code with imports and exports but also other ways with require and module.exports? In this video you will learn about all ways of creating modules and why do you need it at all. So the first question. Do we have a problem at all? If we take a simple javascript file and load it in browser than all variables that we will create in root level of our file will become global. So it's fine to create varibles in functions because they will be isolated there but not just like this. var a = "a"; because in this case we are polluting global namespace. And you might say well it's not a problem it's our project. The problem is that if something is global anybody can change it accidentally and everything is broken. The first way of solving this was immediately invoked function expressions. As I already said we don't care about functions because all varibles are isolated inside that. We can use this approach by wrapping our whole code in a self execute function. (() => { var a = "a"; console.log("a", a); })(); So this is a arrow function without a name which we call directly. The only important thing is additional round brackets which we need to be able to call this function. If we check now in browser we don't pollute a global namespace. Everything is isolated inside this function. But the problem is now how we organize things if we have 10 of 20 files. Sure we can wrap every file with self executed function but how we can comfortably use a function from one file in other file. It becomes complex and not comfortable quite fast. At some point CommonJS modules were created. What is the idea? Each file is own isolated module out of the box and we can specify what we want to export from it to use in other modules and each module can import what it needs. What is also important is that it allows us to define the entities in different modules with the same name. Because they are fully isolated are even if we export the same names it's not coming to global namespace. In nodeJS until now we have exactly this approach. Let's check on the example. foo.js const getFullName = (name, surname) => { return name + " " + surname; }; module.exports = getFullName; bar.js const getFullName = require("./foo"); console.log("getFullName", getFullName("moster", "lessons")); If we write in console node bar.js We will get our full name. So some important things here. Both bar and foo are fully isolated. When we want to use something from other module we need to require it. The only way to get something from other module is if that module (in our case foo) exports it. For this we must define it in module exports. What you might ask at this point: "What do we do if we need to export several things?". This is completely valid and possible. const getFullName = (name, surname) => { return name + " " + surname; }; const getSurname = (name, surname) => { return surname; }; module.exports = { getSurname, getFullName, }; We can just export an object will whatever we need to export. Or we can write it with exports notation. foo.js exports.getFullName = getFullName; exports.getSurname = getSurname; bar.js const foo = require("./foo"); console.log("foo", foo.getFullName("monster", "lessons")); As you can see we are requiring a full module here as an object and get all things that we exported at an object. The super important thing to remember is that require is just a function. Which means we can do with it whatever we want. For example put inside functions or conditions. if (1 == 1) { const foo = require("./foo"); console.log("foo", foo.getFullName("monster", "lessons")); } So this is just a function and this module will be required only if condition is true. One more nice thing is to use destructuring to get directly local variables instead of a module. const { getFullName } = require("./foo"); console.log("foo", getFullName("monster", "lessons")); So here we directly get a local function getFullName without a module. It's quite handy. So where you can find CommonJS modules? In all nodeJS applications by default if it was not made more complex with babel or other things that can give you other type of modular system. Also in some frontend projects depending how they were done but much rarely. The next thing that came after common js module are es6 modules. They have the similar approaches but solve problems a bit differently. Actually all new browsers support es6 modules. bares6.js import getFullName from "./fooes6.js"; console.log("foo", getFullName("monster", "lessons")); fooes6.js const getFullName = (name, surname) => { return name + " " + surname; }; const getSurname = (name, surname) => { return surname; }; export default getFullName; So I copied 2 files and change them a bit. Instead of require we used import syntax. To make a single export instead of module.exports we have export default. Now we need to specify in the script that we want load it as a es6 module. <script src="./bares6.js" type="module"></script> So here we added type=module for the import. But here is a problem. I just opened in browser my index.html like a file. And it won't work with module. We get an error Access to script at '' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https. To make everything working we must serve an index.html at localhost instead. We can do it quite easy with npm package which is called serve. npm install -g serve serve As you can see now we can just to localhost:5000 and see the same page. And in this case it works and we can see out console.log. If we want to export several things from a module we can use export word. export const getFullName = (name, surname) => { return name + " " + surname; }; export const getSurname = (name, surname) => { return surname; }; And in the same way with destructuring we can get the same exported functions. import {getFullName} from "./fooes6.js"; console.log("foo", getFullName("monster", "lessons")); So this is how use are using the newest module system. export or export default and import. Now the most important question what is the difference between commonJS modules and es6 modules. Why es6 modules were invented and are they better. The main difference is that es6 modules are static and commonJS modules are dynamic. Which means you can nest imports of es6 modules. You can't put them inside functions or conditions. They are allowed only in root of the file. It's because require works in runtime and imports in parsed time. Obviously in parse time parser can't know if our statement is true or false. But this is a benefit. Es6 modules throw errors in parsed time not in runtime so much earlier. Also all imports are hoisted. This means that they are moved to the top of the file. Exactly like var properties works. Which means they are available for the whole file at the beginning. Require on the other hand is only available after it was required. We can import only from string literal. This means that we can't somehow calculate what module we import or write anything else except of string on the right. But it's all possible with require where we can calculate what we are importing and provide there whatever we want. And the last question that might bother you "Why then we still have CommonJS in Node if es6 is newer and better?". Because NodeJS is huge and complex and it's not that easy to migrate everything to the new module system. Just to remember. The biggest benefit of es6 modules compared to CommonJS is that they are static. This is why you know exactly what you imports. This is why it's better for tooling and static analysis of the code. So this what everything that you need to know about modules in javascript world. Also if you want to improve your programming skill I have lots of full courses regarding different web technologies.
https://monsterlessons-academy.com/posts/require-vs-import-javascript
CC-MAIN-2022-40
refinedweb
1,373
67.86
Java Syntax – A Complete Guide to Master Java In this Java Tutorial, we will learn about Java Syntax. So let’s start!!! Keeping you updated with latest technology trends, Join DataFlair on Telegram What does Syntax mean? Well, simply put, syntax is a particular format for writing commands in a programming language. Every language has its individual syntax. Without proper knowledge of syntax, it would be difficult to generate desired output from a programming language. Syntax are also referred to as the language of the computer. Java Syntax Java syntax is similar to C and C++ because it comes from them. So, let’s dive into the depths of syntax in Java! As soon as a Java program starts, it has package. A package consists of many classes, each consisting of functions,variables and methods. We start with knowing the syntax for identifiers in Java. 1. Identifiers Identifiers are the names given to entities such as classes,variables,functions to uniquely identify them throughout the program. They contain: - Underscore( _ ) and dollar($) (only special characters allowed in naming identifiers.) - Unicode characters such as numbers,alphabets. 2. Keywords Keywords are the identifiers which have special meaning to the compiler. These cannot be used to name variables,classes, functions etc. These are reserved words. Some of the keywords are: a. abstract – This keyword specifies that the class is an abstract class. b. boolean– This is a data type specifier which mentions that a particular variable is boolean. c. byte– this is a data type specifier which specifies a particular variable to be of byte type. d. Case– a switch case keyword which specifies program to be performed if a particular case is satisfied e. catch – during a throw case of error handling catch encloses actions to be performed if exception occurs f. break– The break keyword breaks the control out of a loop g. Void – this keyword renders a method non-returnable h. char– This is a data type specifier which specifies that the variable is of character type i. Class– This keyword specifies the creation of a new class followed by a class name. j. Extends– This is used to indicate that the class mentioned after it is the derivation of a superclass. 3. Literals These are the identifiers which have a particular value in itself. These can be assigned to variables. Literals can also be thought of as constants. These are of different types such as numeric, characters, strings etc. a. Numeric Literals For numeric literals there are 4 kinds of variations: i. Decimal(Any number of base 10), Example- 87,53 ii. Binary(Any number with a base 2), Example- 1011,110 iii. Octal Point(Any number with base 8), Example= 1177 iv. Hexadecimal Point(Any number with base 16), Example- A54C b. Floating point Literals We can specify the numeric values only with the use of a decimal point(.). These numbers represent fractional numbers which cannot be expressed as whole integers. For Example: 10.876 c. Character Literals These are the literals which deal with characters i.e inputs which are not numeric in type. i. Single quoted character– This encloses all the uni-length characters enclosed within single quotes. Example- ‘a’,’j’. ii. Escape Sequences– These are the characters preceded by a backslash which perform a specific function when printed on screen such as a tab, creating a new line, etc. Example-’\n’ iii. Unicode Representation– It can be represented by specifying the concerned unicode value of the character after ‘\u’. Example- “\u0054’ 4. Comments in Java Comments are needed whenever the developer needs to add documentation about a function which is defined within the program. This is to enhance the code-readability and understandability. Comments are not executed by the compiler and simply ignored during execution. The comments are of the following types: a. Single Line Comments in Java These comments, as the name suggests, consist of a single line of comment generally written after a code line to explain its meaning. They are marked with two backslashes(//) and are automatically terminated when there Is a new line inserted in the editor. For Example: int i = 6; String s = “DataFlair”; // The value of i is set to 6 initially.The string has value “DataFlair” b. Multi Line Comments in Java These comments span for multiple lines throughout the codebase. They are generally written at the begiinning of the program to elaborate about the algorithm. These are also used by developers to comment out blocks of code during debugging. They comprise of a starting tag(/*) and an ending tag(*/) For Example: class Comment { public static void main(String[] args) throws IOException { /* all this is under a multiline comment These wont be executed by compiler Thank you*/ } } c. Documentation Comment The javadoc tool processes these comments while generating documentation Basic structure of Java program There are two basic parts of a Java program namely, Packages and Main Method. 1. Package This is the same thing as a folder in your computer. It contains classes,interfaces and many more. It organizes the classes into namespaces. The classes which are of the same package can access each other’s protected and private members. They are generally imported by using the import keyword i.e, import java.util.* where we are importing java’s util package 2. Main Method The main method marks the entry point of the compiler in the program. The main method must always be static. For Example: public class DataFlair { void teachJava() { System.out.println(“Teaching Java by DataFlair”); } public static void main(String[] args) throws IOException { System.out.println(“In main”); DataFlair ob = new DatFlair(); ob.teachJava(); } } Output: Teaching Java by DataFlair The compiler first executes the main method and then the object method. 5. Control statements The syntax of control statements in Java are pretty straightfoward. Let’s take a deeper look into the control statements in Java. a. Conditional Statements These statements are purely based on condition flow of the program. Its divided into the following 3 parts i. if statement The statement suggests that if a particular statement yields to true then the block enclosed within the if statement gets executed. if (condition) { action to be performed } ii. if else statement This statement is of the format that if a condition enclosed is true then the if block gets executed. If not the else block gets executed Example: if (condition) { action1; } else { action2 } iii. Else if statement This statement encloses a if statement in an else block. Example: if (condition) { action 1 } else if (condition2) { action 2 } iv. Switch case The switch case is used for multiple condition checking. It’s based on the value of the variable. The value of the variable mentioned marks the flow of the control to either of the case blocks mentioned. Example: switch (var_name) case value1: action1; break; case value2: action2; break; default: action3; break; b. Iteration Statements These are the statements which are primarily known as loops in programming which run a particular set of programs a fixed number of times, Some of the types of iterative statements are: i. For loop The for loop is responsible for running the snippet of code inside it for a predetermined number of times. Example: for (i = 0; i < 5; i++) { System.out.println(“Hi”); } This prints “Hi” 5 times on the output screen ii. While loop This type of loop runs indefinitely until the condition is false Example: while (i < 6) { System.out.println(“Hi”); i++; } This prints Hi on the screen five times until the value of i becomes 6 iii. Do-while loop This is the same as the while loop. The only difference lies in the fact that the execution occurs once even if the condition is false. Example: do { System.out.println(“Hi”); } while ( i > 6 ); c. Control Flow Statements/Jump Statements Sometimes we need to discontinue a loop during execution. i. Break statement This breaks the nearest loop inside which is mentioned. The execution continues from the next line just when the current scope ends. ii. Continue Statement This continues the execution from the next iteration of the loop and skips the current execution. Example: while (i < 10) { if (i == 3) continue; i++; } This prints all the values from 0 to 9 except 3 iii. Return statement The return statements are generally useful in methods when returning a value when the function is done executing. After the return statement executes, the remaining function does not execute. 6. Exception Handling in Java Exception handling is important to custom output the errors during the unfortunate case of an error occurrence. The syntax of the exception handling is fairly simple and structured. It goes as below: try { // Code block within which error can occur } catch(Exception e) { //Code block to perform when error thrown } Finally { //Code to be executed after the end of try block. This block is executed even if there is no error } There is a special keyword called throws, it is useful to throw custom exceptions. For Example- throw new ArithmeticException(); Try: This block houses the code which is responsible for an error thrown. Generally programmers enclose the code which they think may throw an error in the try block. Catch: This block houses the code to be performed when a particular exception is found. There can be custom messages defining what kind of error has occurred for better documentation and flow of the program. Finally: The finally block executes whether or not there is any error faced by the compiler. This part is generally used to enclose the code that has to be executed irrespective of the errors occurred during compilation/execution of the program. Example program to evaluate exception handling in Java import java.io. * ; class ExcptionHandle { public static void main(String[] args) throws IOException { int a = 10, b = 0; int c; try { c = a / b; } catch(Exception e) { System.out.println(e); //TODO: handle exception } } Output: 7. Operators in Java As the name suggests, operators are the ones for performing operations on two or more entities. They are of multiple types as below: a. Arithmetic These are the operators which are solely for performing arithmetic operations . These include addition (+), subtraction(-), multiplication (*), division (/), modulo(%) and many more. b. Relational These are the operators which obtain the relation between two different entities in a program. These include less than(<), greater than(>), less than or equals to(<=), greater than or equals to(>=) ,equals to(==), not equals to(!=) Example: if (a < b) { System.out.println(“A greater”); } c. Bitwise These operators are useful for performing bitwise operations on an entity. These include AND(&), bitwise OR(|), bitwise XOR(^), bitwise complement (~), bitwise left shift(<<) and so on. Example: (A&B) will give 12 if a = 0000 and b= 1100 d. Logical These operators are useful to check the logic of a particular operation of two operands. These include Logical AND(&&), Logical OR(||), logical NOT(!) and so on. For Example: if (a == 6 && b == 5) e. Assignment These operators are responsible for assigning variables to variables. These include equal(=),add AND(+=), subtract AND operator(-=) and so on. Example: int x = 65; int y += 6 int y+=6(equivalent to int y=y+6;) 8. Object in Java Objects are created from classes in Java. Once we define a class, we can create the object of a class by the following simple syntax. These are the instances of the class: < class - name > <object - name > =new < class - name of instance creation > () Example: DataFlair java = new DataFlair(); 9. Class in Java Classes generally start with the class name which has its first letter capital. Generally the case is CamelCase for class names. It has a very simple syntax as below: class < Class - name > { instance variables; class method1() {} class method2() {} } //end class Example: class DataFlair { int a; void teach() { System.out.println(“Learning java from DataFlair”); } } 10. Methods in Java Methods or functions are specific entities which return a value only when they are called. They have a syntax similar to classes. < return type > < function - name > { action1; action2; } For Example: void print() { System.out.println(“hey I am learning Java at DataFlair”); } 11. Interfaces Interfaces are a collection of abstract methods in Java. We will learn more about Java in the following articles. We define interfaces as below; interface < interface - name > { static functions; abstract methods; } Example: interface DataFlair { void teach(); static void evaluate(); } 12. Access modifiers Access modifiers as the name suggests, limits the access of the entities they are defined with. The access modifiers used by Java are: a. Public – Accessible to every other class or interface. There is no restriction of access. b. Private– This keyword renders all entities to be accessible only inside the class they are declared. c. Protected– The protected members of the class are accessible to classes within the same package or subclasses of different packages. d. Default– If no access modifier is mentioned then the default access modifier is invoked. This limits the access of the particular entity within the same package. For Example: public int a=8; 13. Arrays Arrays are consecutive data items of the same datatype. They have a fairly simple syntax of declaration. If the array has to be declared explicitly it has the syntax of: < data type > <array - name > [ < array - size > ] = { data1, data2, data3... }; For Example: int arr[3] = { 1, 2, 3 }; else if the array has to be declared during runtime. < data type > <array - name > [] = new < array - name > [ < sizeofArray > ] Example: int arr[] = new int[10]; 14. Variables The variables concept has been explained in the following articles,however the syntax of variables is simple and easy to learn. Java Syntax for variables: < data type > <variable - name > Example: String s = ”DataFlair”; 15. Datatype The datatypes come before variables to define the type of data they would be storing. These include int,short,byte,float,double; Syntax < datatype > < var - name > Example: int b = 12; 16. Compiling and Executing a Java Program Once we have written a Java program and saved it, we need to compile and execute it by the following methods. - Open up a CMD window on the saved location by <Shift+right-click> and then select your configured CLI, i,e CMD or powershell. If you are using any other OS like ubuntu or Linux, open up a terminal and navigate to the directory in which you have saved java program. - Next type in javac <filename.java> - follow that by typing java <filename> Example: javac DataFlair.java (This compiles the file and lets us know if there are errors. ) java DataFlair (if no errors are found run this command in CLI) Summary Syntax are important as they are the language which the compiler understands. If the syntax is incorrect even the fastest algorithms can come to a standstill. So we must strengthen our concepts of Java syntax before proceeding further into the concepts of Java. Do share DataFlair Google Rating if you like the article. I am about to complete my engineering soon and I found this blog to be very informative and enlightning. Post reading it, I got valuable insights into my field; which would be useful going ahead. Thank you so much for basic java study material. The Java compiler. When you program for the Java platform, you write source code in .java files and then compile them. i am glad to leave a comment except more articles in future. chicle the selenium tutorial for update knowledge on selenium. Hi Gowsalya, Thank you, for commenting on “Java Syntax Tutorial”, we are glad readers like you share their knowledge with other readers. Keep Learning and Keep Sharing knowledge. Regard, Data-Flair Thanks anyway Thanks hurtchriss, for taking time and giving us your valuable feedback. Keep Visiting Data Flair for more Java Tutorials. why does it show II instead of || ? Hello Ryan, Nice Catch, thanks for correcting us. It was a typo mistake and we made the necessary changes. Nice and comprehensive tutorial I noticed this while compiling example 2.3 “int variable4 = 0b2222;// binary form” However the code in the output is different. Can you please explain The are some errors in the examples. int variable2 = 5463; // has nothing to do with octal should be: int variable3 = 05463l likewise b222 is not a binary value. Please replace with 0b101 Want learn how picture are created, like Control Statements(picture is good). Could you please provide info . Tutorial is having awesome content.
https://data-flair.training/blogs/basic-java-syntax
CC-MAIN-2020-40
refinedweb
2,734
57.98
How can I change the user's password in openstacksdk? I check openstack-sdk source code, I want to change the user's password, and I saw this code in openstack/identity/v3/_proxy: (line656) def update_user(self, user, **attrs): """Update a user :param user: Either the ID of a user or a :class:`~openstack.identity.v3.user.User` instance. :attrs kwargs: The attributes to update on the user represented by ``value``. :returns: The updated user :rtype: :class:`~openstack.identity.v3.user.User` """ return self._update(_user.User, user, **attrs) So, in my project I change the password, use this code: conn.identity.update_user({"password":new_password}) # attention, if I give the user_id to it, it will report error, says: requires 2 args, but 3 given. Use my code. it do not report error, but seems it did not change the password, because I use the new password to login, it will login fail, and I also tried use the dashboard, can not login too. So, how can I change the password correctly? Thanks for your time in the midst of pressing affairs.
https://ask.openstack.org/en/question/110614/how-can-i-change-the-users-password-in-openstacksdk/
CC-MAIN-2019-43
refinedweb
182
65.32
Updated 5 Oct 2019. Also valid for conversion to S/4HANA 1909 This blog is for the detailed steps for Readiness Check (RC) 2.0 for step t2 of conversion to S/4HANA 1809FPS0, FPS1 and FPS2. Readiness Check is an optional step and is a high level analysis to get a Results Dashboard and also download to a Results Document with details of Active Business Functions, Add-On Compatibility, Custom Code Analysis, Recommended Fiori Apps, S/4HANA Sizing, Simplification Items, Business Process Analytics and Data Volume Management. Download the Readiness Check User Guide for reference Please find other blogs as follows: Please find the process flow diagram with application of notes as below. All steps are according to Note 2758146 – SAP Readiness Check 2.0 & Next Generation SAP Business Scenario Recommendations version 34. Click on Show Changes for revisions. STEP 1: PREPARATION De-implement any of the notes if they were implemented earlier. In case of ABAP class inconsistency, please clean up the class header in transaction SE24, specify the object and select Utilities => Regenerate sections in the change mode. If you face issues with above, please open OSS message. If you try to download latest version of note and apply, it may cause a bigger issue with a lot of time wasted later on. You should have 6-8 weeks of transaction history (tcode ST03) in the production system or the system in which you want to execute the application analysis. Otherwise, SAP Readiness Check for SAP S/4HANA can return inaccurate or incomplete results. If you have SAP Note 2310438 implemented in your system, de-implement note 2310438 first. STEP 2: SET UP CUSTOM CODE ANALYSIS Apply Note 2185390 – Custom Code Analyzer (includes manual steps) This note will download other dependent notes, and then some other dependent notes and this goes on. Number may vary depending on your patch level. The Note requires Manual steps as below: As per Manual steps above, In SE80 create Package SYCM_MAIN Create SubPackage SYCM_ANALYSIS Confirm Manual step. Then the note application will prompt for another manual step depending on your SP level, its only applicable to the narrow range of SAP_BASIS SP08 to SP11 only. In SE11, create table WBINDEX You will require the developer key and object access key. Add field PROGNAME and confirm manual step. In SA38, run SAPRSEUC in background now or after the optional step to run it in parallel to improve performance. This is a long running job and runs single threaded by default. TIP: Please note it is not required to run the job SAPRSEUB, which updated Where-Used list for the whole system, the SAPRSEUC updates Where-Used list for Customization only. Job SAPRSEUB used to run several days like 11 days at one customer. The good thing is if it is cancelled it continues from the point it was cancelled with a overhead or 20-30 mins for every restart. If you have issues in running this job the component for OSS message is BC-DWB-CEX. STEP 3: (OPTIONAL) IMPROVE PERFORMANCE OF JOB SAPRSEUC Apply note Note 2667023 – Runtime of job EU_INIT or SAPRSEUB/SAPRSEUC, performance Manual steps are in Note 2228460 – Runtime of job EU_INIT, SAPRSEUB, performance You will have to register developer if needed, and register object to get Access key and fill in as below: Add 2 fields as below: In SE38, BSP_INIT_INDEX_CROS, Variant , Change, add text elements as below. there are 7 programs and 1 class with text elements to be updated. You may also be prompted for Programs WDY_INIT_INDEX_CROSS, SAPRSEUI, QSC_INDEX_ALL_PROXIES to add text elements. After applying the note, job runs with one background process and uses number of dialog processes as defined in (1) table RSEUPACTRL as below. (2) Add column ALLSERVER, if it is blank, (3) Mark X for parallel processing and (4) define percentage of dialog processes to be used according to timezone. If this is sandbox that you want to finish the job as soon as possible you could jackup these percentages. You can now schedule the job SAPRSEUC if you decided to do the optional steps. STEP 4: ENABLING S/4HANA SIZING DATA COLLECTION Apply Note 1872170 – ABAP on HANA sizing report (S/4HANA, Suite on HANA…) – cannot be implemented in SNOTE. Please read the note. Using tCode SNOTE apply Note 2734952 – HANA memory Sizing report – Advanced correction 12 So far this is the latest, if there is later note please apply that note instead of 2734952. Please note: - Note requires minimum ST-PI 740/SP02 or 700,710/SP12 to apply the note. - If you don’t want to apply ST-PI, instead of applying this note, implement report ZNEWHDB_SIZE as described in Note 1872170 – ABAP on HANA sizing report Please note that if you take this option, there are 3 programs and function module to be created/updated to latest code. TIP: ST-PI is independent and doesn’t need other components or stack.xml to apply, this would save lot of manual work. IMPORTANT: In the Note 2758146 it is mentioned that to include sizing in analysis report dashboard, it is recommended to have ST-PI 740/SP07, 700,710/SP17 In tcode SE38, check that program /SDF/HDB_SIZING is available and you can even run it for test now. Please use below for troubleshooting if you run into issues. The same program runs later on when scheduling analysis and the job RC_COLLECT_ANALYSIS_DATA is run as per STEP 12. This is related to 2 jobs we launch in step 13 – TMW_RC_HANAS_DATA_COLL & /SDF/HDB_SIZING_SM. If you have issues in running this job the component for OSS message is XX-SER-SAPSMP-ST. STEP 5: ENABLING SIMPLIFICATION ITEM CHECK Apply Note 2399707 – Simplification Item Check. This can be applied quickly. There are no Manual corrections. This note helps run 1 job we launch in step 13 – TMW_RC_SITEM_DATA_COLL. If you have issues in running this job the component for OSS message is CA-TRS-PRCK STEP 6: ENABLING BUSINESS PROCESS ANALYTICS ANALYSIS Apply Note 2745851 – Business Process Improvement Content for SAP Readiness Check 2.0 and Next Generation SAP Business Scenario Recommendations Content. This note should be applied quickly in the productive client. There are no Manual corrections This note is related to 1 job we launch in step 13 – TMW_RC_BPA_DATA_COLL. If you have issues in running this job the component for OSS message is SV-SMG-MON-BPM-ANA. STEP 7: ENABLING IDOC ANALYSIS Apply Note 2769657 – Interface Discovery for IDoc as part of Readiness Check You need minimum ST-A/PI 01S_700/01S_731. Apply using SAINT. If you have issues in running this job the component for OSS message is SV-SMG-MON-BPM-DCM. STEP 8: ENABLING DATA VOLUME MANAGEMENT ANALYSIS The note can be implemented for ST-PI 740 SP01 700/710 SP09 Apply Note 2612179 using SNOTE. As per manual instructions folow this sequence, - SNOTE apply Note 2611746 – DVM Create objects for APIs for triggering and monitoring ST14 analyses - tCode SE38 run program NOTE_2611746 - SNOTE will apply Note Note 2612179 – DVM API to trigger and monitor DVM ST14 analyses for Readiness Check - In SNOTE apply Note 2693666 – Enhance error handling when collecting DVM ST14 data for SAP S/4 HANA Readiness Check TIP: If there are any errors in DVM data collection, refer Note 1159758 -Data Volume Management: Central Preparation Note and also Note 2721530 – “FAQ for collecting DVM data during S/4 HANA Readiness Check. This note is related to 4 jobs we launch in step 13 – TMW_RC_DVM_DATA_COLL, BP_APPLICATION_ANALYSIS_01, DANA_ANALYSIS, TAANA_ANALYSIS. If you have issues in running this job the component for OSS message is SV-SMG-DVM. STEP 9: SETTING UP READINESS CHECK Apply Note 2758146 – SAP Readiness Check 2.0 & Next Generation SAP Business Scenario Recommendations This prompts for applying Note 2185390 – Custom Code Analyzer and you already did it in earlier step, so confirm. We have already applied this note. The job related to Readiness Check master report we launch in step 13 is RC_COLLECT_ANALYSIS_DATA. If you have issues in running this job the component for OSS message is SV-SCS-S4R. STEP 10: RUN BACKGROUND JOB IN DEV SYSTEM TO DOWNLOAD METADATA INFO In SE38 run background job SYCM_DOWNLOAD_REPOSITORY_INFO. Define the variant to restrict to the required namespace. Then run the program in background using this variant. If the where-used list index for customer objects is not up to date you will get error below: Please refer Note: 2655768 – Custom Code Analyzer – The where-used list index for customer objects is not up to date STEP 11: MONITOR BACKGROUND JOB AND DOWNLOAD ZIP FILE In case you get below dump: After the job is finished, in SE38 run SYCM_DOWNLOAD_REPOSITORY_INFO again and click on button to Download Zip file… The solution is – Enter tCode SE38, Program LZEHPRC_CP_BB20UXX, click on Change (You will need developer access). Go to menu option Utilities, Settings. select option above, click on OK, Save and Activate the program. Unfortunately you have to Rerun the job from the beginning. STEP 12: TRANSPORT 7+ NOTES TO PRODUCTION In tCode SE01, release transport and using tCode STMS import into QAS and PROD systems in the landscape. STEP 13: RUN BACKGROUND JOB IN PROD SYSTEM In the productive client, tCode SE38 – RC_COLLECT_ANALYSIS_DATA (1) select target S/4HANA Version, (2) Schedule Analysis, (3) Immediate and (4) ok. As per the note 2758146, if you do not have the min ST-PI 700/710 SP17 or 740 SP07, then unmark the checkbox for HANA Sizing Data. This will trigger number of background jobs as shown in next step. You should get message that Job RC_COLLECT_ANALYSIS_DATA is scheduled, and a series of messages. TIP: If there are any errors in DVM data collection, refer Note 1159758 -Data Volume Management: Central Preparation Note and also Note 2721530 – “FAQ for collecting DVM data during S/4 HANA Readiness Check. If you get this error, apply Note 2443236 – SAP Readiness Check for SAP S/4HANA Business Process Improvement Content and also the needed ST-A/PI through SPAM. STEP 14: MONITOR BACKGROUND JOB AND DOWNLOAD ZIP FILE There are various jobs launched in order as below and you must check job logs to ensure the data was collected properly. Job RC_COLLECT_ANALYSIS_DATA is the main job to collect analysis data. Job TMW_RC_BPA_DATA_COLL is scheduled to collect Business Process Analytics data Job TMW_RC_HANAS_DATA_COLL is scheduled to collect HANA Sizing data Job TMW_RC_DVM_DATA_COLL is scheduled to collect Data Volume Management data Job /SDF/HDB_SIZING_SM is scheduled to collect data for sizing Job TMW_RC_SITEM_DATA_COLL is scheduled to collect Simplification Item relevance check data Job BO APPLICATION ANALYSIS NN scheduled for DVM triggers TAANA and DANA Analysis Job TAANA ANALYSIS is scheduled for large Table Analysis Job DANA ANALYSIS is scheduled for Data Volume Management Analysis After the jobs are finished, in SE38 run RC_COLLECT_ANALYSIS_DATA again and click on button to Download Analysis Data as shown in previous step. ERROR SITUATION 1: If the job TMW_RC_HANAS_DATA_COLL gives error – internal Error! Set GF_INCLNO in 00F_SET_INCLNO, refer SAP Note 2809344 – Job TMW_RC_BPA_DATA_COLL is cancelled with error: “internal Error! Set GF_INCLNO in 00F_SET_INCLNO” which suggests to apply Note 2557474. STEP 15: GENERATE READINESS CHECK RESULTS DASHBOARD In SAP Launchpad (S-USER is required) url (1) (2) Start New Analysis, (3) Analysis Name, (4) Customer, (5) Browse, (6) Select zip file RC2AnalysisDataSIDyyyymmdd.zip, (7) & (8) Terms of use, (9) Create. Once the analysis is in ready state (about an hour), Open the analysis and use the zip file generated from program SYCM_DOWNLOAD_REPOSITORY_INFO and click (1) icon on the top right, (2) Browse, (3) select filename S4HMigrationRepositoryInfoSID.zip, (4) Terms of Use,(5) Update . You can click on wheel (1) and switch on (3) for Update & Delete to input details of (3) email id click on Save (4). You can click on + to add more email id’s. You can view the Results Dashboard as shown below. Above steps complete the readiness check. Readiness Check should be used as a interactive dashboard which has the greatest benefit of online team collaboration. It is now possible to download the Readiness Check as a word document like in Readiness Check 1.0. Customer can provide access to any Implementation Partner with P-User which can be easily created or SAP employee. The access can also be revoked as needed. ERROR SITUATION 1: In case you get the message below, it is likely that your system is not connected properly through Solution Manager to the SAP Support Portal. Please refer Note 2408911 and blog. Use component for Readiness Check: SV-SCS-S4R to report problems during preparation or execution. STEP 16: (OPTIONAL) ENABLE ATC CHECK RESULT EXPORT Please follow the elaborate process to apply notes in Checked System as per blog – Conversion to S/4HANA 1809FPS0 – t5 – Custom Code Migration Apply the required 4+ notes in checked system, Apply 3+ notes in Central Checking system which should be Netweaver 7.52 or higher. In the Central Checking system run tCode ATC, Runs, Manage Results. In the ATC Results Browser select (1) the result series, Right Click and select (2) Export File for, (3) SAP Readiness Check for S/4HANA”. You will doenload a file named <SID>_atc_findings.zip You can get the results in the Custom Code Analysis tile as shown below: If you have issues in running this job the component for OSS message is BC-DWB-CEX. STEP 17: (OPTIONAL) ENABLE CONSISTENCY CHECK RESULT EXPORT Apply Note 2502552 – S4TC – SAP S/4HANA Conversion & Upgrade new Simplification Item Checks There is an elaborate process to apply this note. Please refer the steps 1-5 in the Simplification Item Check blog – Conversion to S/4HANA 1809FPS0 – t4 – Simplification Item-Check You can run the program RC_COLLECT_ANALYSIS_DATA selecting all items or below. Download the zip file and simply click on Update Analysis icon to upload the zip archive update the analysis. Dashboard will retain old data for other items and update the Simplification Item consistency check. If you have issues in running this job the component for OSS message is CA-TRS-PRCK. You can also do this for example if only sizing data is required to be updated => apply the latest sizing note and run the program RC_COLLECT_ANALYSIS_DATA with checkmark on Hana sizing and then click on Update Analysis to upload the zip archive. LANDSCAPE CONSIDERATIONS: There is no option available to create the Readiness Check 2.0 through Solution Manager. As shown in the main graphic, you could run analysis related to Custom Code on DEV system so you analyze code that has never gone into production. If you want to analyze only code that has gone into production please run analysis related to Custom Code in PROD. Another reason for running Custom Code Analysis job in DEV system is where used index may take a while in PROD system. TIP: During your regular maintenance patch update, please include ST-PI & ST-A/PI, that way some of the required notes are already applied. Both these OCS Packages ST-PI and ST-A/PI do not need stack the xml and can be applied separately. OTHER REFERENCES: Readiness Check Help Portal Readiness Chck User Guide Note 2758146 – SAP Readiness Check 2.0 & Next Generation SAP Business Scenario Recommendations Readiness Check Jam Group Readiness Check video Expert Guided Implementation (EGI) <===== sessions on SAP Learning Hub, SAP Enterprise Support Edition* *Only SAP Enterprise Support customers are eligible to attend this remote training workshop. Please note that to access the SAP Learning Hub, edition for SAP Enterprise Support, a one-time registration is required. A detailed step-by step guidance can be found here. FAQ blog – SAP Readiness Check 2.0 for SAP S/4HANA – FAQ & What’s New in Releases Thank you. Hope you enjoyed the blog ! Mahesh Sardesai Product Expert – S/4HANA Hello Mahesh, Great effort on highlighting all steps for Readiness Check 2.0. But I would like to highlight few things here. The last screenshot of dashboard, is really from new application of SAP Readiness check 2.0? Because I got different visualization in dashboard. I think for SAP Readiness Check 2.0 we have to use URL, not as mentioned in your steps. Also we first need to upload only RC_COLLECT_ANALYSIS_DATA file while creating analysis report (there is no provision to upload both report at the same time) and once it is in ready state we upload SYNC_DOWNLOAD_REPOSITORY_INFO by clicking on the left hand icon of “update analysis”. It will update the report. I feel steps mentioned here are bit misinforming as it highlights some part of SAP Readiness Check 1.0 as well. Regards, Dennis Hi Dennis, I click on publish too soon when it wasn’t ready. It has been updated now. Thanks. Hi Mahesh, I came to step 16 without any problem and while uploading my RC2AnalysisDataRRR20190530.zip, I received this warning: “Analysis creation failed: The uploaded file is not valid. Check that the file is downloaded using report RC_COLLECT_ANALYSIS_DATA.” I don´t know what to do or where to find the reason. Can you help me please? Best regards Slavomír Hronec Hi, There has been revision to the Note 2758146 (version 18) on 29 May. Please download version 18 and run the analysis again. Hi Mahesh, I executed a readiness check 2.0 and I got some problems: thank you in advance Simone Hi Simone, have you get any reply for the topic “why don´t get any informations in section business process discovery”? We have the same problem but I can´t get any information how to solve that issue. Thanks & Regards, Manuel Sorry Manuel, but my issue is not solved. If I’ll discover the cause, I’ll share with you. Regards Simone Hi Simone, Please note that this particular note is to be applied in productive client and if you have applied it in client 000 it may not pull data. Also please note the main graphic the programRC_COLLECT_ANALYSIS_DATA has to be run in productive client not 000 or other client. Thanks, Thank you Mahesh for your reply. About first point, I charged the productive statistics on TST system and I got the infos. About the second, ok: I’ll analyze the summary from the ZNEWHDB_SIZE log. On referring to point 3, I applyed the suggested sapnote into the used client, and executed the RC* tool on correct client, but the business process analysis is unavailable from both readiness check, because the bpa.xml is quite empty. Simone HI Mahesh is it possible to run the readiness check in a CCS (SAP Utilities) version 6.03? SAP ECC is installed in another instance and will be kept as is. In CCS there are thousands of developments and readiness would help in the evaluation another question: my customer is live in S/4HANA 1511. Can I run readiness check? thanks a lot in advance Bruno Hi, Readiness Check is primarily for Conversion of ERP to S/4HANA. It looks like you would like to analyse custom code and it would be good to do the check for Custom Code Migration Worklist and this will require Netweaver 7.52 system. You can do the readiness check for upgrade to get summary report but being already on S/4HANA the benefit here is reduced. You could prepare the simplification list itself by applying note 2502552 as you already have TCI note in the system, it may be little effort to get to the final iist. Dear Mahesh thank you very much all the best Bruno Hi all, do you – really?! – call this a decent “Readyness check”? I’d assume, that nothing is ready, i.e. prepared from the vendor. “Run simple” by delegating the work, trial and error to the customer. What a foreseeable mess… Hi Joerg, Sorry that the tool did not meet your expectations. It has been tested well with our testing team and partners. Please let us know issues you are facing so we can consider for improvement. Hi @ all, does anyone have an idea why section business process discovery don´t deliver any information? In every section of the readiness check 2.0 I receive information except for this section of business process discovery. Would be great to get an answer how to solve this issue. Thanks & Regards, Manuel Great Blog 🙂 Thank you. Is there any Blog how to implement the RC 2.0 on BW systems? Kind regards, Karsten Hi Karsten, Karsten Kautz RC 2.0 is not available for BW systems. Best regards Renaud HI , when you click on the Create Result Document , we will get the below error . HTTP Status 504 – An internal application error occurred. Request: 1234567 supportportal:supportshell Regards Prabhu Hi Allamprabhu, “Create Result Document” is only valid for Readiness Check 1.0 and is available for Readiness Check 2.0. Also the old readiness check is being discontinued, so you will have to create OSS message to check if it is available. Hi, We’re pursuing the below approach for S/4 HANA conversion. Having said that, does readiness check 2.0 and simplification item checks are required to run or applicable to this scenario as well? “Selective data transition using Landscape transformation” Regards, Dheeraj Hi Dheeraj, Readiness Check is applicable to conversion scenario. However if you have ECC system you can still run it to get information on S/4HANA to know what add-ons are installed, what business functions you have activated, what simplification items are applicable specific to your scenario. Some of these may be redundant. However you have to ignore certain information that may no longer be worth using like for example sizing. Thanks for this great blog ! Result Document will be available mid-September on RC 2.0 For custom full code analysis you will need to have a 7.52 system to be able to use ABAP Test Cockpit Best regards HI Mahesh, thank you for answering my question . TMW_RC_BPA_DATA_COLL : job getting failed due to the memory issue , i have increased the memory by report : RSMEMORY , even that also the issue is not solved . internal table PROGRAM=/SSA/EKP/FORM=09F_COLLECT_DATA=LT_PURCH2_DATA IL_03 could not be further extended the amount of storage space in byews filled at termination time was Role are 11958080 Ext memory (EM) 4001312480 ASS Memory (HEP) 3999415488 Page area 32768 Maximum address space 429467295 TSV_TNEW_PAGE_ALLOC_FAILED /SSA/EKP or /SSA/EKP 09F_COLLECT_DATA Hi Allamprabhu, The error could be related to Business Process Analytics check – BPA data coll as you mentioned. Some customers have reported issue and there has been a correction on this recently. Please download latest version of changed notes and try again..
https://blogs.sap.com/2019/05/23/conversion-to-s4hana-1809fps0-t2-readiness-check-2.0/
CC-MAIN-2019-43
refinedweb
3,769
61.97
Normalization vs Standardization — Quantitative analysis Stop using StandardScaler from Sklearn as a default feature scaling method can get you a boost of 7% in accuracy, even when you hyperparameters are tuned! Let’s analyze the results - There is no single scaling method to rule them all. - We can see that scaling improved the results. SVM, MLP, KNN, and NB got a significant boost from different scaling methods. - Notice that NB, RF, LDA, CART are unaffected by some of the scaling methods. This is, of course, related to how each of the classifiers works. Trees are not affected by scaling because the splitting criterion first orders the values of each feature and then calculate the gini\entropy of the split. Some scaling methods keep this order, so no change to the accuracy score. NB is not affected because the model’s priors determined by the count in each class and not by the actual value. Linear Discriminant Analysis (LDA) finds it’s coefficients using the variation between the classes (check this), so the scaling doesn’t matter either. - Some of the scaling methods, like QuantileTransformer-Uniform, doesn’t preserve the exact order of the values in each feature, hence the change in score even in the above classifiers that were agnostic to other scaling methods. 3. Classifier+Scaling+PCA We know that some well-known ML methods like PCA can benefit from scaling (blog). Let’s try adding PCA(n_components=4) to the pipeline and analyze the results. import operator temp = results_df.copy() temp["model"] = results_df["Classifier_Name"].apply(lambda sen: sen.split("_")[1]) temp["scaler"] = results_df["Classifier_Name"].apply(lambda sen: sen.split("_")[0]) def df_style(val): return 'font-weight: 800' pivot_t = pd.pivot_table(temp, values='CV_mean', index=["scaler"], columns=['model'], aggfunc=np.sum) pivot_t_bold = pivot_t.style.applymap(df_style, subset=pd.IndexSlice[pivot_t["CART"].idxmax(),"CART"]) for col in list(pivot_t): pivot_t_bold = pivot_t_bold.applymap(df_style, subset=pd.IndexSlice[pivot_t[col].idxmax(),col]) pivot_t_bold Let’s analyze the results - Most of the time scaling methods improve models with PCA, but no specific scaling method is in charge. Let’s look at “QuantileTransformer-Uniform”, the method with most of the high scores. In LDA-PCA it improved the results from 0.704 to 0.783 (8% jump in accuracy!), but in RF-PCA it makes things worse, from 0.711 to 0.668 (4.35% drop in accuracy!) On the other hand, using RF-PCA with “QuantileTransformer-Normal”, improved the accuracy to 0.766 (5% jump in accuracy!) - We can see that PCA only improve LDA and RF, so PCA is not a magic solution. It’s fine. We didn’t hypertune the n_components parameter, and even if we did, PCA doesn’t guarantee to improve predictions. - We can see that StandardScaler and MinMaxScaler achieve best scores only in 4 out of 16 cases. So we should think carefully what scaling method to choose, even as a default one. We can conclude that even though PCA is a known component that benefits from scaling, no single scaling method always improved our results, and some of them even cause harm(RF-PCA with StandardScaler). The dataset is also a great factor here. To better understand the consequences of scaling methods on PCA, we should experiment with more diverse datasets (class imbalanced, different scales of features and datasets with numerical and categorical features). I’m doing this analysis in section 5. 4. Classifiers+Scaling+PCA+Hyperparameter tuning There are big differences in the accuracy score between different scaling methods for a given classifier. One can assume that when the hyperparameters are tuned, the difference between the scaling techniques will be minor and we can use StandardScaler or MinMaxScaler as used in many classification pipelines tutorials in the web. Let’s check that! First, NB is not here, that’s because NB has no parameters to tune. We can see that almost all the algorithms benefit from hyperparameter tuning compare to results from o previous step. An interesting exception is MLP that got worse results. It’s probably because neural networks can easily overfit the data (especially when the number of parameters is much bigger than the number of training samples), and we didn’t perform a careful early stopping to avoid it, nor applied any regularizations. Yet, even when the hyperparameters are tuned, there are still big differences between the results using different scaling methods. If we would compare different scaling techniques to the broadly used StandardScaler technique, we can gain up to 7% improvement in accuracy (KNN column) when experiencing with other techniques. The main conclusion from this step is that even though the hyperparameters are tuned, changing the scaling method can dramatically affect the results. So, we should consider the scaling method as a crucial hyperparameter of our model. Part 5 contains a more in-depth analysis of more diverse datasets. If you don’t want to deep dive into it, feel free to jump to the conclusion section. 5. All again on more datasets To get a better understanding and to derive more generalized conclusions, we should experiment with more datasets. We will apply Classifier+Scaling+PCA like section 3 on several datasets with different characteristics and analyze the results. All datasets were taken from Kaggel. - For the sake of convenience, I selected only the numerical columns out of each dataset. In multivariate datasets (numeric and categorical features), there is an ongoing debate about how to scale the features. - I didn’t hypertune any parameters of the classifiers. 5.1 Rain in Australia dataset Link Classification task: Predict is it’s going to rain? Metric: Accuracy Dataset shape: (56420, 18) Counts for each class: No 43993 Yes 12427 Here is a sample of 5 rows, we can’t show all the columns in one picture. dataset.describe() We will suspect that scaling will improve classification results due to the different scales of the features (check min max values in the above table, it even get worse on some of the rest of the features). Results Results Analysis - We can see the StandardScaler never got the highest score, nor MinMaxScaler. - We can see differences of up to 20% between StandardScaler and other methods. (CART-PCA column) - We can see that scaling usually improved the results. Take for example SVM that jumped from 78% to 99%. 5.2 Bank Marketing dataset Link Classification task: Predict has the client subscribed a term deposit? Metric: AUC ( The data is imbalanced) Dataset shape: (41188, 11) Counts for each class: no 36548 yes 4640 Here is a sample of 5 rows, we can’t show all the columns in one picture. dataset.describe() Again, features in different scales. Results Results Analysis - We can see that in this dataset, even though the features are on different scales, scaling when using PCA doesn’t always improve the results. However, the second-best score in each PCA column is pretty close to the best score. It might indicate that hypertune the number of components of the PCA and using scaling will improve the results over not scaling at all. - Again, there is no one single scaling method that stood out. - Another interesting result is that in most models, all the scaling methods didn’t affect that much (usually 1%–3% improvement). Let’s remember that this is an unbalanced dataset and we didn’t hypertune the parameters. Another reason is that the AUC score is already high (~90%), so it’s harder to see major improvements. 5.3 Sloan Digital Sky Survey DR14 dataset Link Classification task: Predict if an object to be either a galaxy, star or quasar. Metric: Accuracy (multiclass) Dataset shape: (10000, 18) Counts for each class: GALAXY 4998 STAR 4152 QSO 850 Here is a sample of 5 rows, we can’t show all the columns in one picture. dataset.describe() Again, features in different scales. Results Results Analysis - We can see that scaling highly improved the results. We could expect it because it contains features on different scales. - We can see that RobustScaler almost always wins when we use PCA. It might be due to the many outliers in this dataset that shift the PCA eigenvectors. On the other hand, those outliers don’t make such an effect when we do not use PCA. We should do some data exploration to check that. - There is up to 5% difference in accuracy if we will compare StandardScaler to the other scaling method. So it’s another indicator to the need for experiment with multiple scaling techniques. - PCA almost always benefit from scaling. 5.4 Income classification dataset Link Classification task: Predict if income is >50K, <=50K. Metric: AUC (imbalanced dataset) Dataset shape: (32561, 7) Counts for each class: <=50K 24720 >50K 7841 Here is a sample of 5 rows, we can’t show all the columns in one picture. dataset.describe() Again, features in different scales. Results Results Analysis - Here again, we have an imbalanced dataset, but we can see that scaling do a good job in improving the results (up to 20%!). This is probably because the AUC score is lower (~80%) compared to the Bank Marketing dataset, so it’s easier to see major improvements. - Even though StandardScaler is not highlighted (I highlighted only the first best score in each column), in many columns, it achieves the same results as the best, but not always. From the running time results(no appeared here), I can tell you that running StandatdScaler is much faster than many of the other scalers. So if you are in a rush to get some results, it can be a good starting point. But if you want to squeeze every percent from your model, you might want to experience with multiple scaling methods. - Again, no single best scale method. - PCA almost always benefited from scaling Conclusions - Experiment with multiple scaling methods can dramatically increase your score on classification tasks, even when you hyperparameters are tuned. So, you should consider the scaling method as an important hyperparameter of your model. - Scaling methods affect differently on different classifiers. Distance-based classifiers like SVM, KNN, and MLP(neural network) dramatically benefit from scaling. But even trees (CART, RF), that are agnostic to some of the scaling methods, can benefit from other methods. - Knowing the underlying math behind models\preprocessing methods is the best way to understand the results. (For example, how trees work and why some of the scaling methods didn’t affect them). It can also save you a lot of time if you know no to apply StandardScaler when your model is Random Forest. - Preprocessing methods like PCA that known to be benefited from scaling, do benefit from scaling. When it doesn’t, it might be due to a bad setup of the number of components parameter of PCA, outliers in the data or a bad choice of a scaling method. If you find some mistakes or have proposals to improve the coverage or the validity of the experiments, please notify me. Thanks to Dvir Cohen and Nicholas Hoernle. Bio: Shay Geller is a full time AI and NLP researcher and Masters student of AI and Data Science at Ben Gurion University. Original. Reposted with permission. Related: - Simple Yet Practical Data Cleaning Codes - Feature engineering, Explained - A Quick Guide to Feature Engineering
https://www.kdnuggets.com/2019/04/normalization-vs-standardization-quantitative-analysis.html/2
CC-MAIN-2019-26
refinedweb
1,881
55.64
The current code (5.1.0.2) will never return the number of events in the eventset unless the supplied array (and thus the size argument) is larger than the event set. The man page clearly states that the returned number may be greater than the array size if the event set does not fit in the supplied array. In particular the call PAPI_list_events(EventSet, NULL, &n) should be allowed if n=0 at the time of the call. Now, this may break some existing code out there Since I have no code that relies on the above behaviour I think we should fix the library to follow its spec and that way find out who has programmed their apps according to library behaviour and not library spec Cheers, /Nils - Code: Select all --- orig/papi.c 2013-01-15 21:44:44.000000000 +0100 +++ patched/papi.c 2013-03-21 10:12:38.999322342 +0100 @@ -5882,26 +5882,36 @@ PAPI_remove_events( int EventSet, int *E int PAPI_list_events( int EventSet, int *Events, int *number ) { + int maxEvents = *number; EventSetInfo_t *ESI; int i, j; - if ( ( Events == NULL ) || ( *number <= 0 ) ) + if ( ( number == NULL ) || ( *number < 0 ) ) papi_return( PAPI_EINVAL ); ESI = _papi_hwi_lookup_EventSet( EventSet ); if ( !ESI ) papi_return( PAPI_ENOEVST ); + /* The spec states that we always return the number of events in the event set */ + *number = ESI->NumberOfEvents; + + if ( maxEvents == 0 ) + papi_return( PAPI_OK ); + + /* We better have a valid pointer now that we are going to write stuff */ + if ( Events == NULL ) + papi_return( PAPI_EINVAL ); + for ( i = 0, j = 0; j < ESI->NumberOfEvents; i++ ) { if ( ( int ) ESI->EventInfoArray[i].event_code != PAPI_NULL ) { Events[j] = ( int ) ESI->EventInfoArray[i].event_code; j++; - if ( j == *number ) + if ( j == maxEvents ) break; } } - *number = j; return ( PAPI_OK ); }
http://icl.cs.utk.edu/papi/forum/viewtopic.php?p=2355
CC-MAIN-2016-44
refinedweb
276
67.59
0 The below code simply reads the string "This is a test" from a text file and displayes it on the console. I've deliberately placed an endline at the end of each time the string is loaded to show that the string is all that is passed to 'mystring' from 'myfile'. Is there a way in C++ to increase the number of characters picked up by 'myfile' ? Say, for the first loop of while instead of 'myfile' only picking up "This", it picks up "This i" and on the next loop it picks up the next 6 characters including white space "s a te" etc? At the moment, 'myfile' only takes in everything up to the first white space. Thanks #include <iostream> #include <string> #include <fstream> using namespace std; int main() { ifstream myfile; string mystring; myfile.open("myfile.txt"); while (!myfile.eof()) { myfile>>mystring; cout << mystring << endl; } myfile.close(); }
https://www.daniweb.com/programming/software-development/threads/466890/limiting-stream-data
CC-MAIN-2017-09
refinedweb
150
76.15
Especially since the IETF "LISP" is a misnomer; it is not a locator/identifier split. It's a global locator to site locator mapping. This was pointed out some time ago... You've presented one definition of namespace. I strongly suspect that there are a lot of other definitions floating around and that the term was being used loosely. I have not seen a lot of support for your strict definition of namespaces. However, I think that addressing Bryan, Lixia and Margaret's concern needs to be addressed by making this distinction clear. I think that avoiding the term namespace or defining what we mean by namespace will be more productive than an argument over its definition and whether we have found the clearly correct definition for our field. At least as I understand it, your proposed charter text change in this area seems to do this.
http://www.firstpr.com.au/ip/ivip/namespace/
CC-MAIN-2020-16
refinedweb
147
63.8